doc_content stringlengths 1 386k | doc_id stringlengths 5 188 |
|---|---|
class email.charset.Charset(input_charset=DEFAULT_CHARSET)
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:
input_charset
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.
header_encoding
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.
body_encoding
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.
output_charset
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.
input_codec
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.
output_codec
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:
get_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.
get_output_charset()
Return the output character set. This is the output_charset attribute if that is not None, otherwise it is input_charset.
header_encode(string)
Header-encode the string string. The type of encoding (base64 or quoted-printable) will be based on the header_encoding attribute.
header_encode_lines(string, maxlengths)
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(string)
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.
__str__()
Returns input_charset as a string coerced to lower case. __repr__() is an alias for __str__().
__eq__(other)
This method allows you to compare two Charset instances for equality.
__ne__(other)
This method allows you to compare two Charset instances for inequality. | python.library.email.charset#email.charset.Charset |
body_encode(string)
Body-encode the string string. The type of encoding (base64 or quoted-printable) will be based on the body_encoding attribute. | python.library.email.charset#email.charset.Charset.body_encode |
body_encoding
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. | python.library.email.charset#email.charset.Charset.body_encoding |
get_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. | python.library.email.charset#email.charset.Charset.get_body_encoding |
get_output_charset()
Return the output character set. This is the output_charset attribute if that is not None, otherwise it is input_charset. | python.library.email.charset#email.charset.Charset.get_output_charset |
header_encode(string)
Header-encode the string string. The type of encoding (base64 or quoted-printable) will be based on the header_encoding attribute. | python.library.email.charset#email.charset.Charset.header_encode |
header_encode_lines(string, maxlengths)
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. | python.library.email.charset#email.charset.Charset.header_encode_lines |
header_encoding
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. | python.library.email.charset#email.charset.Charset.header_encoding |
input_charset
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. | python.library.email.charset#email.charset.Charset.input_charset |
input_codec
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. | python.library.email.charset#email.charset.Charset.input_codec |
output_charset
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. | python.library.email.charset#email.charset.Charset.output_charset |
output_codec
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. | python.library.email.charset#email.charset.Charset.output_codec |
__eq__(other)
This method allows you to compare two Charset instances for equality. | python.library.email.charset#email.charset.Charset.__eq__ |
__ne__(other)
This method allows you to compare two Charset instances for inequality. | python.library.email.charset#email.charset.Charset.__ne__ |
__str__()
Returns input_charset as a string coerced to lower case. __repr__() is an alias for __str__(). | python.library.email.charset#email.charset.Charset.__str__ |
class email.contentmanager.ContentManager
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.
get_content(msg, *args, **kw)
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: the string representing the full MIME type (maintype/subtype) the string representing the maintype
the empty string If none of these keys produce a handler, raise a KeyError for the full MIME type.
set_content(msg, obj, *args, **kw)
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: the type itself (typ) the type’s fully qualified name (typ.__module__ + '.' +
typ.__qualname__). the type’s qualname (typ.__qualname__) the type’s name (typ.__name__). 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).
add_get_handler(key, handler)
Record the function handler as the handler for key. For the possible values of key, see get_content().
add_set_handler(typekey, handler)
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(). | python.library.email.contentmanager#email.contentmanager.ContentManager |
add_get_handler(key, handler)
Record the function handler as the handler for key. For the possible values of key, see get_content(). | python.library.email.contentmanager#email.contentmanager.ContentManager.add_get_handler |
add_set_handler(typekey, handler)
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(). | python.library.email.contentmanager#email.contentmanager.ContentManager.add_set_handler |
get_content(msg, *args, **kw)
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: the string representing the full MIME type (maintype/subtype) the string representing the maintype
the empty string If none of these keys produce a handler, raise a KeyError for the full MIME type. | python.library.email.contentmanager#email.contentmanager.ContentManager.get_content |
set_content(msg, obj, *args, **kw)
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: the type itself (typ) the type’s fully qualified name (typ.__module__ + '.' +
typ.__qualname__). the type’s qualname (typ.__qualname__) the type’s name (typ.__name__). 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). | python.library.email.contentmanager#email.contentmanager.ContentManager.set_content |
email.contentmanager.get_content(msg, errors='replace')
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. | python.library.email.contentmanager#email.contentmanager.get_content |
email.contentmanager.raw_data_manager
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.
email.contentmanager.get_content(msg, errors='replace')
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.
email.contentmanager.set_content(msg, <'str'>, subtype="plain", charset='utf-8', cte=None, disposition=None, filename=None, cid=None, params=None, headers=None)
email.contentmanager.set_content(msg, <'bytes'>, maintype, subtype, cte="base64", disposition=None, filename=None, cid=None, params=None, headers=None)
email.contentmanager.set_content(msg, <'EmailMessage'>, cte=None, disposition=None, filename=None, cid=None, params=None, headers=None)
Add headers and payload to msg: Add a Content-Type header with a maintype/subtype value. For str, set the MIME maintype to text, and set the subtype to subtype if it is specified, or plain if it is not. For bytes, use the specified maintype and subtype, or raise a TypeError if they are not specified. For EmailMessage objects, set the maintype to message, and set the subtype to subtype if it is specified or rfc822 if it is not. If subtype is partial, raise an error (bytes objects must be used to construct message/partial parts). 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. For str objects, if cte is not set use heuristics to determine the most compact encoding. For EmailMessage, per RFC 2046, raise an error if a cte of quoted-printable or base64 is requested for subtype rfc822, and for any cte other than 7bit for subtype external-body. For message/rfc822, use 8bit if cte is not specified. For all other values of subtype, use 7bit. 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. | python.library.email.contentmanager#email.contentmanager.raw_data_manager |
email.contentmanager.set_content(msg, <'str'>, subtype="plain", charset='utf-8', cte=None, disposition=None, filename=None, cid=None, params=None, headers=None)
email.contentmanager.set_content(msg, <'bytes'>, maintype, subtype, cte="base64", disposition=None, filename=None, cid=None, params=None, headers=None)
email.contentmanager.set_content(msg, <'EmailMessage'>, cte=None, disposition=None, filename=None, cid=None, params=None, headers=None)
Add headers and payload to msg: Add a Content-Type header with a maintype/subtype value. For str, set the MIME maintype to text, and set the subtype to subtype if it is specified, or plain if it is not. For bytes, use the specified maintype and subtype, or raise a TypeError if they are not specified. For EmailMessage objects, set the maintype to message, and set the subtype to subtype if it is specified or rfc822 if it is not. If subtype is partial, raise an error (bytes objects must be used to construct message/partial parts). 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. For str objects, if cte is not set use heuristics to determine the most compact encoding. For EmailMessage, per RFC 2046, raise an error if a cte of quoted-printable or base64 is requested for subtype rfc822, and for any cte other than 7bit for subtype external-body. For message/rfc822, use 8bit if cte is not specified. For all other values of subtype, use 7bit. 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. | python.library.email.contentmanager#email.contentmanager.set_content |
email.encoders.encode_7or8bit(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. | python.library.email.encoders#email.encoders.encode_7or8bit |
email.encoders.encode_base64(msg)
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. | python.library.email.encoders#email.encoders.encode_base64 |
email.encoders.encode_noop(msg)
This does nothing; it doesn’t even set the Content-Transfer-Encoding header. | python.library.email.encoders#email.encoders.encode_noop |
email.encoders.encode_quopri(msg)
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. | python.library.email.encoders#email.encoders.encode_quopri |
exception email.errors.BoundaryError
Deprecated and no longer used. | python.library.email.errors#email.errors.BoundaryError |
exception email.errors.HeaderParseError
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). | python.library.email.errors#email.errors.HeaderParseError |
exception email.errors.MessageError
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. | python.library.email.errors#email.errors.MessageError |
exception email.errors.MessageParseError
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. | python.library.email.errors#email.errors.MessageParseError |
exception email.errors.MultipartConversionError
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). | python.library.email.errors#email.errors.MultipartConversionError |
class email.generator.BytesGenerator(outfp, mangle_from_=None, maxheaderlen=None, *, policy=None)
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.
flatten(msg, unixfrom=False, linesep=None)
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.
clone(fp)
Return an independent clone of this BytesGenerator instance with the exact same option settings, and fp as the new outfp.
write(s)
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. | python.library.email.generator#email.generator.BytesGenerator |
clone(fp)
Return an independent clone of this BytesGenerator instance with the exact same option settings, and fp as the new outfp. | python.library.email.generator#email.generator.BytesGenerator.clone |
flatten(msg, unixfrom=False, linesep=None)
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. | python.library.email.generator#email.generator.BytesGenerator.flatten |
write(s)
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. | python.library.email.generator#email.generator.BytesGenerator.write |
class email.generator.DecodedGenerator(outfp, mangle_from_=None, maxheaderlen=None, fmt=None, *, policy=None)
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:
type – Full MIME type of the non-text part
maintype – Main MIME type of the non-text part
subtype – Sub-MIME type of the non-text part
filename – Filename of the non-text part
description – Description associated with the non-text part
encoding – Content transfer encoding of the non-text part 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. | python.library.email.generator#email.generator.DecodedGenerator |
class email.generator.Generator(outfp, mangle_from_=None, maxheaderlen=None, *, policy=None)
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.
flatten(msg, unixfrom=False, linesep=None)
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.
clone(fp)
Return an independent clone of this Generator instance with the exact same options, and fp as the new outfp.
write(s)
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. | python.library.email.generator#email.generator.Generator |
clone(fp)
Return an independent clone of this Generator instance with the exact same options, and fp as the new outfp. | python.library.email.generator#email.generator.Generator.clone |
flatten(msg, unixfrom=False, linesep=None)
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. | python.library.email.generator#email.generator.Generator.flatten |
write(s)
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. | python.library.email.generator#email.generator.Generator.write |
email.header.decode_header(header)
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: >>> from email.header import decode_header
>>> decode_header('=?iso-8859-1?q?p=F6stal?=')
[(b'p\xf6stal', 'iso-8859-1')] | python.library.email.header#email.header.decode_header |
class email.header.Header(s=None, charset=None, maxlinelen=None, header_name=None, continuation_ws=' ', errors='strict')
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(s, charset=None, errors='strict')
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(splitchars=';, \t', maxlinelen=None, linesep='\n')
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.
__str__()
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.
__eq__(other)
This method allows you to compare two Header instances for equality.
__ne__(other)
This method allows you to compare two Header instances for inequality. | python.library.email.header#email.header.Header |
append(s, charset=None, errors='strict')
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. | python.library.email.header#email.header.Header.append |
encode(splitchars=';, \t', maxlinelen=None, linesep='\n')
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. | python.library.email.header#email.header.Header.encode |
__eq__(other)
This method allows you to compare two Header instances for equality. | python.library.email.header#email.header.Header.__eq__ |
__ne__(other)
This method allows you to compare two Header instances for inequality. | python.library.email.header#email.header.Header.__ne__ |
__str__()
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. | python.library.email.header#email.header.Header.__str__ |
email.header.make_header(decoded_seq, maxlinelen=None, header_name=None, continuation_ws=' ')
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. | python.library.email.header#email.header.make_header |
class email.headerregistry.Address(display_name='', username='', domain='', addr_spec=None)
The class used to represent an email address. The general form of an address is: [display_name] <username@domain>
or: username@domain
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.
display_name
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.
username
The username portion of the address, with all quoting removed.
domain
The domain portion of the address.
addr_spec
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.
__str__()
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 <>. | python.library.email.headerregistry#email.headerregistry.Address |
addr_spec
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. | python.library.email.headerregistry#email.headerregistry.Address.addr_spec |
display_name
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. | python.library.email.headerregistry#email.headerregistry.Address.display_name |
domain
The domain portion of the address. | python.library.email.headerregistry#email.headerregistry.Address.domain |
username
The username portion of the address, with all quoting removed. | python.library.email.headerregistry#email.headerregistry.Address.username |
__str__()
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. | python.library.email.headerregistry#email.headerregistry.Address.__str__ |
class email.headerregistry.AddressHeader
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:
groups
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.
addresses
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. | python.library.email.headerregistry#email.headerregistry.AddressHeader |
addresses
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). | python.library.email.headerregistry#email.headerregistry.AddressHeader.addresses |
groups
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. | python.library.email.headerregistry#email.headerregistry.AddressHeader.groups |
class email.headerregistry.BaseHeader(name, value)
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:
name
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.
defects
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.
max_count
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:
fold(*, policy)
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: parse(string, kwds)
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: def init(self, /, *args, **kw):
self._myattr = kw.pop('myattr')
super().init(*args, **kw)
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. | python.library.email.headerregistry#email.headerregistry.BaseHeader |
defects
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. | python.library.email.headerregistry#email.headerregistry.BaseHeader.defects |
fold(*, policy)
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. | python.library.email.headerregistry#email.headerregistry.BaseHeader.fold |
max_count
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. | python.library.email.headerregistry#email.headerregistry.BaseHeader.max_count |
name
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. | python.library.email.headerregistry#email.headerregistry.BaseHeader.name |
class email.headerregistry.ContentDispositionHeader
A ParameterizedMIMEHeader class that handles the Content-Disposition header.
content_disposition
inline and attachment are the only valid values in common use. | python.library.email.headerregistry#email.headerregistry.ContentDispositionHeader |
content_disposition
inline and attachment are the only valid values in common use. | python.library.email.headerregistry#email.headerregistry.ContentDispositionHeader.content_disposition |
class email.headerregistry.ContentTransferEncoding
Handles the Content-Transfer-Encoding header.
cte
Valid values are 7bit, 8bit, base64, and quoted-printable. See RFC 2045 for more information. | python.library.email.headerregistry#email.headerregistry.ContentTransferEncoding |
cte
Valid values are 7bit, 8bit, base64, and quoted-printable. See RFC 2045 for more information. | python.library.email.headerregistry#email.headerregistry.ContentTransferEncoding.cte |
class email.headerregistry.ContentTypeHeader
A ParameterizedMIMEHeader class that handles the Content-Type header.
content_type
The content type string, in the form maintype/subtype.
maintype
subtype | python.library.email.headerregistry#email.headerregistry.ContentTypeHeader |
content_type
The content type string, in the form maintype/subtype. | python.library.email.headerregistry#email.headerregistry.ContentTypeHeader.content_type |
maintype | python.library.email.headerregistry#email.headerregistry.ContentTypeHeader.maintype |
subtype | python.library.email.headerregistry#email.headerregistry.ContentTypeHeader.subtype |
class email.headerregistry.DateHeader
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:
datetime
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: email.utils.format_datetime(self.datetime)
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: msg['Date'] = datetime(2011, 7, 15, 21)
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: msg['Date'] = utils.localtime()
This example sets the date header to the current time and date using the current timezone offset. | python.library.email.headerregistry#email.headerregistry.DateHeader |
datetime
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. | python.library.email.headerregistry#email.headerregistry.DateHeader.datetime |
class email.headerregistry.Group(display_name=None, addresses=None)
The class used to represent an address group. The general form of an address group is: display_name: [address-list];
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.
display_name
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.
addresses
A possibly empty tuple of Address objects representing the addresses in the group.
__str__()
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. | python.library.email.headerregistry#email.headerregistry.Group |
addresses
A possibly empty tuple of Address objects representing the addresses in the group. | python.library.email.headerregistry#email.headerregistry.Group.addresses |
display_name
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. | python.library.email.headerregistry#email.headerregistry.Group.display_name |
__str__()
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. | python.library.email.headerregistry#email.headerregistry.Group.__str__ |
class email.headerregistry.HeaderRegistry(base_class=BaseHeader, default_class=UnstructuredHeader, use_default_map=True)
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: subject
UniqueUnstructuredHeader date
UniqueDateHeader resent-date
DateHeader orig-date
UniqueDateHeader sender
UniqueSingleAddressHeader resent-sender
SingleAddressHeader to
UniqueAddressHeader resent-to
AddressHeader cc
UniqueAddressHeader resent-cc
AddressHeader bcc
UniqueAddressHeader resent-bcc
AddressHeader from
UniqueAddressHeader resent-from
AddressHeader reply-to
UniqueAddressHeader mime-version
MIMEVersionHeader content-type
ContentTypeHeader content-disposition
ContentDispositionHeader content-transfer-encoding
ContentTransferEncodingHeader message-id
MessageIDHeader HeaderRegistry has the following methods:
map_to_type(self, name, cls)
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.
__getitem__(name)
Construct and return a class to handle creating a name header.
__call__(name, value)
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. | python.library.email.headerregistry#email.headerregistry.HeaderRegistry |
map_to_type(self, name, cls)
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. | python.library.email.headerregistry#email.headerregistry.HeaderRegistry.map_to_type |
__call__(name, value)
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. | python.library.email.headerregistry#email.headerregistry.HeaderRegistry.__call__ |
__getitem__(name)
Construct and return a class to handle creating a name header. | python.library.email.headerregistry#email.headerregistry.HeaderRegistry.__getitem__ |
class email.headerregistry.MIMEVersionHeader
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:
version
The version number as a string, with any whitespace and/or comments removed.
major
The major version number as an integer
minor
The minor version number as an integer | python.library.email.headerregistry#email.headerregistry.MIMEVersionHeader |
major
The major version number as an integer | python.library.email.headerregistry#email.headerregistry.MIMEVersionHeader.major |
minor
The minor version number as an integer | python.library.email.headerregistry#email.headerregistry.MIMEVersionHeader.minor |
version
The version number as a string, with any whitespace and/or comments removed. | python.library.email.headerregistry#email.headerregistry.MIMEVersionHeader.version |
class email.headerregistry.ParameterizedMIMEHeader
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.
params
A dictionary mapping parameter names to parameter values. | python.library.email.headerregistry#email.headerregistry.ParameterizedMIMEHeader |
params
A dictionary mapping parameter names to parameter values. | python.library.email.headerregistry#email.headerregistry.ParameterizedMIMEHeader.params |
class email.headerregistry.SingleAddressHeader
A subclass of AddressHeader that adds one additional attribute:
address
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. | python.library.email.headerregistry#email.headerregistry.SingleAddressHeader |
address
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. | python.library.email.headerregistry#email.headerregistry.SingleAddressHeader.address |
class email.headerregistry.UnstructuredHeader
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. | python.library.email.headerregistry#email.headerregistry.UnstructuredHeader |
email.iterators.body_line_iterator(msg, decode=False)
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. | python.library.email.iterators#email.iterators.body_line_iterator |
email.iterators.typed_subpart_iterator(msg, maintype='text', subtype=None)
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/*. | python.library.email.iterators#email.iterators.typed_subpart_iterator |
email.iterators._structure(msg, fp=None, level=0, include_default=False)
Prints an indented representation of the content types of the message object structure. For example: >>> msg = email.message_from_file(somefile)
>>> _structure(msg)
multipart/mixed
text/plain
text/plain
multipart/digest
message/rfc822
text/plain
message/rfc822
text/plain
message/rfc822
text/plain
message/rfc822
text/plain
message/rfc822
text/plain
text/plain
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. | python.library.email.iterators#email.iterators._structure |
class email.message.EmailMessage(policy=default)
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.
as_string(unixfrom=False, maxheaderlen=None, policy=None)
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.
__str__()
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().
as_bytes(unixfrom=False, policy=None)
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.
__bytes__()
Equivalent to as_bytes(). Allows bytes(msg) to produce a bytes object containing the serialized message.
is_multipart()
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_unixfrom(unixfrom)
Set the message’s envelope header to unixfrom, which should be a string. (See mboxMessage for a brief description of this header.)
get_unixfrom()
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.
__len__()
Return the total number of headers, including duplicates.
__contains__(name)
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: if 'message-id' in myMessage:
print('Message-ID:', myMessage['message-id'])
__getitem__(name)
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.
__setitem__(name, val)
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.: del msg['subject']
msg['subject'] = 'Python roolz!'
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.
__delitem__(name)
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.
keys()
Return a list of all the message’s header field names.
values()
Return a list of all the message’s field values.
items()
Return a list of 2-tuples containing all the message’s field headers and values.
get(name, failobj=None)
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:
get_all(name, failobj=None)
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).
add_header(_name, _value, **_params)
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: msg.add_header('Content-Disposition', 'attachment', filename='bud.gif')
This will add a header that looks like Content-Disposition: attachment; filename="bud.gif"
An example of the extended interface with non-ASCII characters: msg.add_header('Content-Disposition', 'attachment',
filename=('iso-8859-1', '', 'Fußballer.ppt'))
replace_header(_name, _value)
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.
get_content_type()
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.)
get_content_maintype()
Return the message’s main content type. This is the maintype part of the string returned by get_content_type().
get_content_subtype()
Return the message’s sub-content type. This is the subtype part of the string returned by get_content_type().
get_default_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_default_type(ctype)
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_param(param, value, header='Content-Type', requote=True, charset=None, language='', replace=False)
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.
del_param(param, header='content-type', requote=True)
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.
get_filename(failobj=None)
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().
get_boundary(failobj=None)
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_boundary(boundary)
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.
get_content_charset(failobj=None)
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.
get_charsets(failobj=None)
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.
is_attachment()
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().
get_content_disposition()
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.
walk()
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: >>> for part in msg.walk():
... print(part.get_content_type())
multipart/report
text/plain
message/delivery-status
text/plain
text/plain
message/rfc822
text/plain
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: >>> from email.iterators import _structure
>>> for part in msg.walk():
... print(part.get_content_maintype() == 'multipart',
... part.is_multipart())
True True
False False
False True
False False
False False
False True
False False
>>> _structure(msg)
multipart/report
text/plain
message/delivery-status
text/plain
text/plain
message/rfc822
text/plain
Here the message parts are not multiparts, but they do contain subparts. is_multipart() returns True and walk descends into the subparts.
get_body(preferencelist=('related', 'html', 'plain'))
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.
iter_attachments()
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.
iter_parts()
Return an iterator over all of the immediate sub-parts of the message, which will be empty for a non-multipart. (See also walk().)
get_content(*args, content_manager=None, **kw)
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.
set_content(*args, content_manager=None, **kw)
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.
make_related(boundary=None)
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).
make_alternative(boundary=None)
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).
make_mixed(boundary=None)
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).
add_related(*args, content_manager=None, **kw)
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.
add_alternative(*args, content_manager=None, **kw)
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.
add_attachment(*args, content_manager=None, **kw)
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.
clear()
Remove the payload and all of the headers.
clear_content()
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:
preamble
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.
epilogue
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.
defects
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. | python.library.email.message#email.message.EmailMessage |
add_alternative(*args, content_manager=None, **kw)
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. | python.library.email.message#email.message.EmailMessage.add_alternative |
add_attachment(*args, content_manager=None, **kw)
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. | python.library.email.message#email.message.EmailMessage.add_attachment |
add_header(_name, _value, **_params)
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: msg.add_header('Content-Disposition', 'attachment', filename='bud.gif')
This will add a header that looks like Content-Disposition: attachment; filename="bud.gif"
An example of the extended interface with non-ASCII characters: msg.add_header('Content-Disposition', 'attachment',
filename=('iso-8859-1', '', 'Fußballer.ppt')) | python.library.email.message#email.message.EmailMessage.add_header |
add_related(*args, content_manager=None, **kw)
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. | python.library.email.message#email.message.EmailMessage.add_related |
as_bytes(unixfrom=False, policy=None)
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. | python.library.email.message#email.message.EmailMessage.as_bytes |
as_string(unixfrom=False, maxheaderlen=None, policy=None)
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. | python.library.email.message#email.message.EmailMessage.as_string |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.