From Media Design: Networked & Lens-Based wiki
Jump to navigation Jump to search

This python script will use imaplib modules to check email in your email account using imap protocol It will also use the email module to parse the email

import imaplib, email, json
import datetime
date = ( - datetime.timedelta(1)).strftime("%d-%b-%Y")

user_email_addr = ''
user_pwd = 'yyyyy'

inbox={} #dict to store the messages

def imap(addr, pwd):
    mail = imaplib.IMAP4_SSL('') # will be using IMAP4_SSL , but is also possible to use only IMAP4, for no encryption
    mail.login(addr, pwd)
    mail.list()#list of "folders" aka labels in gmail."inbox") # connect to inbox.   

#    result, data = mail.uid('search', None, "ALL") #all the mgs 
    #result, data = mail.uid('search', None, '(HEADER Subject "X") (SENTSINCE {date})'.format(date=date)) #combine subject: X w/ sentsince: today
#    result, data = mail.uid('search', None, '(HEADER Subject "test")')
#    result, data = mail.uid('search', None, '(HEADER From "your uncle")')
#    result, data = mail.uid('search', None, '(UNSEEN)') #unseen msgs
    result, data = mail.uid('search', None, '(UNANSWERED)') 

    for uid in data[0].split():
        print "UID: "+ str(uid)
        result, data = mail.uid('fetch', uid, "(RFC822)") # fetch the email body (RFC822)
        raw_email = data[0][1] #the email raw text including headers

        # PARSING THE EMAIL       
        # using email module we can easily parse the email
        msg = email.message_from_string(raw_email)
#        print msg.items()
        msg_id= str(msg['message-id'])
        print msg_id
#        print "To: "+ str(msg['To'])        
        msg_from = msg['From']
        msg_subject = msg['Subject']
        msg_date = msg['Date']

        # an email can be simple of multip part
        # if simple it contains only one representation of the content 
        # if multipart it will contain more than 1 content type (eg: html and plain)

        # get_payload will a str if it only has 1 content type (text/plain) or a list of the parts (multipart)
        # If multi-part we must "walk" through them in order to access the part(s) we want

        payload = msg.get_payload()
        if type(payload) is str:
            msg_payload = payload
            print msg.get_content_type()

        elif type(payload) is list:
            print msg.get_content_type()

            # the walking
            for part in msg.walk():
                if part.get_content_type() == 'text/plain':
                    msg_payload = part.get_payload()
        inbox[msg_id]=[msg_date, msg_from, msg_subject, msg_payload] # Add to dictionary

    mail.close() #close the mailbox
    mail.logout() #Shutdown connection to server

    dump = json.dumps(inbox, sort_keys=True, indent=4)
    print dump


imap(user_email_addr, user_pwd)