18.1.4. email: Creating email and MIME objects from scratch¶
Ordinarily, you get a message object structure by passing a file or some text to
a parser, which parses the text and returns the root message object. However
you can also build a complete message structure from scratch, or even individual
Message objects by hand. In fact, you can also take an
existing structure and add new Message objects, move them
around, etc. This makes a very convenient interface for slicing-and-dicing MIME
messages.
You can create a new object structure by creating Message
instances, adding attachments and all the appropriate headers manually. For MIME
messages though, the email package provides some convenient subclasses to
make things easier.
Here are the classes:
-
class
email.mime.base.MIMEBase(_maintype, _subtype, **_params)¶ Module:
email.mime.baseThis is the base class for all the MIME-specific subclasses of
Message. Ordinarily you won’t create instances specifically ofMIMEBase, although you could.MIMEBaseis provided primarily as a convenient base class for more specific MIME-aware subclasses._maintype is the Content-Type major type (e.g. text or image), and _subtype is the Content-Type minor type (e.g. plain or gif). _params is a parameter key/value dictionary and is passed directly to
Message.add_header().The
MIMEBaseclass always adds a Content-Type header (based on _maintype, _subtype, and _params), and a MIME-Version header (always set to1.0).
-
class
email.mime.nonmultipart.MIMENonMultipart¶ Module:
email.mime.nonmultipartA subclass of
MIMEBase, this is an intermediate base class for MIME messages that are not multipart. The primary purpose of this class is to prevent the use of theattach()method, which only makes sense for multipart messages. Ifattach()is called, aMultipartConversionErrorexception is raised.New in version 2.2.2:
New in version 2.2.2.
-
class
email.mime.multipart.MIMEMultipart([_subtype[, boundary[, _subparts[, _params]]]])¶ Module:
email.mime.multipartA subclass of
MIMEBase, this is an intermediate base class for MIME messages that are multipart. Optional _subtype defaults to mixed, but can be used to specify the subtype of the message. A Content-Type header of multipart/_subtype will be added to the message object. A MIME-Version header will also be added.Optional boundary is the multipart boundary string. When
None(the default), the boundary is calculated when needed (for example, when the message is serialized)._subparts is a sequence of initial subparts for the payload. It must be possible to convert this sequence to a list. You can always attach new subparts to the message by using the
Message.attach()method.Additional parameters for the Content-Type header are taken from the keyword arguments, or passed into the _params argument, which is a keyword dictionary.
New in version 2.2.2:
New in version 2.2.2.