A single interactive example, consisting of a Python statement and its expected output. The constructor arguments are used to initialize the attributes of the same names.
Example defines the following attributes. They are initialized by the constructor, and should not be modified directly.
A string containing the example’s source code. This source code consists of a single Python statement, and always ends with a newline; the constructor adds a newline when necessary.
The expected output from running the example’s source code (either from stdout, or a traceback in case of exception). want ends with a newline unless no output is expected, in which case it’s an empty string. The constructor adds a newline when necessary.
The exception message generated by the example, if the example is expected to generate an exception; or None if it is not expected to generate an exception. This exception message is compared against the return value of traceback.format_exception_only(). exc_msg ends with a newline unless it’s None. The constructor adds a newline if needed.
The line number within the string containing this example where the example begins. This line number is zero-based with respect to the beginning of the containing string.
The example’s indentation in the containing string, i.e., the number of space characters that precede the example’s first prompt.
A dictionary mapping from option flags to True or False, which is used to override default options for this example. Any option flags not contained in this dictionary are left at their default value (as specified by the DocTestRunner’s optionflags). By default, no options are set.


The exception message generated by the example, if the example is expected to generate an exception; or None if it is not expected to generate an exception. This exception message is compared against the return value of traceback.format_exception_only(). exc_msg ends with a newline unless it’s None. The constructor adds a newline if needed.


The example’s indentation in the containing string, i.e., the number of space characters that precede the example’s first prompt.


The line number within the string containing this example where the example begins. This line number is zero-based with respect to the beginning of the containing string.


A dictionary mapping from option flags to True or False, which is used to override default options for this example. Any option flags not contained in this dictionary are left at their default value (as specified by the DocTestRunner’s optionflags). By default, no options are set.


A string containing the example’s source code. This source code consists of a single Python statement, and always ends with a newline; the constructor adds a newline when necessary.


The expected output from running the example’s source code (either from stdout, or a traceback in case of exception). want ends with a newline unless no output is expected, in which case it’s an empty string. The constructor adds a newline when necessary.


When specified, exit after the first failing example and don’t attempt to run the remaining examples. Thus, the number of failures reported will be at most 1. This flag may be useful during debugging, since examples after the first failure won’t even produce debugging output.
The doctest command line accepts the option -f as a shorthand for -o
FAIL_FAST.
New in version 3.4.


When specified, an example that expects an exception passes if an exception of the expected type is raised, even if the exception detail does not match. For example, an example expecting ValueError: 42 will pass if the actual exception raised is ValueError: 3*14, but will fail, e.g., if TypeError is raised.
It will also ignore the module name used in Python 3 doctest reports. Hence both of these variations will work with the flag specified, regardless of whether the test is run under Python 2.7 or Python 3.2 (or later versions):
Note that ELLIPSIS can also be used to ignore the details of the exception message, but such a test may still fail based on whether or not the module details are printed as part of the exception name. Using IGNORE_EXCEPTION_DETAIL and the details from Python 2.3 is also the only clear way to write a doctest that doesn’t care about the exception detail yet continues to pass under Python 2.3 or earlier (those releases do not support doctest directives and ignore them as irrelevant comments). For example:
passes under Python 2.3 and later Python versions with the flag specified, even though the detail changed in Python 2.4 to say “does not” instead of “doesn’t”.
Changed in version 3.2: IGNORE_EXCEPTION_DETAIL now also ignores any information relating to the module containing the exception under test.


When specified, all sequences of whitespace (blanks and newlines) are treated as equal. Any sequence of whitespace within the expected output will match any sequence of whitespace within the actual output. By default, whitespace must match exactly. NORMALIZE_WHITESPACE is especially useful when a line of expected output is very long, and you want to wrap it across multiple lines in your source.


A class used to check the whether the actual output from a doctest example matches the expected output. OutputChecker defines two methods: check_output(), which compares a given pair of outputs, and returns True if they match; and output_difference(), which returns a string describing the differences between two outputs.
OutputChecker defines the following methods:
Return True iff the actual output from an example (got) matches the expected output (want). These strings are always considered to match if they are identical; but depending on what option flags the test runner is using, several non-exact match types are also possible. See section Option Flags for more information about option flags.
Return a string describing the differences between the expected output for a given example (example) and the actual output (got). optionflags is the set of option flags used to compare want and got.


Return True iff the actual output from an example (got) matches the expected output (want). These strings are always considered to match if they are identical; but depending on what option flags the test runner is using, several non-exact match types are also possible. See section Option Flags for more information about option flags.


Return a string describing the differences between the expected output for a given example (example) and the actual output (got). optionflags is the set of option flags used to compare want and got.


Create a new option flag with a given name, and return the new flag’s integer value. register_optionflag() can be used when subclassing OutputChecker or DocTestRunner to create new options that are supported by your subclasses. register_optionflag() should always be called using the following idiom:


A bitmask or’ing together all the reporting flags above.


When specified, failures that involve multi-line expected and actual outputs will be displayed using a context diff.


When specified, differences are computed by difflib.Differ, using the same algorithm as the popular ndiff.py utility. This is the only method that marks differences within lines as well as across lines. For example, if a line of expected output contains digit 1 where actual output contains letter l, a line is inserted with a caret marking the mismatching column positions.


When specified, display the first failing example in each doctest, but suppress output for all remaining examples. This will prevent doctest from reporting correct examples that break because of earlier failures; but it might also hide incorrect examples that fail independently of the first failure. When REPORT_ONLY_FIRST_FAILURE is specified, the remaining examples are still run, and still count towards the total number of failures reported; only the output is suppressed.


When specified, failures that involve multi-line expected and actual outputs are displayed using a unified diff.


Test examples associated with object f; for example, f may be a string, a module, a function, or a class object.
A shallow copy of dictionary argument globs is used for the execution context.
Optional argument name is used in failure messages, and defaults to "NoName".
If optional argument verbose is true, output is generated even if there are no failures. By default, output is generated only in case of an example failure.
Optional argument compileflags gives the set of flags that should be used by the Python compiler when running the examples. By default, or if None, flags are deduced corresponding to the set of future features found in globs.
Optional argument optionflags works as for function testfile() above.


Convert text with examples to a script.
Argument s is a string containing doctest examples. The string is converted to a Python script, where doctest examples in s are converted to regular code, and everything else is converted to Python comments. The generated script is returned as a string. For example,
displays:
This function is used internally by other functions (see below), but can also be useful when you want to transform an interactive Python session into a Python script.


Set the doctest reporting flags to use.
Argument flags takes the bitwise OR of option flags. See section Option Flags. Only “reporting flags” can be used.
This is a module-global setting, and affects all future doctests run by module unittest: the runTest() method of DocTestCase looks at the option flags specified for the test case when the DocTestCase instance was constructed. If no reporting flags were specified (which is the typical and expected case), doctest’s unittest reporting flags are bitwise ORed into the option flags, and the option flags so augmented are passed to the DocTestRunner instance created to run the doctest. If any reporting flags were specified when the DocTestCase instance was constructed, doctest’s unittest reporting flags are ignored.
The value of the unittest reporting flags in effect before the function was called is returned by the function.


When specified, do not run the example at all. This can be useful in contexts where doctest examples serve as both documentation and test cases, and an example should be included for documentation purposes, but should not be checked. E.g., the example’s output might be random; or the example might depend on resources which would be unavailable to the test driver.
The SKIP flag can also be used for temporarily “commenting out” examples.


All arguments except filename are optional, and should be specified in keyword form.
Test examples in the file named filename. Return (failure_count,
test_count).
Optional argument module_relative specifies how the filename should be interpreted:
Optional argument name gives the name of the test; by default, or if None, os.path.basename(filename) is used.
Optional argument package is a Python package or the name of a Python package whose directory should be used as the base directory for a module-relative filename. If no package is specified, then the calling module’s directory is used as the base directory for module-relative filenames. It is an error to specify package if module_relative is False.
Optional argument globs gives a dict to be used as the globals when executing examples. A new shallow copy of this dict is created for the doctest, so its examples start with a clean slate. By default, or if None, a new empty dict is used.
Optional argument extraglobs gives a dict merged into the globals used to execute examples. This works like dict.update(): if globs and extraglobs have a common key, the associated value in extraglobs appears in the combined dict. By default, or if None, no extra globals are used. This is an advanced feature that allows parameterization of doctests. For example, a doctest can be written for a base class, using a generic name for the class, then reused to test any number of subclasses by passing an extraglobs dict mapping the generic name to the subclass to be tested.
Optional argument verbose prints lots of stuff if true, and prints only failures if false; by default, or if None, it’s true if and only if '-v' is in sys.argv.
Optional argument report prints a summary at the end when true, else prints nothing at the end. In verbose mode, the summary is detailed, else the summary is very brief (in fact, empty if all tests passed).
Optional argument optionflags (default value 0) takes the bitwise OR of option flags. See section Option Flags.
Optional argument raise_on_error defaults to false. If true, an exception is raised upon the first failure or unexpected exception in an example. This allows failures to be post-mortem debugged. Default behavior is to continue running examples.
Optional argument parser specifies a DocTestParser (or subclass) that should be used to extract tests from the files. It defaults to a normal parser (i.e., DocTestParser()).
Optional argument encoding specifies an encoding that should be used to convert the file to unicode.


All arguments are optional, and all except for m should be specified in keyword form.
Test examples in docstrings in functions and classes reachable from module m (or module __main__ if m is not supplied or is None), starting with m.__doc__.
Also test examples reachable from dict m.__test__, if it exists and is not None. m.__test__ maps names (strings) to functions, classes and strings; function and class docstrings are searched for examples; strings are searched directly, as if they were docstrings.
Only docstrings attached to objects belonging to module m are searched.
Return (failure_count, test_count).
Optional argument name gives the name of the module; by default, or if None, m.__name__ is used.
Optional argument exclude_empty defaults to false. If true, objects for which no doctests are found are excluded from consideration. The default is a backward compatibility hack, so that code still using doctest.master.summarize() in conjunction with testmod() continues to get output for objects with no tests. The exclude_empty argument to the newer DocTestFinder constructor defaults to true.
Optional arguments extraglobs, verbose, report, optionflags, raise_on_error, and globs are the same as for function testfile() above, except that globs defaults to m.__dict__.


Convert the doctest for an object to a script.
Argument module is a module object, or dotted name of a module, containing the object whose doctests are of interest. Argument name is the name (within the module) of the object with the doctests of interest. The result is a string, containing the object’s docstring converted to a Python script, as described for script_from_examples() above. For example, if module a.py contains a top-level function f(), then
prints a script version of function f()’s docstring, with doctests converted to code, and the rest placed in comments.


An exception raised by DocTestRunner to signal that a doctest example raised an unexpected exception. The constructor arguments are used to initialize the attributes of the same names.


A tuple containing information about the unexpected exception, as returned by sys.exc_info().


The DocTest object that was being run when the example failed.


The same as the ellipsis literal “...”. Special value used mostly in conjunction with extended slicing syntax for user-defined container data types.


Source code: Lib/email/__init__.py
The email package is a library for managing email messages. It is specifically not designed to do any sending of email messages to SMTP (RFC 2821), NNTP, or other servers; those are functions of modules such as smtplib and nntplib. The email package attempts to be as RFC-compliant as possible, supporting RFC 5322 and RFC 6532, as well as such MIME-related RFCs as RFC 2045, RFC 2046, RFC 2047, RFC 2183, and RFC 2231.
The overall structure of the email package can be divided into three major components, plus a fourth component that controls the behavior of the other components.
The central component of the package is an “object model” that represents email messages. An application interacts with the package primarily through the object model interface defined in the message sub-module. The application can use this API to ask questions about an existing email, to construct a new email, or to add or remove email subcomponents that themselves use the same object model interface. That is, following the nature of email messages and their MIME subcomponents, the email object model is a tree structure of objects that all provide the EmailMessage API.
The other two major components of the package are the parser and the generator. The parser takes the serialized version of an email message (a stream of bytes) and converts it into a tree of EmailMessage objects. The generator takes an EmailMessage and turns it back into a serialized byte stream. (The parser and generator also handle streams of text characters, but this usage is discouraged as it is too easy to end up with messages that are not valid in one way or another.)
The control component is the policy module. Every EmailMessage, every generator, and every parser has an associated policy object that controls its behavior. Usually an application only needs to specify the policy when an EmailMessage is created, either by directly instantiating an EmailMessage to create a new email, or by parsing an input stream using a parser. But the policy can be changed when the message is serialized using a generator. This allows, for example, a generic email message to be parsed from disk, but to serialize it using standard SMTP settings when sending it to an email server.
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.
The following sections describe the functionality of the email package. We start with the message object model, which is the primary interface an application will use, and follow that with the parser and generator components. Then we cover the policy controls, which completes the treatment of the main components of the library.
The next three sections cover the exceptions the package may raise and the defects (non-compliance with the RFCs) that the parser may detect. Then we cover the headerregistry and the contentmanager sub-components, which provide tools for doing more detailed manipulation of headers and payloads, respectively. Both of these components contain features relevant to consuming and producing non-trivial messages, but also document their extensibility APIs, which will be of interest to advanced applications.
Following those is a set of examples of using the fundamental parts of the APIs covered in the preceding sections.
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.
Changed in version 3.6: Docs reorganized and rewritten to promote the new EmailMessage/EmailPolicy API.
Contents of the email package documentation:
Legacy API:
See also
SMTP (Simple Mail Transport Protocol) client
POP (Post Office Protocol) client
IMAP (Internet Message Access Protocol) client
NNTP (Net News Transport Protocol) client
Tools for creating, reading, and managing collections of messages on disk using a variety standard formats.
SMTP server framework (primarily useful for testing)


Add a character set alias. alias is the alias name, e.g. latin-1. canonical is the character set’s canonical name, e.g. iso-8859-1.
The global charset alias registry is kept in the module global dictionary ALIASES.


Add character properties to the global registry.
charset is the input character set, and must be the canonical name of a character set.
Optional header_enc and body_enc is either Charset.QP for quoted-printable, Charset.BASE64 for base64 encoding, Charset.SHORTEST for the shortest of quoted-printable or base64 encoding, or None for no encoding. SHORTEST is only valid for header_enc. The default is None for no encoding.
Optional output_charset is the character set that the output should be in. Conversions will proceed from input charset, to Unicode, to the output charset when the method Charset.convert() is called. The default is to output in the same character set as the input.
Both input_charset and output_charset must have Unicode codec entries in the module’s character set-to-codec mapping; use add_codec() to add codecs the module does not know about. See the codecs module’s documentation for more information.
The global character set registry is kept in the module global dictionary CHARSETS.


Add a codec that map characters in the given character set to and from Unicode.
charset is the canonical name of a character set. codecname is the name of a Python codec, as appropriate for the second argument to the str’s encode() method.


Map character sets to their email properties.
This class provides information about the requirements imposed on email for a specific character set. It also provides convenience routines for converting between character sets, given the availability of the applicable codecs. Given a character set, it will do its best to provide information on how to use that character set in an email message in an RFC-compliant way.
Certain character sets must be encoded with quoted-printable or base64 when used in email headers or bodies. Certain character sets must be converted outright, and are not allowed in email.
Optional input_charset is as described below; it is always coerced to lower case. After being alias normalized it is also used as a lookup into the registry of character sets to find out the header encoding, body encoding, and output conversion codec to be used for the character set. For example, if input_charset is iso-8859-1, then headers and bodies will be encoded using quoted-printable and no output conversion codec is necessary. If input_charset is euc-jp, then headers will be encoded with base64, bodies will not be encoded, but output text will be converted from the euc-jp character set to the iso-2022-jp character set.
Charset instances have the following data attributes:
The initial character set specified. Common aliases are converted to their official email names (e.g. latin_1 is converted to iso-8859-1). Defaults to 7-bit us-ascii.
If the character set must be encoded before it can be used in an email header, this attribute will be set to Charset.QP (for quoted-printable), Charset.BASE64 (for base64 encoding), or Charset.SHORTEST for the shortest of QP or BASE64 encoding. Otherwise, it will be None.
Same as header_encoding, but describes the encoding for the mail message’s body, which indeed may be different than the header encoding. Charset.SHORTEST is not allowed for body_encoding.
Some character sets must be converted before they can be used in email headers or bodies. If the input_charset is one of them, this attribute will contain the name of the character set output will be converted to. Otherwise, it will be None.
The name of the Python codec used to convert the input_charset to Unicode. If no conversion codec is necessary, this attribute will be None.
The name of the Python codec used to convert Unicode to the output_charset. If no conversion codec is necessary, this attribute will have the same value as the input_codec.
Charset instances also have the following methods:
Return the content transfer encoding used for body encoding.
This is either the string quoted-printable or base64 depending on the encoding used, or it is a function, in which case you should call the function with a single argument, the Message object being encoded. The function should then set the Content-Transfer-Encoding header itself to whatever is appropriate.
Returns the string quoted-printable if body_encoding is QP, returns the string base64 if body_encoding is BASE64, and returns the string 7bit otherwise.
Return the output character set.
This is the output_charset attribute if that is not None, otherwise it is input_charset.
Header-encode the string string.
The type of encoding (base64 or quoted-printable) will be based on the header_encoding attribute.
Header-encode a string by converting it first to bytes.
This is similar to header_encode() except that the string is fit into maximum line lengths as given by the argument maxlengths, which must be an iterator: each element returned from this iterator will provide the next maximum line length.
Body-encode the string string.
The type of encoding (base64 or quoted-printable) will be based on the body_encoding attribute.
The Charset class also provides a number of methods to support standard operations and built-in functions.
Returns input_charset as a string coerced to lower case. __repr__() is an alias for __str__().
This method allows you to compare two Charset instances for equality.
This method allows you to compare two Charset instances for inequality.


Body-encode the string string.
The type of encoding (base64 or quoted-printable) will be based on the body_encoding attribute.


Same as header_encoding, but describes the encoding for the mail message’s body, which indeed may be different than the header encoding. Charset.SHORTEST is not allowed for body_encoding.


Return the content transfer encoding used for body encoding.
This is either the string quoted-printable or base64 depending on the encoding used, or it is a function, in which case you should call the function with a single argument, the Message object being encoded. The function should then set the Content-Transfer-Encoding header itself to whatever is appropriate.
Returns the string quoted-printable if body_encoding is QP, returns the string base64 if body_encoding is BASE64, and returns the string 7bit otherwise.


Return the output character set.
This is the output_charset attribute if that is not None, otherwise it is input_charset.


Header-encode the string string.
The type of encoding (base64 or quoted-printable) will be based on the header_encoding attribute.


Header-encode a string by converting it first to bytes.
This is similar to header_encode() except that the string is fit into maximum line lengths as given by the argument maxlengths, which must be an iterator: each element returned from this iterator will provide the next maximum line length.


If the character set must be encoded before it can be used in an email header, this attribute will be set to Charset.QP (for quoted-printable), Charset.BASE64 (for base64 encoding), or Charset.SHORTEST for the shortest of QP or BASE64 encoding. Otherwise, it will be None.


The initial character set specified. Common aliases are converted to their official email names (e.g. latin_1 is converted to iso-8859-1). Defaults to 7-bit us-ascii.


The name of the Python codec used to convert the input_charset to Unicode. If no conversion codec is necessary, this attribute will be None.


Some character sets must be converted before they can be used in email headers or bodies. If the input_charset is one of them, this attribute will contain the name of the character set output will be converted to. Otherwise, it will be None.


The name of the Python codec used to convert Unicode to the output_charset. If no conversion codec is necessary, this attribute will have the same value as the input_codec.


This method allows you to compare two Charset instances for equality.


This method allows you to compare two Charset instances for inequality.


Returns input_charset as a string coerced to lower case. __repr__() is an alias for __str__().


Base class for content managers. Provides the standard registry mechanisms to register converters between MIME content and other representations, as well as the get_content and set_content dispatch methods.
Look up a handler function based on the mimetype of msg (see next paragraph), call it, passing through all arguments, and return the result of the call. The expectation is that the handler will extract the payload from msg and return an object that encodes information about the extracted data.
To find the handler, look for the following keys in the registry, stopping with the first one found:
If none of these keys produce a handler, raise a KeyError for the full MIME type.
If the maintype is multipart, raise a TypeError; otherwise look up a handler function based on the type of obj (see next paragraph), call clear_content() on the msg, and call the handler function, passing through all arguments. The expectation is that the handler will transform and store obj into msg, possibly making other changes to msg as well, such as adding various MIME headers to encode information needed to interpret the stored data.
To find the handler, obtain the type of obj (typ = type(obj)), and look for the following keys in the registry, stopping with the first one found:
If none of the above match, repeat all of the checks above for each of the types in the MRO (typ.__mro__). Finally, if no other key yields a handler, check for a handler for the key None. If there is no handler for None, raise a KeyError for the fully qualified name of the type.
Also add a MIME-Version header if one is not present (see also MIMEPart).
Record the function handler as the handler for key. For the possible values of key, see get_content().
Record handler as the function to call when an object of a type matching typekey is passed to set_content(). For the possible values of typekey, see set_content().


Record the function handler as the handler for key. For the possible values of key, see get_content().


Record handler as the function to call when an object of a type matching typekey is passed to set_content(). For the possible values of typekey, see set_content().


Look up a handler function based on the mimetype of msg (see next paragraph), call it, passing through all arguments, and return the result of the call. The expectation is that the handler will extract the payload from msg and return an object that encodes information about the extracted data.
To find the handler, look for the following keys in the registry, stopping with the first one found:
If none of these keys produce a handler, raise a KeyError for the full MIME type.


If the maintype is multipart, raise a TypeError; otherwise look up a handler function based on the type of obj (see next paragraph), call clear_content() on the msg, and call the handler function, passing through all arguments. The expectation is that the handler will transform and store obj into msg, possibly making other changes to msg as well, such as adding various MIME headers to encode information needed to interpret the stored data.
To find the handler, obtain the type of obj (typ = type(obj)), and look for the following keys in the registry, stopping with the first one found:
If none of the above match, repeat all of the checks above for each of the types in the MRO (typ.__mro__). Finally, if no other key yields a handler, check for a handler for the key None. If there is no handler for None, raise a KeyError for the fully qualified name of the type.
Also add a MIME-Version header if one is not present (see also MIMEPart).


Return the payload of the part as either a string (for text parts), an EmailMessage object (for message/rfc822 parts), or a bytes object (for all other non-multipart types). Raise a KeyError if called on a multipart. If the part is a text part and errors is specified, use it as the error handler when decoding the payload to unicode. The default error handler is replace.


This content manager provides only a minimum interface beyond that provided by Message itself: it deals only with text, raw byte strings, and Message objects. Nevertheless, it provides significant advantages compared to the base API: get_content on a text part will return a unicode string without the application needing to manually decode it, set_content provides a rich set of options for controlling the headers added to a part and controlling the content transfer encoding, and it enables the use of the various add_ methods, thereby simplifying the creation of multipart messages.
Return the payload of the part as either a string (for text parts), an EmailMessage object (for message/rfc822 parts), or a bytes object (for all other non-multipart types). Raise a KeyError if called on a multipart. If the part is a text part and errors is specified, use it as the error handler when decoding the payload to unicode. The default error handler is replace.
Add headers and payload to msg:
Add a Content-Type header with a maintype/subtype value.
If charset is provided (which is valid only for str), encode the string to bytes using the specified character set. The default is utf-8. If the specified charset is a known alias for a standard MIME charset name, use the standard charset instead.
If cte is set, encode the payload using the specified content transfer encoding, and set the Content-Transfer-Encoding header to that value. Possible values for cte are quoted-printable, base64, 7bit, 8bit, and binary. If the input cannot be encoded in the specified encoding (for example, specifying a cte of 7bit for an input that contains non-ASCII values), raise a ValueError.
Note
A cte of binary does not actually work correctly yet. The EmailMessage object as modified by set_content is correct, but BytesGenerator does not serialize it correctly.
If disposition is set, use it as the value of the Content-Disposition header. If not specified, and filename is specified, add the header with the value attachment. If disposition is not specified and filename is also not specified, do not add the header. The only valid values for disposition are attachment and inline.
If filename is specified, use it as the value of the filename parameter of the Content-Disposition header.
If cid is specified, add a Content-ID header with cid as its value.
If params is specified, iterate its items method and use the resulting (key, value) pairs to set additional parameters on the Content-Type header.
If headers is specified and is a list of strings of the form headername: headervalue or a list of header objects (distinguished from strings by having a name attribute), add the headers to msg.


Add headers and payload to msg:
Add a Content-Type header with a maintype/subtype value.
If charset is provided (which is valid only for str), encode the string to bytes using the specified character set. The default is utf-8. If the specified charset is a known alias for a standard MIME charset name, use the standard charset instead.
If cte is set, encode the payload using the specified content transfer encoding, and set the Content-Transfer-Encoding header to that value. Possible values for cte are quoted-printable, base64, 7bit, 8bit, and binary. If the input cannot be encoded in the specified encoding (for example, specifying a cte of 7bit for an input that contains non-ASCII values), raise a ValueError.
Note
A cte of binary does not actually work correctly yet. The EmailMessage object as modified by set_content is correct, but BytesGenerator does not serialize it correctly.
If disposition is set, use it as the value of the Content-Disposition header. If not specified, and filename is specified, add the header with the value attachment. If disposition is not specified and filename is also not specified, do not add the header. The only valid values for disposition are attachment and inline.
If filename is specified, use it as the value of the filename parameter of the Content-Disposition header.
If cid is specified, add a Content-ID header with cid as its value.
If params is specified, iterate its items method and use the resulting (key, value) pairs to set additional parameters on the Content-Type header.
If headers is specified and is a list of strings of the form headername: headervalue or a list of header objects (distinguished from strings by having a name attribute), add the headers to msg.


This doesn’t actually modify the message’s payload, but it does set the Content-Transfer-Encoding header to either 7bit or 8bit as appropriate, based on the payload data.


Encodes the payload into base64 form and sets the Content-Transfer-Encoding header to base64. This is a good encoding to use when most of your payload is unprintable data since it is a more compact form than quoted-printable. The drawback of base64 encoding is that it renders the text non-human readable.


This does nothing; it doesn’t even set the Content-Transfer-Encoding header.


Encodes the payload into quoted-printable form and sets the Content-Transfer-Encoding header to quoted-printable 1. This is a good encoding to use when most of your payload is normal printable data, but contains a few unprintable characters.


Raised under some error conditions when parsing the RFC 5322 headers of a message, this class is derived from MessageParseError. The set_boundary() method will raise this error if the content type is unknown when the method is called. Header may raise this error for certain base64 decoding errors, and when an attempt is made to create a header that appears to contain an embedded header (that is, there is what is supposed to be a continuation line that has no leading whitespace and looks like a header).


This is the base class for all exceptions that the email package can raise. It is derived from the standard Exception class and defines no additional methods.


This is the base class for exceptions raised by the Parser class. It is derived from MessageError. This class is also used internally by the parser used by headerregistry.


Raised when a payload is added to a Message object using add_payload(), but the payload is already a scalar and the message’s Content-Type main type is not either multipart or missing. MultipartConversionError multiply inherits from MessageError and the built-in TypeError.
Since Message.add_payload() is deprecated, this exception is rarely raised in practice. However the exception may also be raised if the attach() method is called on an instance of a class derived from MIMENonMultipart (e.g. MIMEImage).


Return a BytesGenerator object that will write any message provided to the flatten() method, or any surrogateescape encoded text provided to the write() method, to the file-like object outfp. outfp must support a write method that accepts binary data.
If optional 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 for the 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).
If maxheaderlen is not None, refold any header lines that are longer than maxheaderlen, or if 0, do not rewrap any headers. If manheaderlen is None (the default), wrap headers and other message lines according to the policy settings.
If 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.
New in version 3.2.
Changed in version 3.3: Added the policy keyword.
Changed in version 3.6: The default behavior of the mangle_from_ and maxheaderlen parameters is to follow the policy.
Print the textual representation of the message object structure rooted at msg to the output file specified when the BytesGenerator instance was created.
If the policy option cte_type is 8bit (the default), copy any headers in the original parsed message that have not been modified to the output with any bytes with the high bit set reproduced as in the original, and preserve the non-ASCII Content-Transfer-Encoding of any body parts that have them. If cte_type is 7bit, convert the bytes with the high bit set as needed using an ASCII-compatible Content-Transfer-Encoding. That is, transform parts with non-ASCII Content-Transfer-Encoding (Content-Transfer-Encoding: 8bit) to an ASCII compatible Content-Transfer-Encoding, and encode RFC-invalid non-ASCII bytes in headers using the MIME unknown-8bit character set, thus rendering them RFC-compliant.
If unixfrom is True, print the envelope header delimiter used by the Unix mailbox format (see mailbox) before the first of the RFC 5322 headers of the root message object. If the root object has no envelope header, craft a standard one. The default is False. Note that for subparts, no envelope header is ever printed.
If linesep is not None, use it as the separator character between all the lines of the flattened message. If linesep is None (the default), use the value specified in the policy.
Return an independent clone of this BytesGenerator instance with the exact same option settings, and fp as the new outfp.
Encode s using the ASCII codec and the surrogateescape error handler, and pass it to the write method of the outfp passed to the BytesGenerator’s constructor.


Return an independent clone of this BytesGenerator instance with the exact same option settings, and fp as the new outfp.


Print the textual representation of the message object structure rooted at msg to the output file specified when the BytesGenerator instance was created.
If the policy option cte_type is 8bit (the default), copy any headers in the original parsed message that have not been modified to the output with any bytes with the high bit set reproduced as in the original, and preserve the non-ASCII Content-Transfer-Encoding of any body parts that have them. If cte_type is 7bit, convert the bytes with the high bit set as needed using an ASCII-compatible Content-Transfer-Encoding. That is, transform parts with non-ASCII Content-Transfer-Encoding (Content-Transfer-Encoding: 8bit) to an ASCII compatible Content-Transfer-Encoding, and encode RFC-invalid non-ASCII bytes in headers using the MIME unknown-8bit character set, thus rendering them RFC-compliant.
If unixfrom is True, print the envelope header delimiter used by the Unix mailbox format (see mailbox) before the first of the RFC 5322 headers of the root message object. If the root object has no envelope header, craft a standard one. The default is False. Note that for subparts, no envelope header is ever printed.
If linesep is not None, use it as the separator character between all the lines of the flattened message. If linesep is None (the default), use the value specified in the policy.


Encode s using the ASCII codec and the surrogateescape error handler, and pass it to the write method of the outfp passed to the BytesGenerator’s constructor.


Act like Generator, except that for any subpart of the message passed to Generator.flatten(), if the subpart is of main type text, print the decoded payload of the subpart, and if the main type is not text, instead of printing it fill in the string fmt using information from the part and print the resulting filled-in string.
To fill in fmt, execute fmt % part_info, where part_info is a dictionary composed of the following keys and values:
If fmt is None, use the following default fmt:
“[Non-text (%(type)s) part of message omitted, filename %(filename)s]”
Optional _mangle_from_ and maxheaderlen are as with the Generator base class.


Return a Generator object that will write any message provided to the flatten() method, or any text provided to the write() method, to the file-like object outfp. outfp must support a write method that accepts string data.
If optional 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 for the 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).
If maxheaderlen is not None, refold any header lines that are longer than maxheaderlen, or if 0, do not rewrap any headers. If manheaderlen is None (the default), wrap headers and other message lines according to the policy settings.
If 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.
Changed in version 3.3: Added the policy keyword.
Changed in version 3.6: The default behavior of the mangle_from_ and maxheaderlen parameters is to follow the policy.
Print the textual representation of the message object structure rooted at msg to the output file specified when the Generator instance was created.
If the policy option cte_type is 8bit, generate the message as if the option were set to 7bit. (This is required because strings cannot represent non-ASCII bytes.) Convert any bytes with the high bit set as needed using an ASCII-compatible Content-Transfer-Encoding. That is, transform parts with non-ASCII Content-Transfer-Encoding (Content-Transfer-Encoding: 8bit) to an ASCII compatible Content-Transfer-Encoding, and encode RFC-invalid non-ASCII bytes in headers using the MIME unknown-8bit character set, thus rendering them RFC-compliant.
If unixfrom is True, print the envelope header delimiter used by the Unix mailbox format (see mailbox) before the first of the RFC 5322 headers of the root message object. If the root object has no envelope header, craft a standard one. The default is False. Note that for subparts, no envelope header is ever printed.
If linesep is not None, use it as the separator character between all the lines of the flattened message. If linesep is None (the default), use the value specified in the policy.
Changed in version 3.2: Added support for re-encoding 8bit message bodies, and the linesep argument.
Return an independent clone of this Generator instance with the exact same options, and fp as the new outfp.
Write s to the write method of the outfp passed to the Generator’s constructor. This provides just enough file-like API for Generator instances to be used in the print() function.


Return an independent clone of this Generator instance with the exact same options, and fp as the new outfp.


Print the textual representation of the message object structure rooted at msg to the output file specified when the Generator instance was created.
If the policy option cte_type is 8bit, generate the message as if the option were set to 7bit. (This is required because strings cannot represent non-ASCII bytes.) Convert any bytes with the high bit set as needed using an ASCII-compatible Content-Transfer-Encoding. That is, transform parts with non-ASCII Content-Transfer-Encoding (Content-Transfer-Encoding: 8bit) to an ASCII compatible Content-Transfer-Encoding, and encode RFC-invalid non-ASCII bytes in headers using the MIME unknown-8bit character set, thus rendering them RFC-compliant.
If unixfrom is True, print the envelope header delimiter used by the Unix mailbox format (see mailbox) before the first of the RFC 5322 headers of the root message object. If the root object has no envelope header, craft a standard one. The default is False. Note that for subparts, no envelope header is ever printed.
If linesep is not None, use it as the separator character between all the lines of the flattened message. If linesep is None (the default), use the value specified in the policy.
Changed in version 3.2: Added support for re-encoding 8bit message bodies, and the linesep argument.


Write s to the write method of the outfp passed to the Generator’s constructor. This provides just enough file-like API for Generator instances to be used in the print() function.


Decode a message header value without converting the character set. The header value is in header.
This function returns a list of (decoded_string, charset) pairs containing each of the decoded parts of the header. charset is None for non-encoded parts of the header, otherwise a lower case string containing the name of the character set specified in the encoded string.
Here’s an example:


Create a MIME-compliant header that can contain strings in different character sets.
Optional s is the initial header value. If None (the default), the initial header value is not set. You can later append to the header with append() method calls. s may be an instance of bytes or str, but see the append() documentation for semantics.
Optional charset serves two purposes: it has the same meaning as the charset argument to the append() method. It also sets the default character set for all subsequent append() calls that omit the charset argument. If charset is not provided in the constructor (the default), the us-ascii character set is used both as s’s initial charset and as the default for subsequent append() calls.
The maximum line length can be specified explicitly via maxlinelen. For splitting the first line to a shorter value (to account for the field header which isn’t included in s, e.g. Subject) pass in the name of the field in header_name. The default maxlinelen is 76, and the default value for header_name is None, meaning it is not taken into account for the first line of a long, split header.
Optional continuation_ws must be RFC 2822-compliant folding whitespace, and is usually either a space or a hard tab character. This character will be prepended to continuation lines. continuation_ws defaults to a single space character.
Optional errors is passed straight through to the append() method.
Append the string s to the MIME header.
Optional charset, if given, should be a Charset instance (see email.charset) or the name of a character set, which will be converted to a Charset instance. A value of None (the default) means that the charset given in the constructor is used.
s may be an instance of bytes or str. If it is an instance of bytes, then charset is the encoding of that byte string, and a UnicodeError will be raised if the string cannot be decoded with that character set.
If s is an instance of str, then charset is a hint specifying the character set of the characters in the string.
In either case, when producing an RFC 2822-compliant header using RFC 2047 rules, the string will be encoded using the output codec of the charset. If the string cannot be encoded using the output codec, a UnicodeError will be raised.
Optional errors is passed as the errors argument to the decode call if s is a byte string.
Encode a message header into an RFC-compliant format, possibly wrapping long lines and encapsulating non-ASCII parts in base64 or quoted-printable encodings.
Optional splitchars is a string containing characters which should be given extra weight by the splitting algorithm during normal header wrapping. This is in very rough support of RFC 2822’s ‘higher level syntactic breaks’: split points preceded by a splitchar are preferred during line splitting, with the characters preferred in the order in which they appear in the string. Space and tab may be included in the string to indicate whether preference should be given to one over the other as a split point when other split chars do not appear in the line being split. Splitchars does not affect RFC 2047 encoded lines.
maxlinelen, if given, overrides the instance’s value for the maximum line length.
linesep specifies the characters used to separate the lines of the folded header. It defaults to the most useful value for Python application code (\n), but \r\n can be specified in order to produce headers with RFC-compliant line separators.
Changed in version 3.2: Added the linesep argument.
The Header class also provides a number of methods to support standard operators and built-in functions.
Returns an approximation of the Header as a string, using an unlimited line length. All pieces are converted to unicode using the specified encoding and joined together appropriately. Any pieces with a charset of 'unknown-8bit' are decoded as ASCII using the 'replace' error handler.
Changed in version 3.2: Added handling for the 'unknown-8bit' charset.
This method allows you to compare two Header instances for equality.
This method allows you to compare two Header instances for inequality.


Append the string s to the MIME header.
Optional charset, if given, should be a Charset instance (see email.charset) or the name of a character set, which will be converted to a Charset instance. A value of None (the default) means that the charset given in the constructor is used.
s may be an instance of bytes or str. If it is an instance of bytes, then charset is the encoding of that byte string, and a UnicodeError will be raised if the string cannot be decoded with that character set.
If s is an instance of str, then charset is a hint specifying the character set of the characters in the string.
In either case, when producing an RFC 2822-compliant header using RFC 2047 rules, the string will be encoded using the output codec of the charset. If the string cannot be encoded using the output codec, a UnicodeError will be raised.
Optional errors is passed as the errors argument to the decode call if s is a byte string.


Encode a message header into an RFC-compliant format, possibly wrapping long lines and encapsulating non-ASCII parts in base64 or quoted-printable encodings.
Optional splitchars is a string containing characters which should be given extra weight by the splitting algorithm during normal header wrapping. This is in very rough support of RFC 2822’s ‘higher level syntactic breaks’: split points preceded by a splitchar are preferred during line splitting, with the characters preferred in the order in which they appear in the string. Space and tab may be included in the string to indicate whether preference should be given to one over the other as a split point when other split chars do not appear in the line being split. Splitchars does not affect RFC 2047 encoded lines.
maxlinelen, if given, overrides the instance’s value for the maximum line length.
linesep specifies the characters used to separate the lines of the folded header. It defaults to the most useful value for Python application code (\n), but \r\n can be specified in order to produce headers with RFC-compliant line separators.
Changed in version 3.2: Added the linesep argument.


This method allows you to compare two Header instances for equality.


This method allows you to compare two Header instances for inequality.


Returns an approximation of the Header as a string, using an unlimited line length. All pieces are converted to unicode using the specified encoding and joined together appropriately. Any pieces with a charset of 'unknown-8bit' are decoded as ASCII using the 'replace' error handler.
Changed in version 3.2: Added handling for the 'unknown-8bit' charset.


Create a Header instance from a sequence of pairs as returned by decode_header().
decode_header() takes a header value string and returns a sequence of pairs of the format (decoded_string, charset) where charset is the name of the character set.
This function takes one of those sequence of pairs and returns a Header instance. Optional maxlinelen, header_name, and continuation_ws are as in the Header constructor.


The class used to represent an email address. The general form of an address is:
or:
where each part must conform to specific syntax rules spelled out in RFC 5322.
As a convenience addr_spec can be specified instead of username and domain, in which case username and domain will be parsed from the addr_spec. An addr_spec must be a properly RFC quoted string; if it is not Address will raise an error. Unicode characters are allowed and will be property encoded when serialized. However, per the RFCs, unicode is not allowed in the username portion of the address.
The display name portion of the address, if any, with all quoting removed. If the address does not have a display name, this attribute will be an empty string.
The username portion of the address, with all quoting removed.
The domain portion of the address.
The username@domain portion of the address, correctly quoted for use as a bare address (the second form shown above). This attribute is not mutable.
The str value of the object is the address quoted according to RFC 5322 rules, but with no Content Transfer Encoding of any non-ASCII characters.
To support SMTP (RFC 5321), Address handles one special case: if username and domain are both the empty string (or None), then the string value of the Address is <>.


The username@domain portion of the address, correctly quoted for use as a bare address (the second form shown above). This attribute is not mutable.


The display name portion of the address, if any, with all quoting removed. If the address does not have a display name, this attribute will be an empty string.


The username portion of the address, with all quoting removed.


The str value of the object is the address quoted according to RFC 5322 rules, but with no Content Transfer Encoding of any non-ASCII characters.


Address headers are one of the most complex structured header types. The AddressHeader class provides a generic interface to any address header.
This header type provides the following additional attributes:
A tuple of Group objects encoding the addresses and groups found in the header value. Addresses that are not part of a group are represented in this list as single-address Groups whose display_name is None.
A tuple of Address objects encoding all of the individual addresses from the header value. If the header value contains any groups, the individual addresses from the group are included in the list at the point where the group occurs in the value (that is, the list of addresses is “flattened” into a one dimensional list).
The decoded value of the header will have all encoded words decoded to unicode. idna encoded domain names are also decoded to unicode. The decoded value is set by joining the str value of the elements of the groups attribute with ',
'.
A list of Address and Group objects in any combination may be used to set the value of an address header. Group objects whose display_name is None will be interpreted as single addresses, which allows an address list to be copied with groups intact by using the list obtained from the groups attribute of the source header.


A tuple of Address objects encoding all of the individual addresses from the header value. If the header value contains any groups, the individual addresses from the group are included in the list at the point where the group occurs in the value (that is, the list of addresses is “flattened” into a one dimensional list).


A tuple of Group objects encoding the addresses and groups found in the header value. Addresses that are not part of a group are represented in this list as single-address Groups whose display_name is None.


name and value are passed to BaseHeader from the header_factory call. The string value of any header object is the value fully decoded to unicode.
This base class defines the following read-only properties:
The name of the header (the portion of the field before the ‘:’). This is exactly the value passed in the header_factory call for name; that is, case is preserved.
A tuple of HeaderDefect instances reporting any RFC compliance problems found during parsing. The email package tries to be complete about detecting compliance issues. See the errors module for a discussion of the types of defects that may be reported.
The maximum number of headers of this type that can have the same name. A value of None means unlimited. The BaseHeader value for this attribute is None; it is expected that specialized header classes will override this value as needed.
BaseHeader also provides the following method, which is called by the email library code and should not in general be called by application programs:
Return a string containing linesep characters as required to correctly fold the header according to policy. A cte_type of 8bit will be treated as if it were 7bit, since headers may not contain arbitrary binary data. If utf8 is False, non-ASCII data will be RFC 2047 encoded.
BaseHeader by itself cannot be used to create a header object. It defines a protocol that each specialized header cooperates with in order to produce the header object. Specifically, BaseHeader requires that the specialized class provide a classmethod() named parse. This method is called as follows:
kwds is a dictionary containing one pre-initialized key, defects. defects is an empty list. The parse method should append any detected defects to this list. On return, the kwds dictionary must contain values for at least the keys decoded and defects. decoded should be the string value for the header (that is, the header value fully decoded to unicode). The parse method should assume that string may contain content-transfer-encoded parts, but should correctly handle all valid unicode characters as well so that it can parse un-encoded header values.
BaseHeader’s __new__ then creates the header instance, and calls its init method. The specialized class only needs to provide an init method if it wishes to set additional attributes beyond those provided by BaseHeader itself. Such an init method should look like this:
That is, anything extra that the specialized class puts in to the kwds dictionary should be removed and handled, and the remaining contents of kw (and args) passed to the BaseHeader init method.


A tuple of HeaderDefect instances reporting any RFC compliance problems found during parsing. The email package tries to be complete about detecting compliance issues. See the errors module for a discussion of the types of defects that may be reported.


Return a string containing linesep characters as required to correctly fold the header according to policy. A cte_type of 8bit will be treated as if it were 7bit, since headers may not contain arbitrary binary data. If utf8 is False, non-ASCII data will be RFC 2047 encoded.


The maximum number of headers of this type that can have the same name. A value of None means unlimited. The BaseHeader value for this attribute is None; it is expected that specialized header classes will override this value as needed.


The name of the header (the portion of the field before the ‘:’). This is exactly the value passed in the header_factory call for name; that is, case is preserved.


A ParameterizedMIMEHeader class that handles the Content-Disposition header.
inline and attachment are the only valid values in common use.


inline and attachment are the only valid values in common use.


Handles the Content-Transfer-Encoding header.
Valid values are 7bit, 8bit, base64, and quoted-printable. See RFC 2045 for more information.


Valid values are 7bit, 8bit, base64, and quoted-printable. See RFC 2045 for more information.


A ParameterizedMIMEHeader class that handles the Content-Type header.
The content type string, in the form maintype/subtype.


The content type string, in the form maintype/subtype.


RFC 5322 specifies a very specific format for dates within email headers. The DateHeader parser recognizes that date format, as well as recognizing a number of variant forms that are sometimes found “in the wild”.
This header type provides the following additional attributes:
If the header value can be recognized as a valid date of one form or another, this attribute will contain a datetime instance representing that date. If the timezone of the input date is specified as -0000 (indicating it is in UTC but contains no information about the source timezone), then datetime will be a naive datetime. If a specific timezone offset is found (including +0000), then datetime will contain an aware datetime that uses datetime.timezone to record the timezone offset.
The decoded value of the header is determined by formatting the datetime according to the RFC 5322 rules; that is, it is set to:
When creating a DateHeader, value may be datetime instance. This means, for example, that the following code is valid and does what one would expect:
Because this is a naive datetime it will be interpreted as a UTC timestamp, and the resulting value will have a timezone of -0000. Much more useful is to use the localtime() function from the utils module:
This example sets the date header to the current time and date using the current timezone offset.


If the header value can be recognized as a valid date of one form or another, this attribute will contain a datetime instance representing that date. If the timezone of the input date is specified as -0000 (indicating it is in UTC but contains no information about the source timezone), then datetime will be a naive datetime. If a specific timezone offset is found (including +0000), then datetime will contain an aware datetime that uses datetime.timezone to record the timezone offset.


The class used to represent an address group. The general form of an address group is:
As a convenience for processing lists of addresses that consist of a mixture of groups and single addresses, a Group may also be used to represent single addresses that are not part of a group by setting display_name to None and providing a list of the single address as addresses.
The display_name of the group. If it is None and there is exactly one Address in addresses, then the Group represents a single address that is not in a group.
A possibly empty tuple of Address objects representing the addresses in the group.
The str value of a Group is formatted according to RFC 5322, but with no Content Transfer Encoding of any non-ASCII characters. If display_name is none and there is a single Address in the addresses list, the str value will be the same as the str of that single Address.


A possibly empty tuple of Address objects representing the addresses in the group.


The display_name of the group. If it is None and there is exactly one Address in addresses, then the Group represents a single address that is not in a group.


The str value of a Group is formatted according to RFC 5322, but with no Content Transfer Encoding of any non-ASCII characters. If display_name is none and there is a single Address in the addresses list, the str value will be the same as the str of that single Address.


This is the factory used by EmailPolicy by default. HeaderRegistry builds the class used to create a header instance dynamically, using base_class and a specialized class retrieved from a registry that it holds. When a given header name does not appear in the registry, the class specified by default_class is used as the specialized class. When use_default_map is True (the default), the standard mapping of header names to classes is copied in to the registry during initialization. base_class is always the last class in the generated class’s __bases__ list.
The default mappings are:
UniqueUnstructuredHeader
UniqueDateHeader
DateHeader
UniqueDateHeader
UniqueSingleAddressHeader
SingleAddressHeader
UniqueAddressHeader
AddressHeader
UniqueAddressHeader
AddressHeader
UniqueAddressHeader
AddressHeader
UniqueAddressHeader
AddressHeader
UniqueAddressHeader
MIMEVersionHeader
ContentTypeHeader
ContentDispositionHeader
ContentTransferEncodingHeader
MessageIDHeader
HeaderRegistry has the following methods:
name is the name of the header to be mapped. It will be converted to lower case in the registry. cls is the specialized class to be used, along with base_class, to create the class used to instantiate headers that match name.
Construct and return a class to handle creating a name header.
Retrieves the specialized header associated with name from the registry (using default_class if name does not appear in the registry) and composes it with base_class to produce a class, calls the constructed class’s constructor, passing it the same argument list, and finally returns the class instance created thereby.


name is the name of the header to be mapped. It will be converted to lower case in the registry. cls is the specialized class to be used, along with base_class, to create the class used to instantiate headers that match name.


Retrieves the specialized header associated with name from the registry (using default_class if name does not appear in the registry) and composes it with base_class to produce a class, calls the constructed class’s constructor, passing it the same argument list, and finally returns the class instance created thereby.


Construct and return a class to handle creating a name header.


There is really only one valid value for the MIME-Version header, and that is 1.0. For future proofing, this header class supports other valid version numbers. If a version number has a valid value per RFC 2045, then the header object will have non-None values for the following attributes:
The version number as a string, with any whitespace and/or comments removed.
The major version number as an integer
The minor version number as an integer


The version number as a string, with any whitespace and/or comments removed.


MIME headers all start with the prefix ‘Content-‘. Each specific header has a certain value, described under the class for that header. Some can also take a list of supplemental parameters, which have a common format. This class serves as a base for all the MIME headers that take parameters.
A dictionary mapping parameter names to parameter values.


A dictionary mapping parameter names to parameter values.


A subclass of AddressHeader that adds one additional attribute:
The single address encoded by the header value. If the header value actually contains more than one address (which would be a violation of the RFC under the default policy), accessing this attribute will result in a ValueError.


The single address encoded by the header value. If the header value actually contains more than one address (which would be a violation of the RFC under the default policy), accessing this attribute will result in a ValueError.


An “unstructured” header is the default type of header in RFC 5322. Any header that does not have a specified syntax is treated as unstructured. The classic example of an unstructured header is the Subject header.
In RFC 5322, an unstructured header is a run of arbitrary text in the ASCII character set. RFC 2047, however, has an RFC 5322 compatible mechanism for encoding non-ASCII text as ASCII characters within a header value. When a value containing encoded words is passed to the constructor, the UnstructuredHeader parser converts such encoded words into unicode, following the RFC 2047 rules for unstructured text. The parser uses heuristics to attempt to decode certain non-compliant encoded words. Defects are registered in such cases, as well as defects for issues such as invalid characters within the encoded words or the non-encoded text.
This header type provides no additional attributes.


This iterates over all the payloads in all the subparts of msg, returning the string payloads line-by-line. It skips over all the subpart headers, and it skips over any subpart with a payload that isn’t a Python string. This is somewhat equivalent to reading the flat text representation of the message from a file using readline(), skipping over all the intervening headers.
Optional decode is passed through to Message.get_payload.


This iterates over all the subparts of msg, returning only those subparts that match the MIME type specified by maintype and subtype.
Note that subtype is optional; if omitted, then subpart MIME type matching is done only with the main type. maintype is optional too; it defaults to text.
Thus, by default typed_subpart_iterator() returns each subpart that has a MIME type of text/*.


Prints an indented representation of the content types of the message object structure. For example:
Optional fp is a file-like object to print the output to. It must be suitable for Python’s print() function. level is used internally. include_default, if true, prints the default type as well.


If policy is specified use the rules it specifies to update and serialize the representation of the message. If policy is not set, use the default policy, which follows the rules of the email RFCs except for line endings (instead of the RFC mandated \r\n, it uses the Python standard \n line endings). For more information see the policy documentation.
Return the entire message flattened as a string. When optional unixfrom is true, the envelope header is included in the returned string. unixfrom defaults to False. For backward compatibility with the base Message class maxheaderlen is accepted, but defaults to None, which means that by default the line length is controlled by the max_line_length of the policy. The policy argument may be used to override the default policy obtained from the message instance. This can be used to control some of the formatting produced by the method, since the specified policy will be passed to the Generator.
Flattening the message may trigger changes to the EmailMessage if defaults need to be filled in to complete the transformation to a string (for example, MIME boundaries may be generated or modified).
Note that this method is provided as a convenience and may not be the most useful way to serialize messages in your application, especially if you are dealing with multiple messages. See email.generator.Generator for a more flexible API for serializing messages. Note also that this method is restricted to producing messages serialized as “7 bit clean” when utf8 is False, which is the default.
Changed in version 3.6: the default behavior when maxheaderlen is not specified was changed from defaulting to 0 to defaulting to the value of max_line_length from the policy.
Equivalent to as_string(policy=self.policy.clone(utf8=True)). Allows str(msg) to produce a string containing the serialized message in a readable format.
Changed in version 3.4: the method was changed to use utf8=True, thus producing an RFC 6531-like message representation, instead of being a direct alias for as_string().
Return the entire message flattened as a bytes object. When optional unixfrom is true, the envelope header is included in the returned string. unixfrom defaults to False. The policy argument may be used to override the default policy obtained from the message instance. This can be used to control some of the formatting produced by the method, since the specified policy will be passed to the BytesGenerator.
Flattening the message may trigger changes to the EmailMessage if defaults need to be filled in to complete the transformation to a string (for example, MIME boundaries may be generated or modified).
Note that this method is provided as a convenience and may not be the most useful way to serialize messages in your application, especially if you are dealing with multiple messages. See email.generator.BytesGenerator for a more flexible API for serializing messages.
Equivalent to as_bytes(). Allows bytes(msg) to produce a bytes object containing the serialized message.
Return True if the message’s payload is a list of sub-EmailMessage objects, otherwise return False. When is_multipart() returns False, the payload should be a string object (which might be a CTE encoded binary payload). Note that is_multipart() returning True does not necessarily mean that “msg.get_content_maintype() == ‘multipart’” will return the True. For example, is_multipart will return True when the EmailMessage is of type message/rfc822.
Set the message’s envelope header to unixfrom, which should be a string. (See mboxMessage for a brief description of this header.)
Return the message’s envelope header. Defaults to None if the envelope header was never set.
The following methods implement the mapping-like interface for accessing the message’s headers. Note that there are some semantic differences between these methods and a normal mapping (i.e. dictionary) interface. For example, in a dictionary there are no duplicate keys, but here there may be duplicate message headers. Also, in dictionaries there is no guaranteed order to the keys returned by keys(), but in an EmailMessage object, headers are always returned in the order they appeared in the original message, or in which they were added to the message later. Any header deleted and then re-added is always appended to the end of the header list.
These semantic differences are intentional and are biased toward convenience in the most common use cases.
Note that in all cases, any envelope header present in the message is not included in the mapping interface.
Return the total number of headers, including duplicates.
Return True if the message object has a field named name. Matching is done without regard to case and name does not include the trailing colon. Used for the in operator. For example:
Return the value of the named header field. name does not include the colon field separator. If the header is missing, None is returned; a KeyError is never raised.
Note that if the named field appears more than once in the message’s headers, exactly which of those field values will be returned is undefined. Use the get_all() method to get the values of all the extant headers named name.
Using the standard (non-compat32) policies, the returned value is an instance of a subclass of email.headerregistry.BaseHeader.
Add a header to the message with field name name and value val. The field is appended to the end of the message’s existing headers.
Note that this does not overwrite or delete any existing header with the same name. If you want to ensure that the new header is the only one present in the message with field name name, delete the field first, e.g.:
If the policy defines certain headers to be unique (as the standard policies do), this method may raise a ValueError when an attempt is made to assign a value to such a header when one already exists. This behavior is intentional for consistency’s sake, but do not depend on it as we may choose to make such assignments do an automatic deletion of the existing header in the future.
Delete all occurrences of the field with name name from the message’s headers. No exception is raised if the named field isn’t present in the headers.
Return a list of all the message’s header field names.
Return a list of all the message’s field values.
Return a list of 2-tuples containing all the message’s field headers and values.
Return the value of the named header field. This is identical to __getitem__() except that optional failobj is returned if the named header is missing (failobj defaults to None).
Here are some additional useful header related methods:
Return a list of all the values for the field named name. If there are no such named headers in the message, failobj is returned (defaults to None).
Extended header setting. This method is similar to __setitem__() except that additional header parameters can be provided as keyword arguments. _name is the header field to add and _value is the primary value for the header.
For each item in the keyword argument dictionary _params, the key is taken as the parameter name, with underscores converted to dashes (since dashes are illegal in Python identifiers). Normally, the parameter will be added as key="value" unless the value is None, in which case only the key will be added.
If the value contains non-ASCII characters, the charset and language may be explicitly controlled by specifying the value as a three tuple in the format (CHARSET, LANGUAGE, VALUE), where CHARSET is a string naming the charset to be used to encode the value, LANGUAGE can usually be set to None or the empty string (see RFC 2231 for other possibilities), and VALUE is the string value containing non-ASCII code points. If a three tuple is not passed and the value contains non-ASCII characters, it is automatically encoded in RFC 2231 format using a CHARSET of utf-8 and a LANGUAGE of None.
Here is an example:
This will add a header that looks like
An example of the extended interface with non-ASCII characters:
Replace a header. Replace the first header found in the message that matches _name, retaining header order and field name case of the original header. If no matching header is found, raise a KeyError.
Return the message’s content type, coerced to lower case of the form maintype/subtype. If there is no Content-Type header in the message return the value returned by get_default_type(). If the Content-Type header is invalid, return text/plain.
(According to RFC 2045, messages always have a default type, get_content_type() will always return a value. RFC 2045 defines a message’s default type to be text/plain unless it appears inside a multipart/digest container, in which case it would be message/rfc822. If the Content-Type header has an invalid type specification, RFC 2045 mandates that the default type be text/plain.)
Return the message’s main content type. This is the maintype part of the string returned by get_content_type().
Return the message’s sub-content type. This is the subtype part of the string returned by get_content_type().
Return the default content type. Most messages have a default content type of text/plain, except for messages that are subparts of multipart/digest containers. Such subparts have a default content type of message/rfc822.
Set the default content type. ctype should either be text/plain or message/rfc822, although this is not enforced. The default content type is not stored in the Content-Type header, so it only affects the return value of the get_content_type methods when no Content-Type header is present in the message.
Set a parameter in the Content-Type header. If the parameter already exists in the header, replace its value with value. When header is Content-Type (the default) and the header does not yet exist in the message, add it, set its value to text/plain, and append the new parameter value. Optional header specifies an alternative header to Content-Type.
If the value contains non-ASCII characters, the charset and language may be explicitly specified using the optional charset and language parameters. Optional language specifies the RFC 2231 language, defaulting to the empty string. Both charset and language should be strings. The default is to use the utf8 charset and None for the language.
If replace is False (the default) the header is moved to the end of the list of headers. If replace is True, the header will be updated in place.
Use of the requote parameter with EmailMessage objects is deprecated.
Note that existing parameter values of headers may be accessed through the params attribute of the header value (for example, msg['Content-Type'].params['charset']).
Changed in version 3.4: replace keyword was added.
Remove the given parameter completely from the Content-Type header. The header will be re-written in place without the parameter or its value. Optional header specifies an alternative to Content-Type.
Use of the requote parameter with EmailMessage objects is deprecated.
Return the value of the filename parameter of the Content-Disposition header of the message. If the header does not have a filename parameter, this method falls back to looking for the name parameter on the Content-Type header. If neither is found, or the header is missing, then failobj is returned. The returned string will always be unquoted as per email.utils.unquote().
Return the value of the boundary parameter of the Content-Type header of the message, or failobj if either the header is missing, or has no boundary parameter. The returned string will always be unquoted as per email.utils.unquote().
Set the boundary parameter of the Content-Type header to boundary. set_boundary() will always quote boundary if necessary. A HeaderParseError is raised if the message object has no Content-Type header.
Note that using this method is subtly different from deleting the old Content-Type header and adding a new one with the new boundary via add_header(), because set_boundary() preserves the order of the Content-Type header in the list of headers.
Return the charset parameter of the Content-Type header, coerced to lower case. If there is no Content-Type header, or if that header has no charset parameter, failobj is returned.
Return a list containing the character set names in the message. If the message is a multipart, then the list will contain one element for each subpart in the payload, otherwise, it will be a list of length 1.
Each item in the list will be a string which is the value of the charset parameter in the Content-Type header for the represented subpart. If the subpart has no Content-Type header, no charset parameter, or is not of the text main MIME type, then that item in the returned list will be failobj.
Return True if there is a Content-Disposition header and its (case insensitive) value is attachment, False otherwise.
Changed in version 3.4.2: is_attachment is now a method instead of a property, for consistency with is_multipart().
Return the lowercased value (without parameters) of the message’s Content-Disposition header if it has one, or None. The possible values for this method are inline, attachment or None if the message follows RFC 2183.
New in version 3.5.
The following methods relate to interrogating and manipulating the content (payload) of the message.
The walk() method is an all-purpose generator which can be used to iterate over all the parts and subparts of a message object tree, in depth-first traversal order. You will typically use walk() as the iterator in a for loop; each iteration returns the next subpart.
Here’s an example that prints the MIME type of every part of a multipart message structure:
walk iterates over the subparts of any part where is_multipart() returns True, even though msg.get_content_maintype() == 'multipart' may return False. We can see this in our example by making use of the _structure debug helper function:
Here the message parts are not multiparts, but they do contain subparts. is_multipart() returns True and walk descends into the subparts.
Return the MIME part that is the best candidate to be the “body” of the message.
preferencelist must be a sequence of strings from the set related, html, and plain, and indicates the order of preference for the content type of the part returned.
Start looking for candidate matches with the object on which the get_body method is called.
If related is not included in preferencelist, consider the root part (or subpart of the root part) of any related encountered as a candidate if the (sub-)part matches a preference.
When encountering a multipart/related, check the start parameter and if a part with a matching Content-ID is found, consider only it when looking for candidate matches. Otherwise consider only the first (default root) part of the multipart/related.
If a part has a Content-Disposition header, only consider the part a candidate match if the value of the header is inline.
If none of the candidates matches any of the preferences in preferencelist, return None.
Notes: (1) For most applications the only preferencelist combinations that really make sense are ('plain',), ('html', 'plain'), and the default ('related', 'html', 'plain'). (2) Because matching starts with the object on which get_body is called, calling get_body on a multipart/related will return the object itself unless preferencelist has a non-default value. (3) Messages (or message parts) that do not specify a Content-Type or whose Content-Type header is invalid will be treated as if they are of type text/plain, which may occasionally cause get_body to return unexpected results.
Return an iterator over all of the immediate sub-parts of the message that are not candidate “body” parts. That is, skip the first occurrence of each of text/plain, text/html, multipart/related, or multipart/alternative (unless they are explicitly marked as attachments via Content-Disposition: attachment), and return all remaining parts. When applied directly to a multipart/related, return an iterator over the all the related parts except the root part (ie: the part pointed to by the start parameter, or the first part if there is no start parameter or the start parameter doesn’t match the Content-ID of any of the parts). When applied directly to a multipart/alternative or a non-multipart, return an empty iterator.
Return an iterator over all of the immediate sub-parts of the message, which will be empty for a non-multipart. (See also walk().)
Call the get_content() method of the content_manager, passing self as the message object, and passing along any other arguments or keywords as additional arguments. If content_manager is not specified, use the content_manager specified by the current policy.
Call the set_content() method of the content_manager, passing self as the message object, and passing along any other arguments or keywords as additional arguments. If content_manager is not specified, use the content_manager specified by the current policy.
Convert a non-multipart message into a multipart/related message, moving any existing Content- headers and payload into a (new) first part of the multipart. If boundary is specified, use it as the boundary string in the multipart, otherwise leave the boundary to be automatically created when it is needed (for example, when the message is serialized).
Convert a non-multipart or a multipart/related into a multipart/alternative, moving any existing Content- headers and payload into a (new) first part of the multipart. If boundary is specified, use it as the boundary string in the multipart, otherwise leave the boundary to be automatically created when it is needed (for example, when the message is serialized).
Convert a non-multipart, a multipart/related, or a multipart-alternative into a multipart/mixed, moving any existing Content- headers and payload into a (new) first part of the multipart. If boundary is specified, use it as the boundary string in the multipart, otherwise leave the boundary to be automatically created when it is needed (for example, when the message is serialized).
If the message is a multipart/related, create a new message object, pass all of the arguments to its set_content() method, and attach() it to the multipart. If the message is a non-multipart, call make_related() and then proceed as above. If the message is any other type of multipart, raise a TypeError. If content_manager is not specified, use the content_manager specified by the current policy. If the added part has no Content-Disposition header, add one with the value inline.
If the message is a multipart/alternative, create a new message object, pass all of the arguments to its set_content() method, and attach() it to the multipart. If the message is a non-multipart or multipart/related, call make_alternative() and then proceed as above. If the message is any other type of multipart, raise a TypeError. If content_manager is not specified, use the content_manager specified by the current policy.
If the message is a multipart/mixed, create a new message object, pass all of the arguments to its set_content() method, and attach() it to the multipart. If the message is a non-multipart, multipart/related, or multipart/alternative, call make_mixed() and then proceed as above. If content_manager is not specified, use the content_manager specified by the current policy. If the added part has no Content-Disposition header, add one with the value attachment. This method can be used both for explicit attachments (Content-Disposition: attachment) and inline attachments (Content-Disposition: inline), by passing appropriate options to the content_manager.
Remove the payload and all of the headers.
Remove the payload and all of the Content- headers, leaving all other headers intact and in their original order.
EmailMessage objects have the following instance attributes:
The format of a MIME document allows for some text between the blank line following the headers, and the first multipart boundary string. Normally, this text is never visible in a MIME-aware mail reader because it falls outside the standard MIME armor. However, when viewing the raw text of the message, or when viewing the message in a non-MIME aware reader, this text can become visible.
The preamble attribute contains this leading extra-armor text for MIME documents. When the Parser discovers some text after the headers but before the first boundary string, it assigns this text to the message’s preamble attribute. When the Generator is writing out the plain text representation of a MIME message, and it finds the message has a preamble attribute, it will write this text in the area between the headers and the first boundary. See email.parser and email.generator for details.
Note that if the message object has no preamble, the preamble attribute will be None.
The epilogue attribute acts the same way as the preamble attribute, except that it contains text that appears between the last boundary and the end of the message. As with the preamble, if there is no epilog text this attribute will be None.
The defects attribute contains a list of all the problems found when parsing this message. See email.errors for a detailed description of the possible parsing defects.


If the message is a multipart/alternative, create a new message object, pass all of the arguments to its set_content() method, and attach() it to the multipart. If the message is a non-multipart or multipart/related, call make_alternative() and then proceed as above. If the message is any other type of multipart, raise a TypeError. If content_manager is not specified, use the content_manager specified by the current policy.


If the message is a multipart/mixed, create a new message object, pass all of the arguments to its set_content() method, and attach() it to the multipart. If the message is a non-multipart, multipart/related, or multipart/alternative, call make_mixed() and then proceed as above. If content_manager is not specified, use the content_manager specified by the current policy. If the added part has no Content-Disposition header, add one with the value attachment. This method can be used both for explicit attachments (Content-Disposition: attachment) and inline attachments (Content-Disposition: inline), by passing appropriate options to the content_manager.


Extended header setting. This method is similar to __setitem__() except that additional header parameters can be provided as keyword arguments. _name is the header field to add and _value is the primary value for the header.
For each item in the keyword argument dictionary _params, the key is taken as the parameter name, with underscores converted to dashes (since dashes are illegal in Python identifiers). Normally, the parameter will be added as key="value" unless the value is None, in which case only the key will be added.
If the value contains non-ASCII characters, the charset and language may be explicitly controlled by specifying the value as a three tuple in the format (CHARSET, LANGUAGE, VALUE), where CHARSET is a string naming the charset to be used to encode the value, LANGUAGE can usually be set to None or the empty string (see RFC 2231 for other possibilities), and VALUE is the string value containing non-ASCII code points. If a three tuple is not passed and the value contains non-ASCII characters, it is automatically encoded in RFC 2231 format using a CHARSET of utf-8 and a LANGUAGE of None.
Here is an example:
This will add a header that looks like
An example of the extended interface with non-ASCII characters:


If the message is a multipart/related, create a new message object, pass all of the arguments to its set_content() method, and attach() it to the multipart. If the message is a non-multipart, call make_related() and then proceed as above. If the message is any other type of multipart, raise a TypeError. If content_manager is not specified, use the content_manager specified by the current policy. If the added part has no Content-Disposition header, add one with the value inline.


Return the entire message flattened as a bytes object. When optional unixfrom is true, the envelope header is included in the returned string. unixfrom defaults to False. The policy argument may be used to override the default policy obtained from the message instance. This can be used to control some of the formatting produced by the method, since the specified policy will be passed to the BytesGenerator.
Flattening the message may trigger changes to the EmailMessage if defaults need to be filled in to complete the transformation to a string (for example, MIME boundaries may be generated or modified).
Note that this method is provided as a convenience and may not be the most useful way to serialize messages in your application, especially if you are dealing with multiple messages. See email.generator.BytesGenerator for a more flexible API for serializing messages.


Return the entire message flattened as a string. When optional unixfrom is true, the envelope header is included in the returned string. unixfrom defaults to False. For backward compatibility with the base Message class maxheaderlen is accepted, but defaults to None, which means that by default the line length is controlled by the max_line_length of the policy. The policy argument may be used to override the default policy obtained from the message instance. This can be used to control some of the formatting produced by the method, since the specified policy will be passed to the Generator.
Flattening the message may trigger changes to the EmailMessage if defaults need to be filled in to complete the transformation to a string (for example, MIME boundaries may be generated or modified).
Note that this method is provided as a convenience and may not be the most useful way to serialize messages in your application, especially if you are dealing with multiple messages. See email.generator.Generator for a more flexible API for serializing messages. Note also that this method is restricted to producing messages serialized as “7 bit clean” when utf8 is False, which is the default.
Changed in version 3.6: the default behavior when maxheaderlen is not specified was changed from defaulting to 0 to defaulting to the value of max_line_length from the policy.


Remove the payload and all of the headers.