email.parser : 剖析 Email 消息

源代码: Lib/email/parser.py


可以按 2 种方式之一创建消息对象结构:可以从整块布料创建它们通过创建 EmailMessage 对象,添加 Header 头使用字典接口,和添加负载使用 set_content() 和相关方法,或者可以通过剖析 Email 消息的序列化表示来创建它们。

The email 包提供理解大多数 Email 文档结构 (包括 MIME 文档) 的标准剖析器。可以向剖析器传递字节、字符串或文件对象,剖析器会返回根 EmailMessage 实例的对象结构。对于简单非 MIME 消息,此根对象的负载可能是包含消息文本的字符串。对于 MIME 消息,根对象会返回 True 从其 is_multipart() 方法,和可以凭借负载操纵方法访问子部分,譬如 get_body() , iter_parts() ,和 walk() .

实际有 2 种剖析器接口可供使用, Parser API 和增量 FeedParser API。 Parser API 最有用若在内存中有整个消息文本,或者若整个消息活在文件系统的文件中。 FeedParser 更合适当从可能阻塞等待更多输入的流读取消息时 (譬如:从套接字读取 Email 消息)。 FeedParser 可以增量消耗并剖析消息,且仅返回根对象当关闭剖析器时。

注意,可以按有限方式扩展剖析器,当然,也可以完全从新实现自己的剖析器。所有逻辑连接 email 包的捆绑剖析器和 EmailMessage 类体现在 Policy 类,因此,自定义剖析器可以按它找到任何必要方式创建消息对象树,通过实现自定义版本的合适 Policy 方法。

FeedParser API

The BytesFeedParser ,导入从 email.feedparser module, provides an API that is conducive to incremental parsing of email messages, such as would be necessary when reading the text of an email message from a source that can block (such as a socket). The BytesFeedParser can of course be used to parse an email message fully contained in a 像字节对象 , string, or file, but the BytesParser API may be more convenient for such use cases. The semantics and results of the two parser APIs are identical.

The BytesFeedParser ’s API is simple; you create an instance, feed it a bunch of bytes until there’s no more to feed it, then close the parser to retrieve the root message object. The BytesFeedParser is extremely accurate when parsing standards-compliant messages, and it does a very good job of parsing non-compliant messages, providing information about how a message was deemed broken. It will populate a message object’s defects attribute with a list of any problems it found in a message. See the email.errors module for the list of defects that it can find.

Here is the API for the BytesFeedParser :

class email.parser. BytesFeedParser ( _factory = None , * , policy = policy.compat32 )

创建 BytesFeedParser 实例。可选 _factory is a no-argument callable; if not specified use the message_factory policy 。调用 _factory whenever a new message object is needed.

policy is specified use the rules it specifies to update the representation of the message. If policy 未设置,使用 compat32 policy, which maintains backward compatibility with the Python 3.2 version of the email package and provides Message as the default factory. All other policies provide EmailMessage as the default _factory . For more information on what else policy controls, see the policy 文档编制。

注意: 应始终指定 policy 关键字 ;默认将更改为 email.policy.default 在未来 Python 版本中。

Added in version 3.2.

3.3 版改变: 添加 policy 关键词。

3.6 版改变: _factory 默认为策略 message_factory .