| 1 |
:mod:`!email.message`: Representing an email message |
| 2 |
---------------------------------------------------- |
| 3 |
|
| 4 |
.. module:: email.message |
| 5 |
:synopsis: The base class representing email messages. |
| 6 |
.. moduleauthor:: R. David Murray <[email protected]> |
| 7 |
.. sectionauthor:: R. David Murray <[email protected]>, |
| 8 |
Barry A. Warsaw <[email protected]> |
| 9 |
|
| 10 |
**Source code:** :source:`Lib/email/message.py` |
| 11 |
|
| 12 |
-------------- |
| 13 |
|
| 14 |
.. versionadded:: 3.6 [1]_ |
| 15 |
|
| 16 |
The central class in the :mod:`email` package is the :class:`EmailMessage` |
| 17 |
class, imported from the :mod:`!email.message` module. It is the base class for |
| 18 |
the :mod:`email` object model. :class:`EmailMessage` provides the core |
| 19 |
functionality for setting and querying header fields, for accessing message |
| 20 |
bodies, and for creating or modifying structured messages. |
| 21 |
|
| 22 |
An email message consists of *headers* and a *payload* (which is also referred |
| 23 |
to as the *content*). Headers are :rfc:`5322` or :rfc:`6532` style field names |
| 24 |
and values, where the field name and value are separated by a colon. The colon |
| 25 |
is not part of either the field name or the field value. The payload may be a |
| 26 |
simple text message, or a binary object, or a structured sequence of |
| 27 |
sub-messages each with their own set of headers and their own payload. The |
| 28 |
latter type of payload is indicated by the message having a MIME type such as |
| 29 |
:mimetype:`multipart/\*` or :mimetype:`message/rfc822`. |
| 30 |
|
| 31 |
The conceptual model provided by an :class:`EmailMessage` object is that of an |
| 32 |
ordered dictionary of headers coupled with a *payload* that represents the |
| 33 |
:rfc:`5322` body of the message, which might be a list of sub-``EmailMessage`` |
| 34 |
objects. In addition to the normal dictionary methods for accessing the header |
| 35 |
names and values, there are methods for accessing specialized information from |
| 36 |
the headers (for example the MIME content type), for operating on the payload, |
| 37 |
for generating a serialized version of the message, and for recursively walking |
| 38 |
over the object tree. |
| 39 |
|
| 40 |
The :class:`EmailMessage` dictionary-like interface is indexed by the header |
| 41 |
names, which must be ASCII values. The values of the dictionary are strings |
| 42 |
with some extra methods. Headers are stored and returned in case-preserving |
| 43 |
form, but field names are matched case-insensitively. The keys are ordered, |
| 44 |
but unlike a real dict, there can be duplicates. Additional methods are |
| 45 |
provided for working with headers that have duplicate keys. |
| 46 |
|
| 47 |
The *payload* is either a string or bytes object, in the case of simple message |
| 48 |
objects, or a list of :class:`EmailMessage` objects, for MIME container |
| 49 |
documents such as :mimetype:`multipart/\*` and :mimetype:`message/rfc822` |
| 50 |
message objects. |
| 51 |
|
| 52 |
|
| 53 |
.. class:: EmailMessage(policy=default) |
| 54 |
|
| 55 |
If *policy* is specified use the rules it specifies to update and serialize |
| 56 |
the representation of the message. If *policy* is not set, use the |
| 57 |
:class:`~email.policy.default` policy, which follows the rules of the email |
| 58 |
RFCs except for line endings (instead of the RFC mandated ``\r\n``, it uses |
| 59 |
the Python standard ``\n`` line endings). For more information see the |
| 60 |
:mod:`~email.policy` documentation. [2]_ |
| 61 |
|
| 62 |
.. method:: as_string(unixfrom=False, maxheaderlen=None, policy=None) |
| 63 |
|
| 64 |
Return the entire message flattened as a string. When optional |
| 65 |
*unixfrom* is true, the envelope header is included in the returned |
| 66 |
string. *unixfrom* defaults to ``False``. For backward compatibility |
| 67 |
with the base :class:`~email.message.Message` class *maxheaderlen* is |
| 68 |
accepted, but defaults to ``None``, which means that by default the line |
| 69 |
length is controlled by the |
| 70 |
:attr:`~email.policy.Policy.max_line_length` of the policy. The |
| 71 |
*policy* argument may be used to override the default policy obtained |
| 72 |
from the message instance. This can be used to control some of the |
| 73 |
formatting produced by the method, since the specified *policy* will be |
| 74 |
passed to the :class:`~email.generator.Generator`. |
| 75 |
|
| 76 |
Flattening the message may trigger changes to the :class:`EmailMessage` |
| 77 |
if defaults need to be filled in to complete the transformation to a |
| 78 |
string (for example, MIME boundaries may be generated or modified). |
| 79 |
|
| 80 |
Note that this method is provided as a convenience and may not be the |
| 81 |
most useful way to serialize messages in your application, especially if |
| 82 |
you are dealing with multiple messages. See |
| 83 |
:class:`email.generator.Generator` for a more flexible API for |
| 84 |
serializing messages. Note also that this method is restricted to |
| 85 |
producing messages serialized as "7 bit clean" when |
| 86 |
:attr:`~email.policy.EmailPolicy.utf8` is ``False``, which is the default. |
| 87 |
|
| 88 |
.. versionchanged:: 3.6 the default behavior when *maxheaderlen* |
| 89 |
is not specified was changed from defaulting to 0 to defaulting |
| 90 |
to the value of *max_line_length* from the policy. |
| 91 |
|
| 92 |
|
| 93 |
.. method:: __str__() |
| 94 |
|
| 95 |
Equivalent to ``as_string(policy=self.policy.clone(utf8=True))``. Allows |
| 96 |
``str(msg)`` to produce a string containing the serialized message in a |
| 97 |
readable format. |
| 98 |
|
| 99 |
.. versionchanged:: 3.4 the method was changed to use ``utf8=True``, |
| 100 |
thus producing an :rfc:`6531`-like message representation, instead of |
| 101 |
being a direct alias for :meth:`as_string`. |
| 102 |
|
| 103 |
|
| 104 |
.. method:: as_bytes(unixfrom=False, policy=None) |
| 105 |
|
| 106 |
Return the entire message flattened as a bytes object. When optional |
| 107 |
*unixfrom* is true, the envelope header is included in the returned |
| 108 |
string. *unixfrom* defaults to ``False``. The *policy* argument may be |
| 109 |
used to override the default policy obtained from the message instance. |
| 110 |
This can be used to control some of the formatting produced by the |
| 111 |
method, since the specified *policy* will be passed to the |
| 112 |
:class:`~email.generator.BytesGenerator`. |
| 113 |
|
| 114 |
Flattening the message may trigger changes to the :class:`EmailMessage` |
| 115 |
if defaults need to be filled in to complete the transformation to a |
| 116 |
string (for example, MIME boundaries may be generated or modified). |
| 117 |
|
| 118 |
Note that this method is provided as a convenience and may not be the |
| 119 |
most useful way to serialize messages in your application, especially if |
| 120 |
you are dealing with multiple messages. See |
| 121 |
:class:`email.generator.BytesGenerator` for a more flexible API for |
| 122 |
serializing messages. |
| 123 |
|
| 124 |
|
| 125 |
.. method:: __bytes__() |
| 126 |
|
| 127 |
Equivalent to :meth:`.as_bytes`. Allows ``bytes(msg)`` to produce a |
| 128 |
bytes object containing the serialized message. |
| 129 |
|
| 130 |
|
| 131 |
.. method:: is_multipart() |
| 132 |
|
| 133 |
Return ``True`` if the message's payload is a list of |
| 134 |
sub-\ :class:`EmailMessage` objects, otherwise return ``False``. When |
| 135 |
:meth:`is_multipart` returns ``False``, the payload should be a string |
| 136 |
object (which might be a CTE encoded binary payload). Note that |
| 137 |
:meth:`is_multipart` returning ``True`` does not necessarily mean that |
| 138 |
"msg.get_content_maintype() == 'multipart'" will return the ``True``. |
| 139 |
For example, ``is_multipart`` will return ``True`` when the |
| 140 |
:class:`EmailMessage` is of type ``message/rfc822``. |
| 141 |
|
| 142 |
|
| 143 |
.. method:: set_unixfrom(unixfrom) |
| 144 |
|
| 145 |
Set the message's envelope header to *unixfrom*, which should be a |
| 146 |
string. (See :class:`~mailbox.mboxMessage` for a brief description of |
| 147 |
this header.) |
| 148 |
|
| 149 |
|
| 150 |
.. method:: get_unixfrom() |
| 151 |
|
| 152 |
Return the message's envelope header. Defaults to ``None`` if the |
| 153 |
envelope header was never set. |
| 154 |
|
| 155 |
|
| 156 |
The following methods implement the mapping-like interface for accessing the |
| 157 |
message's headers. Note that there are some semantic differences |
| 158 |
between these methods and a normal mapping (i.e. dictionary) interface. For |
| 159 |
example, in a dictionary there are no duplicate keys, but here there may be |
| 160 |
duplicate message headers. Also, in dictionaries there is no guaranteed |
| 161 |
order to the keys returned by :meth:`keys`, but in an :class:`EmailMessage` |
| 162 |
object, headers are always returned in the order they appeared in the |
| 163 |
original message, or in which they were added to the message later. Any |
| 164 |
header deleted and then re-added is always appended to the end of the |
| 165 |
header list. |
| 166 |
|
| 167 |
These semantic differences are intentional and are biased toward |
| 168 |
convenience in the most common use cases. |
| 169 |
|
| 170 |
Note that in all cases, any envelope header present in the message is not |
| 171 |
included in the mapping interface. |
| 172 |
|
| 173 |
|
| 174 |
.. method:: __len__() |
| 175 |
|
| 176 |
Return the total number of headers, including duplicates. |
| 177 |
|
| 178 |
|
| 179 |
.. method:: __contains__(name) |
| 180 |
|
| 181 |
Return ``True`` if the message object has a field named *name*. Matching is |
| 182 |
done without regard to case and *name* does not include the trailing |
| 183 |
colon. Used for the ``in`` operator. For example:: |
| 184 |
|
| 185 |
if 'message-id' in myMessage: |
| 186 |
print('Message-ID:', myMessage['message-id']) |
| 187 |
|
| 188 |
|
| 189 |
.. method:: __getitem__(name) |
| 190 |
|
| 191 |
Return the value of the named header field. *name* does not include the |
| 192 |
colon field separator. If the header is missing, ``None`` is returned; a |
| 193 |
:exc:`KeyError` is never raised. |
| 194 |
|
| 195 |
Note that if the named field appears more than once in the message's |
| 196 |
headers, exactly which of those field values will be returned is |
| 197 |
undefined. Use the :meth:`get_all` method to get the values of all the |
| 198 |
extant headers named *name*. |
| 199 |
|
| 200 |
Using the standard (non-``compat32``) policies, the returned value is an |
| 201 |
instance of a subclass of :class:`email.headerregistry.BaseHeader`. |
| 202 |
|
| 203 |
|
| 204 |
.. method:: __setitem__(name, val) |
| 205 |
|
| 206 |
Add a header to the message with field name *name* and value *val*. The |
| 207 |
field is appended to the end of the message's existing headers. |
| 208 |
|
| 209 |
Note that this does *not* overwrite or delete any existing header with the same |
| 210 |
name. If you want to ensure that the new header is the only one present in the |
| 211 |
message with field name *name*, delete the field first, e.g.:: |
| 212 |
|
| 213 |
del msg['subject'] |
| 214 |
msg['subject'] = 'Python roolz!' |
| 215 |
|
| 216 |
If the :mod:`policy <email.policy>` defines certain headers to be unique (as the standard |
| 217 |
policies do), this method may raise a :exc:`ValueError` when an attempt |
| 218 |
is made to assign a value to such a header when one already exists. This |
| 219 |
behavior is intentional for consistency's sake, but do not depend on it |
| 220 |
as we may choose to make such assignments do an automatic deletion of the |
| 221 |
existing header in the future. |
| 222 |
|
| 223 |
|
| 224 |
.. method:: __delitem__(name) |
| 225 |
|
| 226 |
Delete all occurrences of the field with name *name* from the message's |
| 227 |
headers. No exception is raised if the named field isn't present in the |
| 228 |
headers. |
| 229 |
|
| 230 |
|
| 231 |
.. method:: keys() |
| 232 |
|
| 233 |
Return a list of all the message's header field names. |
| 234 |
|
| 235 |
|
| 236 |
.. method:: values() |
| 237 |
|
| 238 |
Return a list of all the message's field values. |
| 239 |
|
| 240 |
|
| 241 |
.. method:: items() |
| 242 |
|
| 243 |
Return a list of 2-tuples containing all the message's field headers and |
| 244 |
values. |
| 245 |
|
| 246 |
|
| 247 |
.. method:: get(name, failobj=None) |
| 248 |
|
| 249 |
Return the value of the named header field. This is identical to |
| 250 |
:meth:`~object.__getitem__` except that optional *failobj* is returned if the |
| 251 |
named header is missing (*failobj* defaults to ``None``). |
| 252 |
|
| 253 |
|
| 254 |
Here are some additional useful header related methods: |
| 255 |
|
| 256 |
|
| 257 |
.. method:: get_all(name, failobj=None) |
| 258 |
|
| 259 |
Return a list of all the values for the field named *name*. If there are |
| 260 |
no such named headers in the message, *failobj* is returned (defaults to |
| 261 |
``None``). |
| 262 |
|
| 263 |
|
| 264 |
.. method:: add_header(_name, _value, **_params) |
| 265 |
|
| 266 |
Extended header setting. This method is similar to :meth:`__setitem__` |
| 267 |
except that additional header parameters can be provided as keyword |
| 268 |
arguments. *_name* is the header field to add and *_value* is the |
| 269 |
*primary* value for the header. |
| 270 |
|
| 271 |
For each item in the keyword argument dictionary *_params*, the key is |
| 272 |
taken as the parameter name, with underscores converted to dashes (since |
| 273 |
dashes are illegal in Python identifiers). Normally, the parameter will |
| 274 |
be added as ``key="value"`` unless the value is ``None``, in which case |
| 275 |
only the key will be added. |
| 276 |
|
| 277 |
If the value contains non-ASCII characters, the charset and language may |
| 278 |
be explicitly controlled by specifying the value as a three tuple in the |
| 279 |
format ``(CHARSET, LANGUAGE, VALUE)``, where ``CHARSET`` is a string |
| 280 |
naming the charset to be used to encode the value, ``LANGUAGE`` can |
| 281 |
usually be set to ``None`` or the empty string (see :rfc:`2231` for other |
| 282 |
possibilities), and ``VALUE`` is the string value containing non-ASCII |
| 283 |
code points. If a three tuple is not passed and the value contains |
| 284 |
non-ASCII characters, it is automatically encoded in :rfc:`2231` format |
| 285 |
using a ``CHARSET`` of ``utf-8`` and a ``LANGUAGE`` of ``None``. |
| 286 |
|
| 287 |
Here is an example:: |
| 288 |
|
| 289 |
msg.add_header('Content-Disposition', 'attachment', filename='bud.gif') |
| 290 |
|
| 291 |
This will add a header that looks like :: |
| 292 |
|
| 293 |
Content-Disposition: attachment; filename="bud.gif" |
| 294 |
|
| 295 |
An example of the extended interface with non-ASCII characters:: |
| 296 |
|
| 297 |
msg.add_header('Content-Disposition', 'attachment', |
| 298 |
filename=('iso-8859-1', '', 'Fußballer.ppt')) |
| 299 |
|
| 300 |
|
| 301 |
.. method:: replace_header(_name, _value) |
| 302 |
|
| 303 |
Replace a header. Replace the first header found in the message that |
| 304 |
matches *_name*, retaining header order and field name case of the |
| 305 |
original header. If no matching header is found, raise a |
| 306 |
:exc:`KeyError`. |
| 307 |
|
| 308 |
|
| 309 |
.. method:: get_content_type() |
| 310 |
|
| 311 |
Return the message's content type, coerced to lower case of the form |
| 312 |
:mimetype:`maintype/subtype`. If there is no :mailheader:`Content-Type` |
| 313 |
header in the message return the value returned by |
| 314 |
:meth:`get_default_type`. If the :mailheader:`Content-Type` header is |
| 315 |
invalid, return ``text/plain``. |
| 316 |
|
| 317 |
(According to :rfc:`2045`, messages always have a default type, |
| 318 |
:meth:`get_content_type` will always return a value. :rfc:`2045` defines |
| 319 |
a message's default type to be :mimetype:`text/plain` unless it appears |
| 320 |
inside a :mimetype:`multipart/digest` container, in which case it would |
| 321 |
be :mimetype:`message/rfc822`. If the :mailheader:`Content-Type` header |
| 322 |
has an invalid type specification, :rfc:`2045` mandates that the default |
| 323 |
type be :mimetype:`text/plain`.) |
| 324 |
|
| 325 |
|
| 326 |
.. method:: get_content_maintype() |
| 327 |
|
| 328 |
Return the message's main content type. This is the :mimetype:`maintype` |
| 329 |
part of the string returned by :meth:`get_content_type`. |
| 330 |
|
| 331 |
|
| 332 |
.. method:: get_content_subtype() |
| 333 |
|
| 334 |
Return the message's sub-content type. This is the :mimetype:`subtype` |
| 335 |
part of the string returned by :meth:`get_content_type`. |
| 336 |
|
| 337 |
|
| 338 |
.. method:: get_default_type() |
| 339 |
|
| 340 |
Return the default content type. Most messages have a default content |
| 341 |
type of :mimetype:`text/plain`, except for messages that are subparts of |
| 342 |
:mimetype:`multipart/digest` containers. Such subparts have a default |
| 343 |
content type of :mimetype:`message/rfc822`. |
| 344 |
|
| 345 |
|
| 346 |
.. method:: set_default_type(ctype) |
| 347 |
|
| 348 |
Set the default content type. *ctype* should either be |
| 349 |
:mimetype:`text/plain` or :mimetype:`message/rfc822`, although this is |
| 350 |
not enforced. The default content type is not stored in the |
| 351 |
:mailheader:`Content-Type` header, so it only affects the return value of |
| 352 |
the ``get_content_type`` methods when no :mailheader:`Content-Type` |
| 353 |
header is present in the message. |
| 354 |
|
| 355 |
|
| 356 |
.. method:: set_param(param, value, header='Content-Type', requote=True, \ |
| 357 |
charset=None, language='', replace=False) |
| 358 |
|
| 359 |
Set a parameter in the :mailheader:`Content-Type` header. If the |
| 360 |
parameter already exists in the header, replace its value with *value*. |
| 361 |
When *header* is ``Content-Type`` (the default) and the header does not |
| 362 |
yet exist in the message, add it, set its value to |
| 363 |
:mimetype:`text/plain`, and append the new parameter value. Optional |
| 364 |
*header* specifies an alternative header to :mailheader:`Content-Type`. |
| 365 |
|
| 366 |
If the value contains non-ASCII characters, the charset and language may |
| 367 |
be explicitly specified using the optional *charset* and *language* |
| 368 |
parameters. Optional *language* specifies the :rfc:`2231` language, |
| 369 |
defaulting to the empty string. Both *charset* and *language* should be |
| 370 |
strings. The default is to use the ``utf8`` *charset* and ``None`` for |
| 371 |
the *language*. |
| 372 |
|
| 373 |
If *replace* is ``False`` (the default) the header is moved to the |
| 374 |
end of the list of headers. If *replace* is ``True``, the header |
| 375 |
will be updated in place. |
| 376 |
|
| 377 |
Use of the *requote* parameter with :class:`EmailMessage` objects is |
| 378 |
deprecated. |
| 379 |
|
| 380 |
Note that existing parameter values of headers may be accessed through |
| 381 |
the :attr:`~email.headerregistry.ParameterizedMIMEHeader.params` attribute of the |
| 382 |
header value (for example, ``msg['Content-Type'].params['charset']``). |
| 383 |
|
| 384 |
.. versionchanged:: 3.4 ``replace`` keyword was added. |
| 385 |
|
| 386 |
|
| 387 |
.. method:: del_param(param, header='content-type', requote=True) |
| 388 |
|
| 389 |
Remove the given parameter completely from the :mailheader:`Content-Type` |
| 390 |
header. The header will be re-written in place without the parameter or |
| 391 |
its value. Optional *header* specifies an alternative to |
| 392 |
:mailheader:`Content-Type`. |
| 393 |
|
| 394 |
Use of the *requote* parameter with :class:`EmailMessage` objects is |
| 395 |
deprecated. |
| 396 |
|
| 397 |
|
| 398 |
.. method:: get_filename(failobj=None) |
| 399 |
|
| 400 |
Return the value of the ``filename`` parameter of the |
| 401 |
:mailheader:`Content-Disposition` header of the message. If the header |
| 402 |
does not have a ``filename`` parameter, this method falls back to looking |
| 403 |
for the ``name`` parameter on the :mailheader:`Content-Type` header. If |
| 404 |
neither is found, or the header is missing, then *failobj* is returned. |
| 405 |
The returned string will always be unquoted as per |
| 406 |
:func:`email.utils.unquote`. |
| 407 |
|
| 408 |
|
| 409 |
.. method:: get_boundary(failobj=None) |
| 410 |
|
| 411 |
Return the value of the ``boundary`` parameter of the |
| 412 |
:mailheader:`Content-Type` header of the message, or *failobj* if either |
| 413 |
the header is missing, or has no ``boundary`` parameter. The returned |
| 414 |
string will always be unquoted as per :func:`email.utils.unquote`. |
| 415 |
|
| 416 |
|
| 417 |
.. method:: set_boundary(boundary) |
| 418 |
|
| 419 |
Set the ``boundary`` parameter of the :mailheader:`Content-Type` header to |
| 420 |
*boundary*. :meth:`set_boundary` will always quote *boundary* if |
| 421 |
necessary. A :exc:`~email.errors.HeaderParseError` is raised if the |
| 422 |
message object has no :mailheader:`Content-Type` header. |
| 423 |
|
| 424 |
Note that using this method is subtly different from deleting the old |
| 425 |
:mailheader:`Content-Type` header and adding a new one with the new |
| 426 |
boundary via :meth:`add_header`, because :meth:`set_boundary` preserves |
| 427 |
the order of the :mailheader:`Content-Type` header in the list of |
| 428 |
headers. |
| 429 |
|
| 430 |
|
| 431 |
.. method:: get_content_charset(failobj=None) |
| 432 |
|
| 433 |
Return the ``charset`` parameter of the :mailheader:`Content-Type` header, |
| 434 |
coerced to lower case. If there is no :mailheader:`Content-Type` header, or if |
| 435 |
that header has no ``charset`` parameter, *failobj* is returned. |
| 436 |
|
| 437 |
|
| 438 |
.. method:: get_charsets(failobj=None) |
| 439 |
|
| 440 |
Return a list containing the character set names in the message. If the |
| 441 |
message is a :mimetype:`multipart`, then the list will contain one element |
| 442 |
for each subpart in the payload, otherwise, it will be a list of length 1. |
| 443 |
|
| 444 |
Each item in the list will be a string which is the value of the |
| 445 |
``charset`` parameter in the :mailheader:`Content-Type` header for the |
| 446 |
represented subpart. If the subpart has no :mailheader:`Content-Type` |
| 447 |
header, no ``charset`` parameter, or is not of the :mimetype:`text` main |
| 448 |
MIME type, then that item in the returned list will be *failobj*. |
| 449 |
|
| 450 |
|
| 451 |
.. method:: is_attachment |
| 452 |
|
| 453 |
Return ``True`` if there is a :mailheader:`Content-Disposition` header |
| 454 |
and its (case insensitive) value is ``attachment``, ``False`` otherwise. |
| 455 |
|
| 456 |
.. versionchanged:: 3.4.2 |
| 457 |
is_attachment is now a method instead of a property, for consistency |
| 458 |
with :meth:`~email.message.Message.is_multipart`. |
| 459 |
|
| 460 |
|
| 461 |
.. method:: get_content_disposition() |
| 462 |
|
| 463 |
Return the lowercased value (without parameters) of the message's |
| 464 |
:mailheader:`Content-Disposition` header if it has one, or ``None``. The |
| 465 |
possible values for this method are *inline*, *attachment* or ``None`` |
| 466 |
if the message follows :rfc:`2183`. |
| 467 |
|
| 468 |
.. versionadded:: 3.5 |
| 469 |
|
| 470 |
|
| 471 |
The following methods relate to interrogating and manipulating the content |
| 472 |
(payload) of the message. |
| 473 |
|
| 474 |
|
| 475 |
.. method:: walk() |
| 476 |
|
| 477 |
The :meth:`walk` method is an all-purpose generator which can be used to |
| 478 |
iterate over all the parts and subparts of a message object tree, in |
| 479 |
depth-first traversal order. You will typically use :meth:`walk` as the |
| 480 |
iterator in a ``for`` loop; each iteration returns the next subpart. |
| 481 |
|
| 482 |
Here's an example that prints the MIME type of every part of a multipart |
| 483 |
message structure: |
| 484 |
|
| 485 |
.. testsetup:: |
| 486 |
|
| 487 |
from email import message_from_binary_file |
| 488 |
with open('../Lib/test/test_email/data/msg_16.txt', 'rb') as f: |
| 489 |
msg = message_from_binary_file(f) |
| 490 |
|
| 491 |
.. doctest:: |
| 492 |
|
| 493 |
>>> for part in msg.walk(): |
| 494 |
... print(part.get_content_type()) |
| 495 |
multipart/report |
| 496 |
text/plain |
| 497 |
message/delivery-status |
| 498 |
text/plain |
| 499 |
text/plain |
| 500 |
message/rfc822 |
| 501 |
text/plain |
| 502 |
|
| 503 |
``walk`` iterates over the subparts of any part where |
| 504 |
:meth:`is_multipart` returns ``True``, even though |
| 505 |
``msg.get_content_maintype() == 'multipart'`` may return ``False``. We |
| 506 |
can see this in our example by making use of the ``_structure`` debug |
| 507 |
helper function: |
| 508 |
|
| 509 |
.. doctest:: |
| 510 |
|
| 511 |
>>> from email.iterators import _structure |
| 512 |
>>> for part in msg.walk(): |
| 513 |
... print(part.get_content_maintype() == 'multipart', |
| 514 |
... part.is_multipart()) |
| 515 |
True True |
| 516 |
False False |
| 517 |
False True |
| 518 |
False False |
| 519 |
False False |
| 520 |
False True |
| 521 |
False False |
| 522 |
>>> _structure(msg) |
| 523 |
multipart/report |
| 524 |
text/plain |
| 525 |
message/delivery-status |
| 526 |
text/plain |
| 527 |
text/plain |
| 528 |
message/rfc822 |
| 529 |
text/plain |
| 530 |
|
| 531 |
Here the ``message`` parts are not ``multiparts``, but they do contain |
| 532 |
subparts. ``is_multipart()`` returns ``True`` and ``walk`` descends |
| 533 |
into the subparts. |
| 534 |
|
| 535 |
|
| 536 |
.. method:: get_body(preferencelist=('related', 'html', 'plain')) |
| 537 |
|
| 538 |
Return the MIME part that is the best candidate to be the "body" of the |
| 539 |
message. |
| 540 |
|
| 541 |
*preferencelist* must be a sequence of strings from the set ``related``, |
| 542 |
``html``, and ``plain``, and indicates the order of preference for the |
| 543 |
content type of the part returned. |
| 544 |
|
| 545 |
Start looking for candidate matches with the object on which the |
| 546 |
``get_body`` method is called. |
| 547 |
|
| 548 |
If ``related`` is not included in *preferencelist*, consider the root |
| 549 |
part (or subpart of the root part) of any related encountered as a |
| 550 |
candidate if the (sub-)part matches a preference. |
| 551 |
|
| 552 |
When encountering a ``multipart/related``, check the ``start`` parameter |
| 553 |
and if a part with a matching :mailheader:`Content-ID` is found, consider |
| 554 |
only it when looking for candidate matches. Otherwise consider only the |
| 555 |
first (default root) part of the ``multipart/related``. |
| 556 |
|
| 557 |
If a part has a :mailheader:`Content-Disposition` header, only consider |
| 558 |
the part a candidate match if the value of the header is ``inline``. |
| 559 |
|
| 560 |
If none of the candidates matches any of the preferences in |
| 561 |
*preferencelist*, return ``None``. |
| 562 |
|
| 563 |
Notes: (1) For most applications the only *preferencelist* combinations |
| 564 |
that really make sense are ``('plain',)``, ``('html', 'plain')``, and the |
| 565 |
default ``('related', 'html', 'plain')``. (2) Because matching starts |
| 566 |
with the object on which ``get_body`` is called, calling ``get_body`` on |
| 567 |
a ``multipart/related`` will return the object itself unless |
| 568 |
*preferencelist* has a non-default value. (3) Messages (or message parts) |
| 569 |
that do not specify a :mailheader:`Content-Type` or whose |
| 570 |
:mailheader:`Content-Type` header is invalid will be treated as if they |
| 571 |
are of type ``text/plain``, which may occasionally cause ``get_body`` to |
| 572 |
return unexpected results. |
| 573 |
|
| 574 |
|
| 575 |
.. method:: iter_attachments() |
| 576 |
|
| 577 |
Return an iterator over all of the immediate sub-parts of the message |
| 578 |
that are not candidate "body" parts. That is, skip the first occurrence |
| 579 |
of each of ``text/plain``, ``text/html``, ``multipart/related``, or |
| 580 |
``multipart/alternative`` (unless they are explicitly marked as |
| 581 |
attachments via :mailheader:`Content-Disposition: attachment`), and |
| 582 |
return all remaining parts. When applied directly to a |
| 583 |
``multipart/related``, return an iterator over the all the related parts |
| 584 |
except the root part (ie: the part pointed to by the ``start`` parameter, |
| 585 |
or the first part if there is no ``start`` parameter or the ``start`` |
| 586 |
parameter doesn't match the :mailheader:`Content-ID` of any of the |
| 587 |
parts). When applied directly to a ``multipart/alternative`` or a |
| 588 |
non-``multipart``, return an empty iterator. |
| 589 |
|
| 590 |
|
| 591 |
.. method:: iter_parts() |
| 592 |
|
| 593 |
Return an iterator over all of the immediate sub-parts of the message, |
| 594 |
which will be empty for a non-``multipart``. (See also |
| 595 |
:meth:`~email.message.EmailMessage.walk`.) |
| 596 |
|
| 597 |
|
| 598 |
.. method:: get_content(*args, content_manager=None, **kw) |
| 599 |
|
| 600 |
Call the :meth:`~email.contentmanager.ContentManager.get_content` method |
| 601 |
of the *content_manager*, passing self as the message object, and passing |
| 602 |
along any other arguments or keywords as additional arguments. If |
| 603 |
*content_manager* is not specified, use the ``content_manager`` specified |
| 604 |
by the current :mod:`~email.policy`. |
| 605 |
|
| 606 |
|
| 607 |
.. method:: set_content(*args, content_manager=None, **kw) |
| 608 |
|
| 609 |
Call the :meth:`~email.contentmanager.ContentManager.set_content` method |
| 610 |
of the *content_manager*, passing self as the message object, and passing |
| 611 |
along any other arguments or keywords as additional arguments. If |
| 612 |
*content_manager* is not specified, use the ``content_manager`` specified |
| 613 |
by the current :mod:`~email.policy`. |
| 614 |
|
| 615 |
|
| 616 |
.. method:: make_related(boundary=None) |
| 617 |
|
| 618 |
Convert a non-``multipart`` message into a ``multipart/related`` message, |
| 619 |
moving any existing :mailheader:`Content-` headers and payload into a |
| 620 |
(new) first part of the ``multipart``. If *boundary* is specified, use |
| 621 |
it as the boundary string in the multipart, otherwise leave the boundary |
| 622 |
to be automatically created when it is needed (for example, when the |
| 623 |
message is serialized). |
| 624 |
|
| 625 |
|
| 626 |
.. method:: make_alternative(boundary=None) |
| 627 |
|
| 628 |
Convert a non-``multipart`` or a ``multipart/related`` into a |
| 629 |
``multipart/alternative``, moving any existing :mailheader:`Content-` |
| 630 |
headers and payload into a (new) first part of the ``multipart``. If |
| 631 |
*boundary* is specified, use it as the boundary string in the multipart, |
| 632 |
otherwise leave the boundary to be automatically created when it is |
| 633 |
needed (for example, when the message is serialized). |
| 634 |
|
| 635 |
|
| 636 |
.. method:: make_mixed(boundary=None) |
| 637 |
|
| 638 |
Convert a non-``multipart``, a ``multipart/related``, or a |
| 639 |
``multipart-alternative`` into a ``multipart/mixed``, moving any existing |
| 640 |
:mailheader:`Content-` headers and payload into a (new) first part of the |
| 641 |
``multipart``. If *boundary* is specified, use it as the boundary string |
| 642 |
in the multipart, otherwise leave the boundary to be automatically |
| 643 |
created when it is needed (for example, when the message is serialized). |
| 644 |
|
| 645 |
|
| 646 |
.. method:: add_related(*args, content_manager=None, **kw) |
| 647 |
|
| 648 |
If the message is a ``multipart/related``, create a new message |
| 649 |
object, pass all of the arguments to its :meth:`set_content` method, |
| 650 |
and :meth:`~email.message.Message.attach` it to the ``multipart``. If |
| 651 |
the message is a non-``multipart``, call :meth:`make_related` and then |
| 652 |
proceed as above. If the message is any other type of ``multipart``, |
| 653 |
raise a :exc:`TypeError`. If *content_manager* is not specified, use |
| 654 |
the ``content_manager`` specified by the current :mod:`~email.policy`. |
| 655 |
If the added part has no :mailheader:`Content-Disposition` header, |
| 656 |
add one with the value ``inline``. |
| 657 |
|
| 658 |
|
| 659 |
.. method:: add_alternative(*args, content_manager=None, **kw) |
| 660 |
|
| 661 |
If the message is a ``multipart/alternative``, create a new message |
| 662 |
object, pass all of the arguments to its :meth:`set_content` method, and |
| 663 |
:meth:`~email.message.Message.attach` it to the ``multipart``. If the |
| 664 |
message is a non-``multipart`` or ``multipart/related``, call |
| 665 |
:meth:`make_alternative` and then proceed as above. If the message is |
| 666 |
any other type of ``multipart``, raise a :exc:`TypeError`. If |
| 667 |
*content_manager* is not specified, use the ``content_manager`` specified |
| 668 |
by the current :mod:`~email.policy`. |
| 669 |
|
| 670 |
|
| 671 |
.. method:: add_attachment(*args, content_manager=None, **kw) |
| 672 |
|
| 673 |
If the message is a ``multipart/mixed``, create a new message object, |
| 674 |
pass all of the arguments to its :meth:`set_content` method, and |
| 675 |
:meth:`~email.message.Message.attach` it to the ``multipart``. If the |
| 676 |
message is a non-``multipart``, ``multipart/related``, or |
| 677 |
``multipart/alternative``, call :meth:`make_mixed` and then proceed as |
| 678 |
above. If *content_manager* is not specified, use the ``content_manager`` |
| 679 |
specified by the current :mod:`~email.policy`. If the added part |
| 680 |
has no :mailheader:`Content-Disposition` header, add one with the value |
| 681 |
``attachment``. This method can be used both for explicit attachments |
| 682 |
(:mailheader:`Content-Disposition: attachment`) and ``inline`` attachments |
| 683 |
(:mailheader:`Content-Disposition: inline`), by passing appropriate |
| 684 |
options to the ``content_manager``. |
| 685 |
|
| 686 |
|
| 687 |
.. method:: clear() |
| 688 |
|
| 689 |
Remove the payload and all of the headers. |
| 690 |
|
| 691 |
|
| 692 |
.. method:: clear_content() |
| 693 |
|
| 694 |
Remove the payload and all of the :mailheader:`!Content-` headers, leaving |
| 695 |
all other headers intact and in their original order. |
| 696 |
|
| 697 |
|
| 698 |
:class:`EmailMessage` objects have the following instance attributes: |
| 699 |
|
| 700 |
|
| 701 |
.. attribute:: preamble |
| 702 |
|
| 703 |
The format of a MIME document allows for some text between the blank line |
| 704 |
following the headers, and the first multipart boundary string. Normally, |
| 705 |
this text is never visible in a MIME-aware mail reader because it falls |
| 706 |
outside the standard MIME armor. However, when viewing the raw text of |
| 707 |
the message, or when viewing the message in a non-MIME aware reader, this |
| 708 |
text can become visible. |
| 709 |
|
| 710 |
The *preamble* attribute contains this leading extra-armor text for MIME |
| 711 |
documents. When the :class:`~email.parser.Parser` discovers some text |
| 712 |
after the headers but before the first boundary string, it assigns this |
| 713 |
text to the message's *preamble* attribute. When the |
| 714 |
:class:`~email.generator.Generator` is writing out the plain text |
| 715 |
representation of a MIME message, and it finds the |
| 716 |
message has a *preamble* attribute, it will write this text in the area |
| 717 |
between the headers and the first boundary. See :mod:`email.parser` and |
| 718 |
:mod:`email.generator` for details. |
| 719 |
|
| 720 |
Note that if the message object has no preamble, the *preamble* attribute |
| 721 |
will be ``None``. |
| 722 |
|
| 723 |
|
| 724 |
.. attribute:: epilogue |
| 725 |
|
| 726 |
The *epilogue* attribute acts the same way as the *preamble* attribute, |
| 727 |
except that it contains text that appears between the last boundary and |
| 728 |
the end of the message. As with the :attr:`~EmailMessage.preamble`, |
| 729 |
if there is no epilog text this attribute will be ``None``. |
| 730 |
|
| 731 |
|
| 732 |
.. attribute:: defects |
| 733 |
|
| 734 |
The *defects* attribute contains a list of all the problems found when |
| 735 |
parsing this message. See :mod:`email.errors` for a detailed description |
| 736 |
of the possible parsing defects. |
| 737 |
|
| 738 |
|
| 739 |
.. class:: MIMEPart(policy=default) |
| 740 |
|
| 741 |
This class represents a subpart of a MIME message. It is identical to |
| 742 |
:class:`EmailMessage`, except that no :mailheader:`MIME-Version` headers are |
| 743 |
added when :meth:`~EmailMessage.set_content` is called, since sub-parts do |
| 744 |
not need their own :mailheader:`MIME-Version` headers. |
| 745 |
|
| 746 |
|
| 747 |
.. rubric:: Footnotes |
| 748 |
|
| 749 |
.. [1] Originally added in 3.4 as a :term:`provisional module <provisional |
| 750 |
package>`. Docs for legacy message class moved to |
| 751 |
:ref:`compat32_message`. |
| 752 |
|
| 753 |
.. [2] The :class:`EmailMessage` class requires a policy that provides a |
| 754 |
``content_manager`` attribute for content management methods like |
| 755 |
``set_content()`` and ``get_content()`` to work. The legacy |
| 756 |
:const:`~email.policy.compat32` policy does not support these methods |
| 757 |
and should not be used with :class:`EmailMessage`. |