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

无法在python中提取电子邮件文件的正文,python,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:

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

    # 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')
有没有合适的方法只提取正文信息。卡在这一点上

作为参考,电子邮件文件可从


更新


如果出现
AttributeError:“Message”对象没有属性“get\u body”
错误,您可能需要阅读下面的内容

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

实际上,您可能需要的是函数
get\u payload()
它似乎实现了您想要实现的功能:

EmailMessage对象提供的概念模型是 标题的有序字典与表示 RFC 5322消息体,可能是 子EmailMessage对象

get\u payload()
不在当前2017年7月,但
help()
说明如下:

有效负载将是列表对象或字符串。如果你变异了 在list对象中,您可以就地修改消息的有效负载。可选的
i
将该索引返回到有效负载中

可选
decode
是一个标志,根据内容传输编码指示是否应解码有效负载 标题(默认值为
False

True
且消息不是多部分时,如果此标头的值为“quoted printable”或“base64”,则有效负载将被解码。如果使用了某些其他编码,或者缺少报头,或者如果有效负载具有虚假数据(即虚假base64或uuencoded数据),则有效负载将按原样返回

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


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

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

email.message来自文件(fp,\u class=None,*,policy=policy.compat32)

如果要使用3.6文档中的“新”API,则必须使用不同的策略创建消息

import email
from email import policy
...
msg=email.message_from_file(f, policy=policy.default)

将为您提供在文档中看到的新API,其中包括非常有用的:
get\u body()

错误消息是什么?AttributeError:“message”对象没有属性“get\u body”。该方法似乎不存在。你检查过文档了吗?是指此文档链接这指的是
EmailMessage
而不是
Message
,你需要在对象中向下移动一级。您正在查找
类email.message.EmailMessage
给我以下消息msgBody=msg.EmailMessage.get_body('text/plain')AttributeError:'message'对象没有属性'EmailMessage'谢谢您提供的详细答案Fabien,相信大多数人都会从答案中受益。啊,谢谢!我只是花了很长时间想知道为什么库和文档不匹配。这应该是公认的答案。在Python3.7中仍然有效。
import email
from email import policy
...
msg=email.message_from_file(f, policy=policy.default)