18.1.3. email: Generating MIME documents¶
One of the most common tasks is to generate the flat text of the email message
represented by a message object structure. You will need to do this if you want
to send your message via the smtplib module or the nntplib module,
or print the message on the console. Taking a message object structure and
producing a flat text document is the job of the Generator class.
Again, as with the 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 transformation from flat text, to a message
structure via the Parser class, and back to flat text,
is idempotent (the input is identical to the output). On the other hand, using
the Generator on a Message constructed by program may
result in changes to the Message object as defaults are
filled in.
Here are the public methods of the Generator class, imported from the
email.generator module:
-
class
email.generator.Generator(outfp[, mangle_from_[, maxheaderlen]])¶ The constructor for the
Generatorclass takes a file-like object called outfp for an argument. outfp must support thewrite()method and be usable as the output file in a Python extended print statement.Optional mangle_from_ is a flag that, when
True, puts a>character in front of any line in the body that starts exactly asFrom, i.e.Fromfollowed by a space at the beginning of the line. This is the only guaranteed portable way to avoid having such lines be mistaken for a Unix mailbox format envelope header separator (see WHY THE CONTENT-LENGTH FORMAT IS BAD for details). mangle_from_ defaults toTrue, but you might want to set this toFalseif you are not writing Unix mailbox format files.Optional maxheaderlen specifies the longest length for a non-continued header. When a header line is longer than maxheaderlen (in characters, with tabs expanded to 8 spaces), the header will be split as defined in the
Headerclass. Set to zero to disable header wrapping. The default is 78, as recommended (but not required) by RFC 2822.The other public
Generatormethods are:-
flatten(msg[, unixfrom])¶ Print the textual representation of the message object structure rooted at msg to the output file specified when the
Generatorinstance was created. Subparts are visited depth-first and the resulting text will be properly MIME encoded.Optional unixfrom is a flag that forces the printing of the envelope header delimiter before the first RFC 2822 header of the root message object. If the root object has no envelope header, a standard one is crafted. By default, this is set to
Falseto inhibit the printing of the envelope delimiter.Note that for subparts, no envelope header is ever printed.
New in version 2.2.2:
New in version 2.2.2.
-