In other words, the Message object is used both for accessing existing messages and for
creating new ones from scratch. In both cases, email can automatically handle details
like content encodings (e.g., attached binary images can be treated as text with Base64
encoding and decoding), content types, and more.
Message Objects
Since the email module’s Message object is at the heart of its API, you need a cursory
understanding of its form to get started. In short, it is designed to reflect the structure
of a formatted email message. Each Message consists of three main pieces of
information:
Type
A content type (plain text, HTML text, JPEG image, and so on), encoded as a
MIME main type and a subtype. For instance, “text/html” means the main type is
text and the subtype is HTML (a web page); “image/jpeg” means a JPEG photo.
A “multipart/mixed” type means there are nested parts within the message.
Headers
A dictionary-like mapping interface, with one key per mail header (From, To, and
so on). This interface supports almost all of the usual dictionary operations, and
headers may be fetched or set by normal key indexing.
Content
A “payload,” which represents the mail’s content. This can be either a string
(bytes or str) for simple messages, or a list of additional Message objects for
multipart container messages with attached or alternative parts. For some oddball
types, the payload may be a Python None object.
The MIME type of a Message is key to understanding its content. For example, mails
with attached images may have a main top-level Message (type multipart/mixed), with
three more Message objects in its payload—one for its main text (type text/plain),
followed by two of type image for the photos (type image/jpeg). The photo parts may
be encoded for transmission as text with Base64 or another scheme; the encoding type,
as well as the original image filename, are specified in the part’s headers.
Similarly, mails that include both simple text and an HTML alternative will have two
nested Message objects in their payload, of type plain text (text/plain) and HTML text
(text/html), along with a main root Message of type multipart/alternative. Your mail
client decides which part to display, often based on your preferences.
Simpler messages may have just a root Message of type text/plain or text/html, repre-
senting the entire message body. The payload for such mails is a simple string. They
may also have no explicitly given type at all, which generally defaults to text/plain.
Some single-part messages are text/html, with no text/plain alternative—they require
a web browser or other HTML viewer (or a very keen-eyed user).
922 | Chapter 13: Client-Side Scripting