无法在python中提取电子邮件文件的正文

Sum*_*nth 5 python

我正在阅读存储在我的机器中的电子邮件文件,能够提取电子邮件的标题,但无法提取正文.

    # The following part is working , opening a file and reading the header .

    import email
    from email.parser import HeaderParser
    with open(passedArgument1+filename,"r",encoding="ISO-8859-1") as f:
        msg=email.message_from_file(f)
        print('message',msg.as_string())
        parser = HeaderParser()
        h = parser.parsestr(msg.as_string())
        print (h.keys())  

       # The following snippet gives error
        msgBody=msg.get_body('text/plain')
Run Code Online (Sandbox Code Playgroud)

是否有任何正确的方法来提取身体信息.此时此刻.

作为参考,可以从中下载电子邮件文件

https://drive.google.com/file/d/0B3XlF206d5UrOW5xZ3FmV3M3Rzg/view

小智 14

3.6电子邮件lib默认使用与Python 3.2兼容的API,这就是导致此问题的原因.

请注意以下声明中的默认策略:

email.message_from_file(fp, _class=None, *, policy=policy.compat32)

如果要使用在3.6文档中看到的"新"API,则必须使用其他策略创建消息.

import email
from email import policy
...
msg=email.message_from_file(f, policy=policy.default)
Run Code Online (Sandbox Code Playgroud)

将为您提供在文档中看到的新API,其中包含非常有用的内容: get_body()

  • 这应该是公认的答案。在 Python 3.7 中仍然有效。 (5认同)

Fab*_*ien 13

更新

如果您遇到AttributeError: 'Message' object has no attribute 'get_body'错误,可能需要阅读以下内容.

我做了一些测试,与当前的库实现(2017年7月)相比,它似乎确实是错误的.

您可能正在寻找的实际上get_payload()是您想要实现的功能:

EmailMessage对象提供的概念模型是一个有序的头字典,它与有效载荷相结合,有效载荷代表消息的RFC 5322主体,可能是子EmailMessage对象的列表

get_payload()不在2017年7月的文档中,但是help()说如下:

get_payload(i=None, decode=False) method of email.message.Message instance
  Return a reference to the payload.
Run Code Online (Sandbox Code Playgroud)

有效负载将是列表对象或字符串.如果您改变列表对象,则可以在适当的位置修改消息的有效负载.可选 i返回索引到有效内容.

可选decode是根据Content-Transfer-Encoding标头(默认为False)指示是否应解码有效负载的标志.

True消息不是多部分时,如果此标头的值为'quoted-printable'或'base64',则将解码有效负载.如果使用某些其他编码,或者标头丢失,或者有效负载具有伪造数据(即伪造的base64或uuencoded数据),则按原样返回有效负载.

如果消息是多部分并且解码标志是True,则None返回.