email --- 电子邮件与 MIME 处理包¶
email 包是一个用于管理电子邮件消息的库。 它 并非 专门被设计用来执行向 SMTP (RFC 2821), NNTP 或其他服务器发送电子邮件消息;这些是 smtplib 等模块的功能。 email 包试图尽可能地遵循 RFC,支持 RFC 5322 和 RFC 6532,以及与 MIME 相关的各个 RFC 例如 RFC 2045, RFC 2046, RFC 2047, RFC 2183 和 RFC 2231。
email 包的总体结构可以分为三个主要组件,另外还有第四个组件用于控制其他组件的行为。
这个包的中心组件是代表电子邮件消息的“对象模型”。 应用程序主要通过在 message 子模块中定义的对象模型接口与这个包进行交互。 应用程序可以使用此 API 来询问有关现有电子邮件的问题、构造新的电子邮件,或者添加或移除自身也使用相同对象模型接口的电子邮件子组件。 也就是说,遵循电子邮件消息及其 MIME 子组件的性质,电子邮件对象模型是所有提供 EmailMessage API 的对象所构成的树状结构。
这个包的另外两个主要组件是 parser 和 generator。 parser 接受电子邮件消息的序列化版本(字节流)并将其转换为 EmailMessage 对象树。 generator 接受 EmailMessage 并将其转回序列化的字节流。 (parser 和 generator 还能处理文本字符流,但不建议这种用法,因为这很容易导致某种形式的无效消息。
控制组件是 policy 模块。 每一个 EmailMessage、每一个 generator 和每一个 parser 都有一个相关联的 policy 对象来控制其行为。 通常应用程序只有在 EmailMessage 被创建时才需要指明控制策略,或者通过直接实例代 EmailMessage 来新建电子邮件,或者通过使用 parser 来解析输入流。 但是策略也可以在使用 generator 序列化消息时被更改。 例如,这允许从磁盘解析通用电子邮件消息,而在将消息发送到电子邮件服务器时使用标准 SMTP 设置对其进行序列化。
The email package does its best to hide the details of the various governing RFCs from the application. Conceptually the application should be able to treat the email message as a structured tree of Unicode text and binary attachments, without having to worry about how these are represented when serialized. In practice, however, it is often necessary to be aware of at least some of the rules governing MIME messages and their structure, specifically the names and nature of the MIME "content types" and how they identify multipart documents. For the most part this knowledge should only be required for more complex applications, and even then it should only be the high level structure in question, and not the details of how those structures are represented. Since MIME content types are used widely in modern internet software (not just email), this will be a familiar concept to many programmers.
以下小节描述了 email 包的具体功能。 我们会从 message 对象模型开始,它是应用程序将要使用的主要接口,之后是 parser 和 generator 组件。 然后我们会介绍 policy 控制组件,它将完成对这个库的主要组件的处理。
接下来的三个小节会介绍这个包可能引发的异常以及 parser 可能检测到的缺陷(即与 RFC 不相符)。 然后我们会介绍 headerregistry 和 contentmanager 子组件,它们分别提供了用于更精细地操纵标题和载荷的工具。 这两个组件除了包含使用与生成非简单消息的相关特性,还记录了它们的可扩展性 API,这将是高级应用程序所感兴趣的内容。
在此之后是一组使用之前小节所介绍的 API 的基本部分的示例。
The foregoing represent the modern (Unicode friendly) API of the email package.
The remaining sections, starting with the Message
class, cover the legacy compat32 API that deals much more
directly with the details of how email messages are represented. The
compat32 API does not hide the details of the RFCs from
the application, but for applications that need to operate at that level, they
can be useful tools. This documentation is also relevant for applications that
are still using the compat32 API for backward
compatibility reasons.
在 3.6 版本发生变更: 文档经过重新组织和撰写以鼓励使用新的 EmailMessage/EmailPolicy API。
email 包文档的内容:
旧式 API: