9/03/2014

Python mail read example, using imaplib

import imaplib
import email
import mimetypes
from email import header


def decodeHeader( headerMsg ):
    L = header.decode_header(headerMsg)
    s = ''
    for s1, chset in L:
        if(type(s1) == bytes):
            s += s1.decode(chset) if chset else s1.decode()
        else:
            s += s1
    return s



host = 'imap.xxx.comt'
userid = 'myaccount@xxx.com'
passwd = 'passward'

imap = imaplib.IMAP4_SSL(host)
imap.login(userid, passwd)

imap.select('specific_folder') #or use INBOX
status, email_ids = imap.search(None, '(ALL)') #or use , '(UNSEEN)' )


for num in email_ids[0].split():
    type1, data = imap.fetch(num, '(RFC822)')
    raw_email = data[0][1]
    email_msg = email.message_from_bytes( raw_email )

    print( 'Subject: ', decodeHeader( email_msg['Subject'] ) )
    print( 'From: ', decodeHeader( email_msg['From'] ) )
    print( 'To: ', decodeHeader( email_msg['To'] ) )
    print( 'Date: ', decodeHeader( email_msg['Date'] ) )


    type1, data = imap.fetch(num, '(UID BODY[TEXT])')
    raw_email = data[0][1]
    print('contents: ', raw_email )
    print('----\n\n')


No comments:

Post a Comment