July 7, 2011

Python - processing GMail IMAP email

Here is an example of processing your GMail IMAP email in Python.

The script below will:

  • login to GMail account using IMAP
  • open your Inbox
  • retrieve and print all messages
  • close mailbox
  • logout
#!/usr/bin/env python

import imaplib

USER = 'username@gmail.com'
PASSWORD = 'xxx'

mail = imaplib.IMAP4_SSL('imap.gmail.com', 993)
mail.login(USER, PASSWORD)
mail.select('Inbox')

status, data = mail.search(None, 'ALL')
for num in data[0].split():
    status, data = mail.fetch(num, '(RFC822)')
    print 'Message %s\n%s\n' % (num, data[0][1])
   
mail.close()
mail.logout()

1 comment:

Anonymous said...

Thanks, I was looking to something like this :)