简体   繁体   中英

Download / Parse Email with Python

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')

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.

For simple usage examples, I find that Doug Hellmann's "Python Module of the Week" gives a good understanding very quickly. See the section on Fetching messages specifically.

http://www.doughellmann.com/PyMOTW/imaplib/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM