email.generator : 生成 MIME 文档

源代码: Lib/email/generator.py


最常见任务之一是生成由消息对象结构表示的 Email 消息扁平 (序列化) 版本。需要这样做若想要发送消息凭借 smtplib.SMTP.sendmail() , or print the message on the console. Taking a message object structure and producing a serialized representation is the job of the generator classes.

就像 email.parser module, you aren’t limited to the functionality of the bundled generator; you could write one from scratch yourself. However the bundled generator knows how to generate most email in a standards-compliant way, should handle MIME and non-MIME email messages just fine, and is designed so that the bytes-oriented parsing and generation operations are inverses, assuming the same non-transforming policy is used for both. That is, parsing the serialized byte stream via the BytesParser class and then regenerating the serialized byte stream using BytesGenerator should produce output identical to the input [ 1 ] . (On the other hand, using the generator on an EmailMessage constructed by program may result in changes to the EmailMessage object as defaults are filled in.)

The Generator class can be used to flatten a message into a text (as opposed to binary) serialized representation, but since Unicode cannot represent binary data directly, the message is of necessity transformed into something that contains only ASCII characters, using the standard email RFC Content Transfer Encoding techniques for encoding email messages for transport over channels that are not “8 bit clean”.

To accommodate reproducible processing of SMIME-signed messages Generator disables header folding for message parts of type multipart/signed and all subparts.

class email.generator. BytesGenerator ( outfp , mangle_from_ = None , maxheaderlen = None , * , policy = None )

返回 BytesGenerator 对象将写入的任何消息提供给 flatten() 方法,或将任何替代转义编码文本提供给 write() 方法,到 像文件对象 outfp . outfp 必须支持 write 方法 (接受二进制数据)。

若可选 mangle_from_ is True , put a > character in front of any line in the body that starts with the exact string "From " , that is From followed by a space at the beginning of a line. mangle_from_ defaults to the value of the mangle_from_ setting of the policy (which is True compat32 policy and False for all others). mangle_from_ is intended for use when messages are stored in Unix mbox format (see mailbox and WHY THE CONTENT-LENGTH FORMAT IS BAD ).

maxheaderlen 不是 None , refold any header lines that are longer than maxheaderlen ,或者若 0 , do not rewrap any headers. If manheaderlen is None (the default), wrap headers and other message lines according to the policy 设置。

policy is specified, use that policy to control message generation. If policy is None (the default), use the policy associated with the Message or EmailMessage object passed to flatten to control the message generation. See email.policy for details on what policy controls.

Added in version 3.2.

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

3.6 版改变: The default behavior of the mangle_from_ and maxheaderlen parameters is to follow the policy.