使用imaplib获取电子邮件的标题?

时间:2015-02-26 21:39:08

标签: python python-3.x python-3.4 imaplib

这是我的代码:

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

为什么msg.keys()的打印输出为“[]”,msg ['Date']为“无”。没有错误消息。但是,如果我注释掉最后4行代码,并输入print(data),那么所有的标题都会打印出来吗?我正在使用python 3.4

1 个答案:

答案 0 :(得分:0)

conn.fetch返回tuples of message part envelope and data。出于某种原因 - 我不确定为什么 - 它也可能返回一个字符串,例如')'。因此,不是硬编码data[1][0],而是更好(更强大)来遍历data中的元组并解析消息部分:

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

例如,

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

此代码大部分来自Doug Hellman's imaplib tutorial