In [12]:
import sys
import imaplib
import email
import datetime
import yaml
import re
from bs4 import BeautifulSoup
sys.path.append('../')
import jobs2phones as j2p

In [13]:
with open('../config.yaml') as f:
    cf = yaml.safe_load(f)

In [21]:
def parse_text_message_from_email(msg):
    '''
    Gets the actual text sent to the email address by parsing it out of the email body
    '''
    text = {}
    text['sender'] = msg['from']
    if msg.is_multipart():
        for i,part in enumerate(msg.walk()):
            if part.get_content_type() =='text/plain':
                msg_body = part.get_payload(decode=True)
    else:
        msg_body = msg.get_payload(decode=True)
    msg_body.replace('\r','').replace('\n','')
   
    text['message']=msg_body
    return text


def parse_choices(choices_made):
    '''
    Takes a numbered list of choices and maps them to the relevant search criteria.
    '''
    search_criteria='';
    for choice in choices_made:
        if choice == '1':
            search_criteria='dishwasher&20philadelphia ' + search_criteria
        if choice == '2':
            search_criteria='warehouse&20philadelphia ' + search_criteria
        if choice == '3':
            search_criteria='cook&20philadelphia ' + search_criteria
    return search_criteria

def read_mailbox_and_edit_users(M):
    """
    Processes mail in order to add,edit, and remove users
    """
    Session = j2p.bind_to_database(cf['postgres_username'],cf['postgres_password'],cf['postgres_db'])
    rv, data_num = M.search(None, "ALL")
    if rv != 'OK':
        print "No messages found!"
        return
                    
    messages=[]
    for num in data_num[0].split():
        rv, data = M.fetch(num, '(RFC822)')
        if rv != 'OK':
            print "ERROR getting message", num
            return
        email_data = email.message_from_string(data[0][1])
        text = parse_text_message_from_email(email_data)
        choices_made = re.findall(r'\d+',text['message'])
        if 'stop' in text['message'].lower():
            j2p.delete_user(Session,text['sender'])
            j2p.send_text(cf['fromaddr'],cf['username'],cf['password'],text['sender'],cf['stop_message'])
            M.store(num , '+FLAGS', '\\Deleted') #This archives the message.
        elif 'start' in text['message'].lower() or 'list' in text['message'].lower():
            j2p.send_text(cf['fromaddr'],cf['username'],cf['password'],text['sender'],cf['start_message'])
            M.store(num , '+FLAGS', '\\Deleted') #This archives the message.
        elif len(choices_made) > 0:
            search_criteria = parse_choices(choices_made)
            if len(search_criteria) > 0:
                if j2p.check_user(Session,text['sender']):
                    j2p.edit_user(Session,text['sender'],search_criteria)
                else:
                    j2p.insert_user(Session,'',text['sender'],'',search_criteria)
                j2p.send_text(cf['fromaddr'],cf['username'],cf['password'],text['sender'],
                              str(choices_made) + '. ' + cf['chosen_message'])
                M.store(num , '+FLAGS', '\\Deleted') #This archives the message.

In [22]:
EMAIL_ACCOUNT = cf['username']
EMAIL_FOLDER = "INBOX"

M = imaplib.IMAP4_SSL('imap.gmail.com')

try:
    rv, data = M.login(EMAIL_ACCOUNT, cf['password'])
except imaplib.IMAP4.error:
    print "LOGIN FAILED!!! "
    sys.exit(1)

In [23]:
rv, data = M.select(EMAIL_FOLDER)
if rv == 'OK':
    print "Processing mailbox..."
    read_mailbox_and_edit_users(M)
    M.close()
else:
    print "ERROR: Unable to open mailbox ", rv


Processing mailbox...
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-23-7fffd2fa7f3c> in <module>()
      2 if rv == 'OK':
      3     print "Processing mailbox..."
----> 4     read_mailbox_and_edit_users(M)
      5     M.close()
      6 else:

<ipython-input-21-3380e1cc1c31> in read_mailbox_and_edit_users(M)
     51         choices_made = re.findall(r'\d+',text['message'])
     52         if 'stop' in text['message'].lower():
---> 53             j2p.delete_user(Session,text['sender'])
     54             j2p.send_text(cf['fromaddr'],cf['username'],cf['password'],text['sender'],cf['stop_message'])
     55             M.store(num , '+FLAGS', '\\Deleted') #This archives the message.

/home/steve/comphonemploy/jobs2phones/load.py in delete_user(Session, phone_number)
    143 def delete_user(Session,phone_number):
    144         with session_scope(Session) as session:
--> 145             return UserDeleter().delete(session,phone_number)
    146 
    147 def increment_posts_sent_count(Session,phone_number):

/home/steve/comphonemploy/jobs2phones/load.py in delete(self, session, phone_number)
     49 class UserDeleter(object):
     50     def delete(self,session,phone_number):
---> 51         user = session.query(User).filter(User.phone_number==phone_number)[0]
     52         session.delete(user)
     53 

/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/query.pyc in __getitem__(self, item)
   2231                 return list(self)[-1]
   2232             else:
-> 2233                 return list(self[item:item + 1])[0]
   2234 
   2235     @_generative(_no_statement_condition)

IndexError: list index out of range

In [10]:
M.logout()


Out[10]:
('BYE', ['LOGOUT Requested'])

In [19]:
data_num = '1'

In [20]:
data_num.split()


Out[20]:
['1']

In [ ]: