email.generator:產生 MIME 文件

原始碼:Lib/email/generator.py


One of the most common tasks is to generate the flat (serialized) version ofthe email message represented by a message object structure. You will need todo this if you want to send your message viasmtplib.SMTP.sendmail(),or print the message on the console. Taking amessage object structure and producing a serialized representation is the jobof the generator classes.

As with theemail.parser module, you aren't limited to the functionalityof the bundled generator; you could write one from scratch yourself. Howeverthe bundled generator knows how to generate most email in a standards-compliantway, should handle MIME and non-MIME email messages just fine, and is designedso that the bytes-oriented parsing and generation operations are inverses,assuming the same non-transformingpolicy is used for both. Thatis, parsing the serialized byte stream via theBytesParser class and then regenerating the serializedbyte stream usingBytesGenerator should produce output identical tothe input[1]. (On the other hand, using the generator on anEmailMessage constructed by program may result inchanges to theEmailMessage object as defaults arefilled in.)

TheGenerator class can be used to flatten a message into a text (asopposed to binary) serialized representation, but since Unicode cannotrepresent binary data directly, the message is of necessity transformed intosomething that contains only ASCII characters, using the standard email RFCContent Transfer Encoding techniques for encoding email messages for transportover channels that are not "8 bit clean".

To accommodate reproducible processing of SMIME-signed messagesGenerator disables header folding for message parts of typemultipart/signed and all subparts.

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

Return aBytesGenerator object that will write any message providedto theflatten() method, or any surrogateescape encoded text providedto thewrite() method, to thefile-like objectoutfp.outfp must support awrite method that accepts binary data.

If optionalmangle_from_ isTrue, put a> character in front ofany line in the body that starts with the exact string"From", that isFrom followed by a space at the beginning of a line.mangle_from_defaults to the value of themangle_from_setting of thepolicy (which isTrue for thecompat32 policy andFalse for all others).mangle_from_ is intended for use when messages are stored in Unix mboxformat (seemailbox andWHY THE CONTENT-LENGTH FORMAT IS BAD).

Ifmaxheaderlen is notNone, refold any header lines that are longerthanmaxheaderlen, or if0, do not rewrap any headers. Ifmanheaderlen isNone (the default), wrap headers and other messagelines according to thepolicy settings.

Ifpolicy is specified, use that policy to control message generation. Ifpolicy isNone (the default), use the policy associated with theMessage orEmailMessageobject passed toflatten to control the message generation. Seeemail.policy for details on whatpolicy controls.

在 3.2 版被加入.

在 3.3 版的變更:新增關鍵字policy

在 3.6 版的變更:The default behavior of themangle_from_andmaxheaderlen parameters is to follow the policy.

flatten(msg,unixfrom=False,linesep=None)

Print the textual representation of the message object structure rootedatmsg to the output file specified when theBytesGeneratorinstance was created.

If thepolicy optioncte_typeis8bit (the default), copy any headers in the original parsedmessage that have not been modified to the output with any bytes with thehigh bit set reproduced as in the original, and preserve the non-ASCIIContent-Transfer-Encoding of any body parts that have them.Ifcte_type is7bit, convert the bytes with the high bit set asneeded using an ASCII-compatibleContent-Transfer-Encoding.That is, transform parts with non-ASCIIContent-Transfer-Encoding(Content-Transfer-Encoding: 8bit) to an ASCII compatibleContent-Transfer-Encoding, and encode RFC-invalid non-ASCIIbytes in headers using the MIMEunknown-8bit character set, thusrendering them RFC-compliant.

Ifunixfrom isTrue, print the envelope header delimiter used bythe Unix mailbox format (seemailbox) before the first of theRFC 5322 headers of the root message object. If the root object hasno envelope header, craft a standard one. The default isFalse.Note that for subparts, no envelope header is ever printed.

Iflinesep is notNone, use it as the separator character betweenall the lines of the flattened message. Iflinesep isNone (thedefault), use the value specified in thepolicy.

clone(fp)

Return an independent clone of thisBytesGenerator instance withthe exact same option settings, andfp as the newoutfp.

write(s)

Encodes using theASCII codec and thesurrogateescape errorhandler, and pass it to thewrite method of theoutfp passed to theBytesGenerator's constructor.

As a convenience,EmailMessage provides the methodsas_bytes() andbytes(aMessage) (a.k.a.__bytes__()), which simplify the generation ofa serialized binary representation of a message object. For more detail, seeemail.message.

Because strings cannot represent binary data, theGenerator class mustconvert any binary data in any message it flattens to an ASCII compatibleformat, by converting them to an ASCII compatibleContent-Transfer_Encoding. Using the terminology of the emailRFCs, you can think of this asGenerator serializing to an I/O streamthat is not "8 bit clean". In other words, most applications will wantto be usingBytesGenerator, and notGenerator.

classemail.generator.Generator(outfp,mangle_from_=None,maxheaderlen=None,*,policy=None)

Return aGenerator object that will write any message providedto theflatten() method, or any text provided to thewrite()method, to thefile-like objectoutfp.outfp must support awrite method that accepts string data.

If optionalmangle_from_ isTrue, put a> character in front ofany line in the body that starts with the exact string"From", that isFrom followed by a space at the beginning of a line.mangle_from_defaults to the value of themangle_from_setting of thepolicy (which isTrue for thecompat32 policy andFalse for all others).mangle_from_ is intended for use when messages are stored in Unix mboxformat (seemailbox andWHY THE CONTENT-LENGTH FORMAT IS BAD).

Ifmaxheaderlen is notNone, refold any header lines that are longerthanmaxheaderlen, or if0, do not rewrap any headers. Ifmanheaderlen isNone (the default), wrap headers and other messagelines according to thepolicy settings.

Ifpolicy is specified, use that policy to control message generation. Ifpolicy isNone (the default), use the policy associated with theMessage orEmailMessageobject passed toflatten to control the message generation. Seeemail.policy for details on whatpolicy controls.

在 3.3 版的變更:新增關鍵字policy

在 3.6 版的變更:The default behavior of themangle_from_andmaxheaderlen parameters is to follow the policy.

flatten(msg,unixfrom=False,linesep=None)

Print the textual representation of the message object structure rootedatmsg to the output file specified when theGeneratorinstance was created.

If thepolicy optioncte_typeis8bit, generate the message as if the option were set to7bit.(This is required because strings cannot represent non-ASCII bytes.)Convert any bytes with the high bit set as needed using anASCII-compatibleContent-Transfer-Encoding. That is,transform parts with non-ASCIIContent-Transfer-Encoding(Content-Transfer-Encoding: 8bit) to an ASCII compatibleContent-Transfer-Encoding, and encode RFC-invalid non-ASCIIbytes in headers using the MIMEunknown-8bit character set, thusrendering them RFC-compliant.

Ifunixfrom isTrue, print the envelope header delimiter used bythe Unix mailbox format (seemailbox) before the first of theRFC 5322 headers of the root message object. If the root object hasno envelope header, craft a standard one. The default isFalse.Note that for subparts, no envelope header is ever printed.

Iflinesep is notNone, use it as the separator character betweenall the lines of the flattened message. Iflinesep isNone (thedefault), use the value specified in thepolicy.

在 3.2 版的變更:Added support for re-encoding8bit message bodies, and thelinesep argument.

clone(fp)

Return an independent clone of thisGenerator instance with theexact same options, andfp as the newoutfp.

write(s)

Writes to thewrite method of theoutfp passed to theGenerator's constructor. This provides just enough file-likeAPI forGenerator instances to be used in theprint()function.

As a convenience,EmailMessage provides the methodsas_string() andstr(aMessage) (a.k.a.__str__()), which simplify the generation ofa formatted string representation of a message object. For more detail, seeemail.message.

Theemail.generator module also provides a derived class,DecodedGenerator, which is like theGenerator base class,except that non-text parts are not serialized, but are insteadrepresented in the output stream by a string derived from a template filledin with information about the part.

classemail.generator.DecodedGenerator(outfp,mangle_from_=None,maxheaderlen=None,fmt=None,*,policy=None)

Act likeGenerator, except that for any subpart of the messagepassed toGenerator.flatten(), if the subpart is of main typetext, print the decoded payload of the subpart, and if the maintype is nottext, instead of printing it fill in the stringfmt using information from the part and print the resultingfilled-in string.

To fill infmt, executefmt%part_info, wherepart_infois a dictionary composed of the following keys and values:

  • type -- Full MIME type of the non-text part

  • maintype -- Main MIME type of the non-text part

  • subtype -- Sub-MIME type of the non-text part

  • filename -- Filename of the non-text part

  • description -- Description associated with the non-text part

  • encoding -- Content transfer encoding of the non-text part

Iffmt isNone, use the following defaultfmt:

"[Non-text (%(type)s) part of message omitted, filename %(filename)s]"

Optional_mangle_from_ andmaxheaderlen are as with theGenerator base class.

註解

[1]

This statement assumes that you use the appropriate setting forunixfrom, and that there are noemail.policy settings calling forautomatic adjustments (for example,refold_source must benone, which isnot the default). It is also not 100% true, since if the messagedoes not conform to the RFC standards occasionally information about theexact original text is lost during parsing error recovery. It is a goalto fix these latter edge cases when possible.