email.headerregistry.rst 17.6 KB

:mod:`email.headerregistry`: Custom Header Objects

Note

The headerregistry module has been included in the standard library on a :term:`provisional basis <provisional package>`. Backwards incompatible changes (up to and including removal of the module) may occur if deemed necessary by the core developers.

Headers are represented by customized subclasses of :class:`str`. The particular class used to represent a given header is determined by the :attr:`~email.policy.EmailPolicy.header_factory` of the :mod:`~email.policy` in effect when the headers are created. This section documents the particular header_factory implemented by the email package for handling RFC 5322 compliant email messages, which not only provides customized header objects for various header types, but also provides an extension mechanism for applications to add their own custom header types.

When using any of the policy objects derived from :data:`~email.policy.EmailPolicy`, all headers are produced by :class:`.HeaderRegistry` and have :class:`.BaseHeader` as their last base class. Each header class has an additional base class that is determined by the type of the header. For example, many headers have the class :class:`.UnstructuredHeader` as their other base class. The specialized second class for a header is determined by the name of the header, using a lookup table stored in the :class:`.HeaderRegistry`. All of this is managed transparently for the typical application program, but interfaces are provided for modifying the default behavior for use by more complex applications.

The sections below first document the header base classes and their attributes, followed by the API for modifying the behavior of :class:`.HeaderRegistry`, and finally the support classes used to represent the data parsed from structured headers.

name and value are passed to BaseHeader from the :attr:`~email.policy.EmailPolicy.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:

BaseHeader also provides the following method, which is called by the email library code and should not in general be called by application programs:

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 :func:`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 transport 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.

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 :mailheader:`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 back in to the original 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.

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:

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 :class:`~datetime.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 :func:`~email.utils.localtime` function from the :mod:`~email.utils` module:

msg['Date'] = utils.localtime()

This example sets the date header to the current time and date using the current timezone offset.

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:

The decoded value of the header will have all encoded words decoded to unicode. :class:`~encodings.idna` encoded domain names are also decoded to unicode. The decoded value is set by :attr:`~str.join`ing the :class:`str` value of the elements of the groups attribute with ', '.

A list of :class:`.Address` and :class:`.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 groups attribute of the source header.

A subclass of :class:`.AddressHeader` that adds one additional attribute:

Many of the above classes also have a Unique variant (for example, UniqueUnstructuredHeader). The only difference is that in the Unique variant, :attr:`~.BaseHeader.max_count` is set to 1.

There is really only one valid value for the :mailheader:`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:

MOME headers all start with the prefix 'Content-'. Each specific header has a certain value, described under the class for that header. Some can also take a list of supplemental parameters, which have a common format. This class serves as a base for all the MIME headers that take parameters.

A :class:`ParameterizedMIMEHeader` class that handles the :mailheader:`Content-Type` header.

A :class:`ParameterizedMIMEHeader` class that handles the :mailheader:`Content-Disposition` header.

Handles the :mailheader:`Content-Transfer-Encoding` header.

The following classes are the classes used to represent data parsed from structured headers and can, in general, be used by an application program to construct structured values to assign to specific headers.

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.

To support SMTP (RFC 5321), Address handles one special case: if username and domain are both the empty string (or None), then the string value of the Address is <>.

The 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.