email.policy :策略对象

Added in version 3.3.

源代码: Lib/email/policy.py


The email 包的首要焦点是处理由各种 Email 和 MIME RFC 所描述的 Email 消息。不管怎样,Email 消息的一般格式 (每个头字段由名称之后紧跟冒号和值组成的 Header 头字段块,整个块之后紧跟空行和任意本体),是在 Email 界之外找到实用格式。其中一些的用法与主要电子邮件 RFC 相当接近,有些则不。甚至在处理 Email 时,有时也期望打破对 RFC 的严格遵从,譬如:生成本身不遵循标准 Email 服务器互操作的电子邮件,或按违反标准的方式实现想要使用的扩展。

策略对象赋予 email 包灵活处理所有这些迥然不同的用例。

A Policy 对象封装了一组属性和方法,用于控制 email 包在使用期间各个组件的行为。 Policy 实例可以将各种类和方法传入 email 包以改变其默认行为。可设置的值及其默认值的描述见下文。

email 包中的所有类都使用默认策略。对于所有的 parser 类和相关方便函数,和对于 Message 类,这是 Compat32 策略,凭借其相应预定义实例 compat32 。此策略提供对 email 包 Python 3.3 之前版本的完全向后兼容性 (在某些情况下,包括 Bug 兼容性)。

此默认值为 policy 关键词到 EmailMessage EmailPolicy 策略,凭借其预定义实例 default .

Message or EmailMessage object is created, it acquires a policy. If the message is created by a parser , a policy passed to the parser will be the policy used by the message it creates. If the message is created by the program, then the policy can be specified when it is created. When a message is passed to a generator , the generator uses the policy from the message by default, but you can also pass a specific policy to the generator that will override the one stored on the message object.

默认值对于 policy keyword for the email.parser classes and the parser convenience functions will be changing in a future version of Python. Therefore you should always specify explicitly which policy you want to use when calling any of the classes and functions described in the parser 模块。

The first part of this documentation covers the features of Policy 抽象基类 that defines the features that are common to all policy objects, including compat32 . This includes certain hook methods that are called internally by the email package, which a custom policy could override to obtain different behavior. The second part describes the concrete classes EmailPolicy and Compat32 , which implement the hooks that provide the standard behavior and the backward compatible behavior and features, respectively.

Policy instances are immutable, but they can be cloned, accepting the same keyword arguments as the class constructor and returning a new Policy instance that is a copy of the original but with the specified attributes values changed.

As an example, the following code could be used to read an email message from a file on disk and pass it to the system sendmail 程序在 Unix 系统:

>>> from email import message_from_binary_file
>>> from email.generator import BytesGenerator
>>> from email import policy
>>> from subprocess import Popen, PIPE
>>> with open('mymsg.txt', 'rb') as f:
...     msg = message_from_binary_file(f, policy=policy.default)
...
>>> p = Popen(['sendmail', msg['To'].addresses[0]], stdin=PIPE)
>>> g = BytesGenerator(p.stdin, policy=msg.policy.clone(linesep='\r\n'))
>>> g.flatten(msg)
>>> p.stdin.close()
>>> rc = p.wait()