:mod:`email.message`: Representing an email message
The central class in the :mod:`email` package is the :class:`Message` class, imported from the :mod:`email.message` module. It is the base class for the :mod:`email` object model. :class:`Message` provides the core functionality for setting and querying header fields, and for accessing message bodies.
Conceptually, a :class:`Message` object consists of headers and payloads. Headers are RFC 2822 style field names and values where the field name and value are separated by a colon. The colon is not part of either the field name or the field value.
Headers are stored and returned in case-preserving form but are matched
case-insensitively. There may also be a single envelope header, also known as
the Unix-From header or the From_
header. The payload is either a string
in the case of simple message objects or a list of :class:`Message` objects for
MIME container documents (e.g. :mimetype:`multipart/\*` and
:mimetype:`message/rfc822`).
:class:`Message` objects provide a mapping style interface for accessing the message headers, and an explicit interface for accessing both the headers and the payload. It provides convenience methods for generating a flat text representation of the message object tree, for accessing commonly used header parameters, and for recursively walking over the object tree.
Here are the methods of the :class:`Message` class:
The constructor takes no arguments.
The following methods implement a mapping-like interface for accessing the message's RFC 2822 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 :meth:`keys`, but in a :class:`Message` object, headers are always returned in the order they appeared in the original message, or were added to the message later. Any header deleted and then re-added are always appended to the end of the header list.
These semantic differences are intentional and are biased toward maximal convenience.
Note that in all cases, any envelope header present in the message is not included in the mapping interface.
In a model generated from bytes, any header values that (in contravention of the RFCs) contain non-ASCII bytes will, when retrieved through this interface, be represented as :class:`~email.header.Header` objects with a charset of unknown-8bit.
Here are some additional useful methods:
:class:`Message` objects can also optionally contain two instance attributes, which can be used when generating the plain text of a MIME message.