简体   繁体   中英

Using imaplib to get headers of emails?

Here is my code:

    conn = imaplib.IMAP4_SSL('imap.gmail.com')
    conn.login('username', 'password')
    conn.select()
    typ, data = conn.search(None, "ALL")
    parser1 = HeaderParser()
    for num in data[0].split():
        typ, data = conn.fetch(num, '(RFC822)')
        header_data = str(data[1][0])
        msg = email.message_from_string(header_data)
        print(msg.keys())
        print(msg['Date'])

Why am i getting "[]" for the printout of msg.keys() and "None" for the msg['Date']. No error messages. However, if i comment out the last 4 lines of code, and type print(data), then all the headers get printed? Im using python 3.4

conn.fetch returns tuples of message part envelope and data . For some reason -- I'm not sure why -- it may also return a string, such as ')' . So instead of hard-coding data[1][0] , it's better (more robust) to just loop through the tuples in data and parse the message parts:

typ, msg_data = conn.fetch(num, '(RFC822)')
for response_part in msg_data:
    if isinstance(response_part, tuple):
        msg = email.message_from_string(response_part[1])

For example,

import imaplib
import config
import email

conn = imaplib.IMAP4_SSL("imap.gmail.com", 993)
conn.login(config.GMAIL_USER2, config.GMAIL_PASS2)
try:
    conn.select()

    typ, data = conn.search(None, "ALL")
    print(data)
    for num in data[0].split():
        typ, msg_data = conn.fetch(num, '(RFC822)')
        for response_part in msg_data:
            if isinstance(response_part, tuple):
                part = response_part[1].decode('utf-8')
                msg = email.message_from_string(part)
                print(msg.keys())
                print(msg['Date'])
finally:
    try:
        conn.close()
    except:
        pass
    finally:
        conn.logout()

Much of this code comes from Doug Hellman's imaplib tutorial .

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