Skip to content

Instantly share code, notes, and snippets.

@mpkuse
Created September 4, 2017 05:47
Show Gist options
  • Save mpkuse/000b61ebea094b55959205057ce95774 to your computer and use it in GitHub Desktop.
Save mpkuse/000b61ebea094b55959205057ce95774 to your computer and use it in GitHub Desktop.
Python Read Emails from Gmail with imaplib
import imaplib
import email
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('USERNAME_HERE', 'PASSWORD_HERE')
print mail.list()
mail.select('inbox')
result, email_list = mail.uid('search', None, "UNSEEN")
#result, email_list = mail.uid('search', None, "ALL")
print 'search: ', email_list
for l in email_list[0].split():
print l
result, data = mail.uid( 'fetch', l, '(RFC822)' ) #get email '2'
email_message = email.message_from_string( data[0][1] )
print 'Sender : ', email_message['From']
#print email_message.keys()
for part in email_message.walk():
if part.get_content_type() == "text/plain": # ignore attachments/html
body = part.get_payload(decode=True)
print body
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment