Monday, January 11, 2016

email read imap in python

#1
import imaplib
import email
import getpass

imap_server = 'imap.mail.yahoo.com'
email_user = 'dummyrain@sbcglobal.net'

def getLogin():
    #username = raw_input("Email address: ")
    username = email_user
    password = getpass.getpass()
    return username, password

email_user, email_password = getLogin()  

#email_password = 'xxxx'

mail = imaplib.IMAP4_SSL(imap_server)
mail.login(email_user, email_password)
mail.list()
mail.select('INBOX')
#mail.select('inbox')


typ, data = mail.search(None, 'UNSEEN')
ids = data[0]
id_list = ids.split()
#Print total unread messages
print len(id_list)

#get the most recent email id
latest_email_id = int( id_list[-1] )

#iterate through 15 messages in decending order starting with latest_email_id
#the '-1' dictates reverse looping order
for i in id_list:
   typ, data = mail.fetch( i, '(RFC822)' )

   for response_part in data:
      if isinstance(response_part, tuple):
          msg = email.message_from_string(response_part[1])
          varSubject = msg['subject']
          varFrom = msg['from']

   #remove the brackets around the sender email address
   varFrom = varFrom.replace('<', '')
   varFrom = varFrom.replace('>', '')

   #add ellipsis (...) if subject length is greater than 35 characters
   if len( varSubject ) > 35:
      varSubject = varSubject[0:32] + '...'

   print '[' + varFrom.split()[-1] + '] ' + varSubject
   mail.store(i, '-FLAGS', '\Seen')

mail.close()

mail.logout()

No comments:

Post a Comment