【问题标题】:Using imaplib to get headers of emails?使用 imaplib 获取电子邮件标题?
【发布时间】:2015-04-29 11:13:44
【问题描述】:

这是我的代码:

    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'] 的“None”。没有错误信息。但是,如果我注释掉最后 4 行代码,然后键入 print(data),那么所有的标题都会被打印出来吗?我正在使用 python 3.4

【问题讨论】:

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


    【解决方案1】:

    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

    【讨论】:

    • 我刚刚尝试过,但没有收到错误消息。但什么都没有打印。为了确定,我会再看一遍
    • 如果您正在运行我发布的代码并且 nothing 打印,那么 data 是一个空字符串,因为其中有一个 print(data)
    • TypeError: initial_value must be str or None, not bytes 是我得到的错误消息
    • 我的错误。使用 Python3,您必须先解码 response_part[1] 中的字节,然后再使用 email.message_from_string 解析它。
    • 已排序。非常感谢队友!
    猜你喜欢
    • 2015-04-17
    • 2011-09-06
    • 2014-10-03
    • 2012-12-11
    • 2011-03-18
    • 2012-10-24
    • 2011-01-14
    • 2017-05-14
    • 2017-04-04
    相关资源
    最近更新 更多