Download / Parse Email with Python

Zac Brown picture Zac Brown · Jun 8, 2011 · Viewed 9.6k times · Source

I am working on an email client and have run into a small problem. I am unsure of how to download the email messages and save them to the local HDD. I am able to connect to the server using IMAP4 SSL (with the code below).

import imaplib
server = imaplib.IMAP4_SSL('imap.gmail.com')
server.login('USER', 'PASS')

Answer

zeekay picture zeekay · Jun 8, 2011

You can list directories in your mailbox with IMAP4.list. To actually get messages out of a directory use IMAP4.select, and then use IMAP4.search, and iterate over the list of id's it returns. In your case you could do something like this:

server.select('[Gmail]/All Mail')
resp, items = server.search(None, "(UNSEEN)")
for mail in items[0].split():
    resp, data = m.fetch(mail, '(RFC822)')
    body = data[0][1]
    print body

Read the docs for sure: http://docs.python.org/library/imaplib.html. Also agree with this answer, read through PyMOTW's tutorial. In general it's a good place to check for tutorials for modules in the standard library.