| 1 |
.. _compat32_message: |
| 2 |
|
| 3 |
:mod:`email.message.Message`: Representing an email message using the :data:`~email.policy.compat32` API |
| 4 |
-------------------------------------------------------------------------------------------------------- |
| 5 |
|
| 6 |
.. module:: email.message |
| 7 |
:synopsis: The base class representing email messages in a fashion |
| 8 |
backward compatible with Python 3.2 |
| 9 |
:noindex: |
| 10 |
:no-index: |
| 11 |
|
| 12 |
|
| 13 |
The :class:`Message` class is very similar to the |
| 14 |
:class:`~email.message.EmailMessage` class, without the methods added by that |
| 15 |
class, and with the default behavior of certain other methods being slightly |
| 16 |
different. We also document here some methods that, while supported by the |
| 17 |
:class:`~email.message.EmailMessage` class, are not recommended unless you are |
| 18 |
dealing with legacy code. |
| 19 |
|
| 20 |
The philosophy and structure of the two classes is otherwise the same. |
| 21 |
|
| 22 |
This document describes the behavior under the default (for :class:`Message`) |
| 23 |
policy :attr:`~email.policy.Compat32`. If you are going to use another policy, |
| 24 |
you should be using the :class:`~email.message.EmailMessage` class instead. |
| 25 |
|
| 26 |
An email message consists of *headers* and a *payload*. Headers must be |
| 27 |
:rfc:`5322` style names and values, where the field name and value are |
| 28 |
separated by a colon. The colon is not part of either the field name or the |
| 29 |
field value. The payload may be a simple text message, or a binary object, or |
| 30 |
a structured sequence of sub-messages each with their own set of headers and |
| 31 |
their own payload. The latter type of payload is indicated by the message |
| 32 |
having a MIME type such as :mimetype:`multipart/\*` or |
| 33 |
:mimetype:`message/rfc822`. |
| 34 |
|
| 35 |
The conceptual model provided by a :class:`Message` object is that of an |
| 36 |
ordered dictionary of headers with additional methods for accessing both |
| 37 |
specialized information from the headers, for accessing the payload, for |
| 38 |
generating a serialized version of the message, and for recursively walking |
| 39 |
over the object tree. Note that duplicate headers are supported but special |
| 40 |
methods must be used to access them. |
| 41 |
|
| 42 |
The :class:`Message` pseudo-dictionary is indexed by the header names, which |
| 43 |
must be ASCII values. The values of the dictionary are strings that are |
| 44 |
supposed to contain only ASCII characters; there is some special handling for |
| 45 |
non-ASCII input, but it doesn't always produce the correct results. Headers |
| 46 |
are stored and returned in case-preserving form, but field names are matched |
| 47 |
case-insensitively. There may also be a single envelope header, also known as |
| 48 |
the *Unix-From* header or the ``From_`` header. The *payload* is either a |
| 49 |
string or bytes, in the case of simple message objects, or a list of |
| 50 |
:class:`Message` objects, for MIME container documents (e.g. |
| 51 |
:mimetype:`multipart/\*` and :mimetype:`message/rfc822`). |
| 52 |
|
| 53 |
Here are the methods of the :class:`Message` class: |
| 54 |
|
| 55 |
|
| 56 |
.. class:: Message(policy=compat32) |
| 57 |
|
| 58 |
If *policy* is specified (it must be an instance of a :mod:`~email.policy` |
| 59 |
class) use the rules it specifies to update and serialize the representation |
| 60 |
of the message. If *policy* is not set, use the :class:`compat32 |
| 61 |
<email.policy.Compat32>` policy, which maintains backward compatibility with |
| 62 |
the Python 3.2 version of the email package. For more information see the |
| 63 |
:mod:`~email.policy` documentation. |
| 64 |
|
| 65 |
.. versionchanged:: 3.3 The *policy* keyword argument was added. |
| 66 |
|
| 67 |
|
| 68 |
.. method:: as_string(unixfrom=False, maxheaderlen=0, policy=None) |
| 69 |
|
| 70 |
Return the entire message flattened as a string. When optional *unixfrom* |
| 71 |
is true, the envelope header is included in the returned string. |
| 72 |
*unixfrom* defaults to ``False``. For backward compatibility reasons, |
| 73 |
*maxheaderlen* defaults to ``0``, so if you want a different value you |
| 74 |
must override it explicitly (the value specified for *max_line_length* in |
| 75 |
the policy will be ignored by this method). The *policy* argument may be |
| 76 |
used to override the default policy obtained from the message instance. |
| 77 |
This can be used to control some of the formatting produced by the |
| 78 |
method, since the specified *policy* will be passed to the ``Generator``. |
| 79 |
|
| 80 |
Flattening the message may trigger changes to the :class:`Message` if |
| 81 |
defaults need to be filled in to complete the transformation to a string |
| 82 |
(for example, MIME boundaries may be generated or modified). |
| 83 |
|
| 84 |
Note that this method is provided as a convenience and may not always |
| 85 |
format the message the way you want. For example, by default it does |
| 86 |
not do the mangling of lines that begin with ``From`` that is |
| 87 |
required by the Unix mbox format. For more flexibility, instantiate a |
| 88 |
:class:`~email.generator.Generator` instance and use its |
| 89 |
:meth:`~email.generator.Generator.flatten` method directly. For example:: |
| 90 |
|
| 91 |
from io import StringIO |
| 92 |
from email.generator import Generator |
| 93 |
fp = StringIO() |
| 94 |
g = Generator(fp, mangle_from_=True, maxheaderlen=60) |
| 95 |
g.flatten(msg) |
| 96 |
text = fp.getvalue() |
| 97 |
|
| 98 |
If the message object contains binary data that is not encoded according |
| 99 |
to RFC standards, the non-compliant data will be replaced by unicode |
| 100 |
"unknown character" code points. (See also :meth:`.as_bytes` and |
| 101 |
:class:`~email.generator.BytesGenerator`.) |
| 102 |
|
| 103 |
.. versionchanged:: 3.4 the *policy* keyword argument was added. |
| 104 |
|
| 105 |
|
| 106 |
.. method:: __str__() |
| 107 |
|
| 108 |
Equivalent to :meth:`.as_string`. Allows ``str(msg)`` to produce a |
| 109 |
string containing the formatted message. |
| 110 |
|
| 111 |
|
| 112 |
.. method:: as_bytes(unixfrom=False, policy=None) |
| 113 |
|
| 114 |
Return the entire message flattened as a bytes object. When optional |
| 115 |
*unixfrom* is true, the envelope header is included in the returned |
| 116 |
string. *unixfrom* defaults to ``False``. The *policy* argument may be |
| 117 |
used to override the default policy obtained from the message instance. |
| 118 |
This can be used to control some of the formatting produced by the |
| 119 |
method, since the specified *policy* will be passed to the |
| 120 |
``BytesGenerator``. |
| 121 |
|
| 122 |
Flattening the message may trigger changes to the :class:`Message` if |
| 123 |
defaults need to be filled in to complete the transformation to a string |
| 124 |
(for example, MIME boundaries may be generated or modified). |
| 125 |
|
| 126 |
Note that this method is provided as a convenience and may not always |
| 127 |
format the message the way you want. For example, by default it does |
| 128 |
not do the mangling of lines that begin with ``From`` that is |
| 129 |
required by the Unix mbox format. For more flexibility, instantiate a |
| 130 |
:class:`~email.generator.BytesGenerator` instance and use its |
| 131 |
:meth:`~email.generator.BytesGenerator.flatten` method directly. |
| 132 |
For example:: |
| 133 |
|
| 134 |
from io import BytesIO |
| 135 |
from email.generator import BytesGenerator |
| 136 |
fp = BytesIO() |
| 137 |
g = BytesGenerator(fp, mangle_from_=True, maxheaderlen=60) |
| 138 |
g.flatten(msg) |
| 139 |
text = fp.getvalue() |
| 140 |
|
| 141 |
.. versionadded:: 3.4 |
| 142 |
|
| 143 |
|
| 144 |
.. method:: __bytes__() |
| 145 |
|
| 146 |
Equivalent to :meth:`.as_bytes`. Allows ``bytes(msg)`` to produce a |
| 147 |
bytes object containing the formatted message. |
| 148 |
|
| 149 |
.. versionadded:: 3.4 |
| 150 |
|
| 151 |
|
| 152 |
.. method:: is_multipart() |
| 153 |
|
| 154 |
Return ``True`` if the message's payload is a list of |
| 155 |
sub-\ :class:`Message` objects, otherwise return ``False``. When |
| 156 |
:meth:`is_multipart` returns ``False``, the payload should be a string |
| 157 |
object (which might be a CTE encoded binary payload). (Note that |
| 158 |
:meth:`is_multipart` returning ``True`` does not necessarily mean that |
| 159 |
"msg.get_content_maintype() == 'multipart'" will return the ``True``. |
| 160 |
For example, ``is_multipart`` will return ``True`` when the |
| 161 |
:class:`Message` is of type ``message/rfc822``.) |
| 162 |
|
| 163 |
|
| 164 |
.. method:: set_unixfrom(unixfrom) |
| 165 |
|
| 166 |
Set the message's envelope header to *unixfrom*, which should be a string. |
| 167 |
|
| 168 |
|
| 169 |
.. method:: get_unixfrom() |
| 170 |
|
| 171 |
Return the message's envelope header. Defaults to ``None`` if the |
| 172 |
envelope header was never set. |
| 173 |
|
| 174 |
|
| 175 |
.. method:: attach(payload) |
| 176 |
|
| 177 |
Add the given *payload* to the current payload, which must be ``None`` or |
| 178 |
a list of :class:`Message` objects before the call. After the call, the |
| 179 |
payload will always be a list of :class:`Message` objects. If you want to |
| 180 |
set the payload to a scalar object (e.g. a string), use |
| 181 |
:meth:`set_payload` instead. |
| 182 |
|
| 183 |
This is a legacy method. On the |
| 184 |
:class:`~email.message.EmailMessage` class its functionality is |
| 185 |
replaced by :meth:`~email.message.EmailMessage.set_content` and the |
| 186 |
related ``make`` and ``add`` methods. |
| 187 |
|
| 188 |
|
| 189 |
.. method:: get_payload(i=None, decode=False) |
| 190 |
|
| 191 |
Return the current payload, which will be a list of |
| 192 |
:class:`Message` objects when :meth:`is_multipart` is ``True``, or a |
| 193 |
string when :meth:`is_multipart` is ``False``. If the payload is a list |
| 194 |
and you mutate the list object, you modify the message's payload in place. |
| 195 |
|
| 196 |
With optional argument *i*, :meth:`get_payload` will return the *i*-th |
| 197 |
element of the payload, counting from zero, if :meth:`is_multipart` is |
| 198 |
``True``. An :exc:`IndexError` will be raised if *i* is less than 0 or |
| 199 |
greater than or equal to the number of items in the payload. If the |
| 200 |
payload is a string (i.e. :meth:`is_multipart` is ``False``) and *i* is |
| 201 |
given, a :exc:`TypeError` is raised. |
| 202 |
|
| 203 |
Optional *decode* is a flag indicating whether the payload should be |
| 204 |
decoded or not, according to the :mailheader:`Content-Transfer-Encoding` |
| 205 |
header. When ``True`` and the message is not a multipart, the payload will |
| 206 |
be decoded if this header's value is ``quoted-printable`` or ``base64``. |
| 207 |
If some other encoding is used, or :mailheader:`Content-Transfer-Encoding` |
| 208 |
header is missing, the payload is |
| 209 |
returned as-is (undecoded). In all cases the returned value is binary |
| 210 |
data. If the message is a multipart and the *decode* flag is ``True``, |
| 211 |
then ``None`` is returned. If the payload is base64 and it was not |
| 212 |
perfectly formed (missing padding, characters outside the base64 |
| 213 |
alphabet), then an appropriate defect will be added to the message's |
| 214 |
defect property (:class:`~email.errors.InvalidBase64PaddingDefect` or |
| 215 |
:class:`~email.errors.InvalidBase64CharactersDefect`, respectively). |
| 216 |
|
| 217 |
When *decode* is ``False`` (the default) the body is returned as a string |
| 218 |
without decoding the :mailheader:`Content-Transfer-Encoding`. However, |
| 219 |
for a :mailheader:`Content-Transfer-Encoding` of 8bit, an attempt is made |
| 220 |
to decode the original bytes using the ``charset`` specified by the |
| 221 |
:mailheader:`Content-Type` header, using the ``replace`` error handler. |
| 222 |
If no ``charset`` is specified, or if the ``charset`` given is not |
| 223 |
recognized by the email package, the body is decoded using the default |
| 224 |
ASCII charset. |
| 225 |
|
| 226 |
This is a legacy method. On the |
| 227 |
:class:`~email.message.EmailMessage` class its functionality is |
| 228 |
replaced by :meth:`~email.message.EmailMessage.get_content` and |
| 229 |
:meth:`~email.message.EmailMessage.iter_parts`. |
| 230 |
|
| 231 |
|
| 232 |
.. method:: set_payload(payload, charset=None) |
| 233 |
|
| 234 |
Set the entire message object's payload to *payload*. It is the client's |
| 235 |
responsibility to ensure the payload invariants. Optional *charset* sets |
| 236 |
the message's default character set; see :meth:`set_charset` for details. |
| 237 |
|
| 238 |
This is a legacy method. On the |
| 239 |
:class:`~email.message.EmailMessage` class its functionality is |
| 240 |
replaced by :meth:`~email.message.EmailMessage.set_content`. |
| 241 |
|
| 242 |
|
| 243 |
.. method:: set_charset(charset) |
| 244 |
|
| 245 |
Set the character set of the payload to *charset*, which can either be a |
| 246 |
:class:`~email.charset.Charset` instance (see :mod:`email.charset`), a |
| 247 |
string naming a character set, or ``None``. If it is a string, it will |
| 248 |
be converted to a :class:`~email.charset.Charset` instance. If *charset* |
| 249 |
is ``None``, the ``charset`` parameter will be removed from the |
| 250 |
:mailheader:`Content-Type` header (the message will not be otherwise |
| 251 |
modified). Anything else will generate a :exc:`TypeError`. |
| 252 |
|
| 253 |
If there is no existing :mailheader:`MIME-Version` header one will be |
| 254 |
added. If there is no existing :mailheader:`Content-Type` header, one |
| 255 |
will be added with a value of :mimetype:`text/plain`. Whether the |
| 256 |
:mailheader:`Content-Type` header already exists or not, its ``charset`` |
| 257 |
parameter will be set to *charset.output_charset*. If |
| 258 |
*charset.input_charset* and *charset.output_charset* differ, the payload |
| 259 |
will be re-encoded to the *output_charset*. If there is no existing |
| 260 |
:mailheader:`Content-Transfer-Encoding` header, then the payload will be |
| 261 |
transfer-encoded, if needed, using the specified |
| 262 |
:class:`~email.charset.Charset`, and a header with the appropriate value |
| 263 |
will be added. If a :mailheader:`Content-Transfer-Encoding` header |
| 264 |
already exists, the payload is assumed to already be correctly encoded |
| 265 |
using that :mailheader:`Content-Transfer-Encoding` and is not modified. |
| 266 |
|
| 267 |
This is a legacy method. On the |
| 268 |
:class:`~email.message.EmailMessage` class its functionality is |
| 269 |
replaced by the *charset* parameter of the |
| 270 |
:meth:`email.message.EmailMessage.set_content` method. |
| 271 |
|
| 272 |
|
| 273 |
.. method:: get_charset() |
| 274 |
|
| 275 |
Return the :class:`~email.charset.Charset` instance associated with the |
| 276 |
message's payload. |
| 277 |
|
| 278 |
This is a legacy method. On the |
| 279 |
:class:`~email.message.EmailMessage` class it always returns |
| 280 |
``None``. |
| 281 |
|
| 282 |
|
| 283 |
The following methods implement a mapping-like interface for accessing the |
| 284 |
message's :rfc:`2822` headers. Note that there are some semantic differences |
| 285 |
between these methods and a normal mapping (i.e. dictionary) interface. For |
| 286 |
example, in a dictionary there are no duplicate keys, but here there may be |
| 287 |
duplicate message headers. Also, in dictionaries there is no guaranteed |
| 288 |
order to the keys returned by :meth:`keys`, but in a :class:`Message` object, |
| 289 |
headers are always returned in the order they appeared in the original |
| 290 |
message, or were added to the message later. Any header deleted and then |
| 291 |
re-added are always appended to the end of the header list. |
| 292 |
|
| 293 |
These semantic differences are intentional and are biased toward maximal |
| 294 |
convenience. |
| 295 |
|
| 296 |
Note that in all cases, any envelope header present in the message is not |
| 297 |
included in the mapping interface. |
| 298 |
|
| 299 |
In a model generated from bytes, any header values that (in contravention of |
| 300 |
the RFCs) contain non-ASCII bytes will, when retrieved through this |
| 301 |
interface, be represented as :class:`~email.header.Header` objects with |
| 302 |
a charset of ``unknown-8bit``. |
| 303 |
|
| 304 |
|
| 305 |
.. method:: __len__() |
| 306 |
|
| 307 |
Return the total number of headers, including duplicates. |
| 308 |
|
| 309 |
|
| 310 |
.. method:: __contains__(name) |
| 311 |
|
| 312 |
Return ``True`` if the message object has a field named *name*. Matching is |
| 313 |
done case-insensitively and *name* should not include the trailing colon. |
| 314 |
Used for the ``in`` operator, e.g.:: |
| 315 |
|
| 316 |
if 'message-id' in myMessage: |
| 317 |
print('Message-ID:', myMessage['message-id']) |
| 318 |
|
| 319 |
|
| 320 |
.. method:: __getitem__(name) |
| 321 |
|
| 322 |
Return the value of the named header field. *name* should not include the |
| 323 |
colon field separator. If the header is missing, ``None`` is returned; a |
| 324 |
:exc:`KeyError` is never raised. |
| 325 |
|
| 326 |
Note that if the named field appears more than once in the message's |
| 327 |
headers, exactly which of those field values will be returned is |
| 328 |
undefined. Use the :meth:`get_all` method to get the values of all the |
| 329 |
extant named headers. |
| 330 |
|
| 331 |
|
| 332 |
.. method:: __setitem__(name, val) |
| 333 |
|
| 334 |
Add a header to the message with field name *name* and value *val*. The |
| 335 |
field is appended to the end of the message's existing fields. |
| 336 |
|
| 337 |
Note that this does *not* overwrite or delete any existing header with the same |
| 338 |
name. If you want to ensure that the new header is the only one present in the |
| 339 |
message with field name *name*, delete the field first, e.g.:: |
| 340 |
|
| 341 |
del msg['subject'] |
| 342 |
msg['subject'] = 'Python roolz!' |
| 343 |
|
| 344 |
|
| 345 |
.. method:: __delitem__(name) |
| 346 |
|
| 347 |
Delete all occurrences of the field with name *name* from the message's |
| 348 |
headers. No exception is raised if the named field isn't present in the |
| 349 |
headers. |
| 350 |
|
| 351 |
|
| 352 |
.. method:: keys() |
| 353 |
|
| 354 |
Return a list of all the message's header field names. |
| 355 |
|
| 356 |
|
| 357 |
.. method:: values() |
| 358 |
|
| 359 |
Return a list of all the message's field values. |
| 360 |
|
| 361 |
|
| 362 |
.. method:: items() |
| 363 |
|
| 364 |
Return a list of 2-tuples containing all the message's field headers and |
| 365 |
values. |
| 366 |
|
| 367 |
|
| 368 |
.. method:: get(name, failobj=None) |
| 369 |
|
| 370 |
Return the value of the named header field. This is identical to |
| 371 |
:meth:`~object.__getitem__` except that optional *failobj* is returned if the |
| 372 |
named header is missing (defaults to ``None``). |
| 373 |
|
| 374 |
Here are some additional useful methods: |
| 375 |
|
| 376 |
|
| 377 |
.. method:: get_all(name, failobj=None) |
| 378 |
|
| 379 |
Return a list of all the values for the field named *name*. If there are |
| 380 |
no such named headers in the message, *failobj* is returned (defaults to |
| 381 |
``None``). |
| 382 |
|
| 383 |
|
| 384 |
.. method:: add_header(_name, _value, **_params) |
| 385 |
|
| 386 |
Extended header setting. This method is similar to :meth:`__setitem__` |
| 387 |
except that additional header parameters can be provided as keyword |
| 388 |
arguments. *_name* is the header field to add and *_value* is the |
| 389 |
*primary* value for the header. |
| 390 |
|
| 391 |
For each item in the keyword argument dictionary *_params*, the key is |
| 392 |
taken as the parameter name, with underscores converted to dashes (since |
| 393 |
dashes are illegal in Python identifiers). Normally, the parameter will |
| 394 |
be added as ``key="value"`` unless the value is ``None``, in which case |
| 395 |
only the key will be added. If the value contains non-ASCII characters, |
| 396 |
it can be specified as a three tuple in the format |
| 397 |
``(CHARSET, LANGUAGE, VALUE)``, where ``CHARSET`` is a string naming the |
| 398 |
charset to be used to encode the value, ``LANGUAGE`` can usually be set |
| 399 |
to ``None`` or the empty string (see :rfc:`2231` for other possibilities), |
| 400 |
and ``VALUE`` is the string value containing non-ASCII code points. If |
| 401 |
a three tuple is not passed and the value contains non-ASCII characters, |
| 402 |
it is automatically encoded in :rfc:`2231` format using a ``CHARSET`` |
| 403 |
of ``utf-8`` and a ``LANGUAGE`` of ``None``. |
| 404 |
|
| 405 |
Here's an example:: |
| 406 |
|
| 407 |
msg.add_header('Content-Disposition', 'attachment', filename='bud.gif') |
| 408 |
|
| 409 |
This will add a header that looks like :: |
| 410 |
|
| 411 |
Content-Disposition: attachment; filename="bud.gif" |
| 412 |
|
| 413 |
An example with non-ASCII characters:: |
| 414 |
|
| 415 |
msg.add_header('Content-Disposition', 'attachment', |
| 416 |
filename=('iso-8859-1', '', 'Fußballer.ppt')) |
| 417 |
|
| 418 |
Which produces :: |
| 419 |
|
| 420 |
Content-Disposition: attachment; filename*="iso-8859-1''Fu%DFballer.ppt" |
| 421 |
|
| 422 |
|
| 423 |
.. method:: replace_header(_name, _value) |
| 424 |
|
| 425 |
Replace a header. Replace the first header found in the message that |
| 426 |
matches *_name*, retaining header order and field name case. If no |
| 427 |
matching header was found, a :exc:`KeyError` is raised. |
| 428 |
|
| 429 |
|
| 430 |
.. method:: get_content_type() |
| 431 |
|
| 432 |
Return the message's content type. The returned string is coerced to |
| 433 |
lower case of the form :mimetype:`maintype/subtype`. If there was no |
| 434 |
:mailheader:`Content-Type` header in the message the default type as given |
| 435 |
by :meth:`get_default_type` will be returned. Since according to |
| 436 |
:rfc:`2045`, messages always have a default type, :meth:`get_content_type` |
| 437 |
will always return a value. |
| 438 |
|
| 439 |
:rfc:`2045` defines a message's default type to be :mimetype:`text/plain` |
| 440 |
unless it appears inside a :mimetype:`multipart/digest` container, in |
| 441 |
which case it would be :mimetype:`message/rfc822`. If the |
| 442 |
:mailheader:`Content-Type` header has an invalid type specification, |
| 443 |
:rfc:`2045` mandates that the default type be :mimetype:`text/plain`. |
| 444 |
|
| 445 |
|
| 446 |
.. method:: get_content_maintype() |
| 447 |
|
| 448 |
Return the message's main content type. This is the :mimetype:`maintype` |
| 449 |
part of the string returned by :meth:`get_content_type`. |
| 450 |
|
| 451 |
|
| 452 |
.. method:: get_content_subtype() |
| 453 |
|
| 454 |
Return the message's sub-content type. This is the :mimetype:`subtype` |
| 455 |
part of the string returned by :meth:`get_content_type`. |
| 456 |
|
| 457 |
|
| 458 |
.. method:: get_default_type() |
| 459 |
|
| 460 |
Return the default content type. Most messages have a default content |
| 461 |
type of :mimetype:`text/plain`, except for messages that are subparts of |
| 462 |
:mimetype:`multipart/digest` containers. Such subparts have a default |
| 463 |
content type of :mimetype:`message/rfc822`. |
| 464 |
|
| 465 |
|
| 466 |
.. method:: set_default_type(ctype) |
| 467 |
|
| 468 |
Set the default content type. *ctype* should either be |
| 469 |
:mimetype:`text/plain` or :mimetype:`message/rfc822`, although this is not |
| 470 |
enforced. The default content type is not stored in the |
| 471 |
:mailheader:`Content-Type` header. |
| 472 |
|
| 473 |
|
| 474 |
.. method:: get_params(failobj=None, header='content-type', unquote=True) |
| 475 |
|
| 476 |
Return the message's :mailheader:`Content-Type` parameters, as a list. |
| 477 |
The elements of the returned list are 2-tuples of key/value pairs, as |
| 478 |
split on the ``'='`` sign. The left hand side of the ``'='`` is the key, |
| 479 |
while the right hand side is the value. If there is no ``'='`` sign in |
| 480 |
the parameter the value is the empty string, otherwise the value is as |
| 481 |
described in :meth:`get_param` and is unquoted if optional *unquote* is |
| 482 |
``True`` (the default). |
| 483 |
|
| 484 |
Optional *failobj* is the object to return if there is no |
| 485 |
:mailheader:`Content-Type` header. Optional *header* is the header to |
| 486 |
search instead of :mailheader:`Content-Type`. |
| 487 |
|
| 488 |
This is a legacy method. On the |
| 489 |
:class:`~email.message.EmailMessage` class its functionality is |
| 490 |
replaced by the *params* property of the individual header objects |
| 491 |
returned by the header access methods. |
| 492 |
|
| 493 |
|
| 494 |
.. method:: get_param(param, failobj=None, header='content-type', unquote=True) |
| 495 |
|
| 496 |
Return the value of the :mailheader:`Content-Type` header's parameter |
| 497 |
*param* as a string. If the message has no :mailheader:`Content-Type` |
| 498 |
header or if there is no such parameter, then *failobj* is returned |
| 499 |
(defaults to ``None``). |
| 500 |
|
| 501 |
Optional *header* if given, specifies the message header to use instead of |
| 502 |
:mailheader:`Content-Type`. |
| 503 |
|
| 504 |
Parameter keys are always compared case insensitively. The return value |
| 505 |
can either be a string, or a 3-tuple if the parameter was :rfc:`2231` |
| 506 |
encoded. When it's a 3-tuple, the elements of the value are of the form |
| 507 |
``(CHARSET, LANGUAGE, VALUE)``. Note that both ``CHARSET`` and |
| 508 |
``LANGUAGE`` can be ``None``, in which case you should consider ``VALUE`` |
| 509 |
to be encoded in the ``us-ascii`` charset. You can usually ignore |
| 510 |
``LANGUAGE``. |
| 511 |
|
| 512 |
If your application doesn't care whether the parameter was encoded as in |
| 513 |
:rfc:`2231`, you can collapse the parameter value by calling |
| 514 |
:func:`email.utils.collapse_rfc2231_value`, passing in the return value |
| 515 |
from :meth:`get_param`. This will return a suitably decoded Unicode |
| 516 |
string when the value is a tuple, or the original string unquoted if it |
| 517 |
isn't. For example:: |
| 518 |
|
| 519 |
rawparam = msg.get_param('foo') |
| 520 |
param = email.utils.collapse_rfc2231_value(rawparam) |
| 521 |
|
| 522 |
In any case, the parameter value (either the returned string, or the |
| 523 |
``VALUE`` item in the 3-tuple) is always unquoted, unless *unquote* is set |
| 524 |
to ``False``. |
| 525 |
|
| 526 |
This is a legacy method. On the |
| 527 |
:class:`~email.message.EmailMessage` class its functionality is |
| 528 |
replaced by the *params* property of the individual header objects |
| 529 |
returned by the header access methods. |
| 530 |
|
| 531 |
|
| 532 |
.. method:: set_param(param, value, header='Content-Type', requote=True, \ |
| 533 |
charset=None, language='', replace=False) |
| 534 |
|
| 535 |
Set a parameter in the :mailheader:`Content-Type` header. If the |
| 536 |
parameter already exists in the header, its value will be replaced with |
| 537 |
*value*. If the :mailheader:`Content-Type` header as not yet been defined |
| 538 |
for this message, it will be set to :mimetype:`text/plain` and the new |
| 539 |
parameter value will be appended as per :rfc:`2045`. |
| 540 |
|
| 541 |
Optional *header* specifies an alternative header to |
| 542 |
:mailheader:`Content-Type`, and all parameters will be quoted as necessary |
| 543 |
unless optional *requote* is ``False`` (the default is ``True``). |
| 544 |
|
| 545 |
If optional *charset* is specified, the parameter will be encoded |
| 546 |
according to :rfc:`2231`. Optional *language* specifies the RFC 2231 |
| 547 |
language, defaulting to the empty string. Both *charset* and *language* |
| 548 |
should be strings. |
| 549 |
|
| 550 |
If *replace* is ``False`` (the default) the header is moved to the |
| 551 |
end of the list of headers. If *replace* is ``True``, the header |
| 552 |
will be updated in place. |
| 553 |
|
| 554 |
.. versionchanged:: 3.4 ``replace`` keyword was added. |
| 555 |
|
| 556 |
|
| 557 |
.. method:: del_param(param, header='content-type', requote=True) |
| 558 |
|
| 559 |
Remove the given parameter completely from the :mailheader:`Content-Type` |
| 560 |
header. The header will be re-written in place without the parameter or |
| 561 |
its value. All values will be quoted as necessary unless *requote* is |
| 562 |
``False`` (the default is ``True``). Optional *header* specifies an |
| 563 |
alternative to :mailheader:`Content-Type`. |
| 564 |
|
| 565 |
|
| 566 |
.. method:: set_type(type, header='Content-Type', requote=True) |
| 567 |
|
| 568 |
Set the main type and subtype for the :mailheader:`Content-Type` |
| 569 |
header. *type* must be a string in the form :mimetype:`maintype/subtype`, |
| 570 |
otherwise a :exc:`ValueError` is raised. |
| 571 |
|
| 572 |
This method replaces the :mailheader:`Content-Type` header, keeping all |
| 573 |
the parameters in place. If *requote* is ``False``, this leaves the |
| 574 |
existing header's quoting as is, otherwise the parameters will be quoted |
| 575 |
(the default). |
| 576 |
|
| 577 |
An alternative header can be specified in the *header* argument. When the |
| 578 |
:mailheader:`Content-Type` header is set a :mailheader:`MIME-Version` |
| 579 |
header is also added. |
| 580 |
|
| 581 |
This is a legacy method. On the |
| 582 |
:class:`~email.message.EmailMessage` class its functionality is |
| 583 |
replaced by the ``make_`` and ``add_`` methods. |
| 584 |
|
| 585 |
|
| 586 |
.. method:: get_filename(failobj=None) |
| 587 |
|
| 588 |
Return the value of the ``filename`` parameter of the |
| 589 |
:mailheader:`Content-Disposition` header of the message. If the header |
| 590 |
does not have a ``filename`` parameter, this method falls back to looking |
| 591 |
for the ``name`` parameter on the :mailheader:`Content-Type` header. If |
| 592 |
neither is found, or the header is missing, then *failobj* is returned. |
| 593 |
The returned string will always be unquoted as per |
| 594 |
:func:`email.utils.unquote`. |
| 595 |
|
| 596 |
|
| 597 |
.. method:: get_boundary(failobj=None) |
| 598 |
|
| 599 |
Return the value of the ``boundary`` parameter of the |
| 600 |
:mailheader:`Content-Type` header of the message, or *failobj* if either |
| 601 |
the header is missing, or has no ``boundary`` parameter. The returned |
| 602 |
string will always be unquoted as per :func:`email.utils.unquote`. |
| 603 |
|
| 604 |
|
| 605 |
.. method:: set_boundary(boundary) |
| 606 |
|
| 607 |
Set the ``boundary`` parameter of the :mailheader:`Content-Type` header to |
| 608 |
*boundary*. :meth:`set_boundary` will always quote *boundary* if |
| 609 |
necessary. A :exc:`~email.errors.HeaderParseError` is raised if the |
| 610 |
message object has no :mailheader:`Content-Type` header. |
| 611 |
|
| 612 |
Note that using this method is subtly different than deleting the old |
| 613 |
:mailheader:`Content-Type` header and adding a new one with the new |
| 614 |
boundary via :meth:`add_header`, because :meth:`set_boundary` preserves |
| 615 |
the order of the :mailheader:`Content-Type` header in the list of |
| 616 |
headers. However, it does *not* preserve any continuation lines which may |
| 617 |
have been present in the original :mailheader:`Content-Type` header. |
| 618 |
|
| 619 |
|
| 620 |
.. method:: get_content_charset(failobj=None) |
| 621 |
|
| 622 |
Return the ``charset`` parameter of the :mailheader:`Content-Type` header, |
| 623 |
coerced to lower case. If there is no :mailheader:`Content-Type` header, or if |
| 624 |
that header has no ``charset`` parameter, *failobj* is returned. |
| 625 |
|
| 626 |
Note that this method differs from :meth:`get_charset` which returns the |
| 627 |
:class:`~email.charset.Charset` instance for the default encoding of the message body. |
| 628 |
|
| 629 |
|
| 630 |
.. method:: get_charsets(failobj=None) |
| 631 |
|
| 632 |
Return a list containing the character set names in the message. If the |
| 633 |
message is a :mimetype:`multipart`, then the list will contain one element |
| 634 |
for each subpart in the payload, otherwise, it will be a list of length 1. |
| 635 |
|
| 636 |
Each item in the list will be a string which is the value of the |
| 637 |
``charset`` parameter in the :mailheader:`Content-Type` header for the |
| 638 |
represented subpart. However, if the subpart has no |
| 639 |
:mailheader:`Content-Type` header, no ``charset`` parameter, or is not of |
| 640 |
the :mimetype:`text` main MIME type, then that item in the returned list |
| 641 |
will be *failobj*. |
| 642 |
|
| 643 |
|
| 644 |
.. method:: get_content_disposition() |
| 645 |
|
| 646 |
Return the lowercased value (without parameters) of the message's |
| 647 |
:mailheader:`Content-Disposition` header if it has one, or ``None``. The |
| 648 |
possible values for this method are *inline*, *attachment* or ``None`` |
| 649 |
if the message follows :rfc:`2183`. |
| 650 |
|
| 651 |
.. versionadded:: 3.5 |
| 652 |
|
| 653 |
.. method:: walk() |
| 654 |
|
| 655 |
The :meth:`walk` method is an all-purpose generator which can be used to |
| 656 |
iterate over all the parts and subparts of a message object tree, in |
| 657 |
depth-first traversal order. You will typically use :meth:`walk` as the |
| 658 |
iterator in a ``for`` loop; each iteration returns the next subpart. |
| 659 |
|
| 660 |
Here's an example that prints the MIME type of every part of a multipart |
| 661 |
message structure: |
| 662 |
|
| 663 |
.. testsetup:: |
| 664 |
|
| 665 |
import email |
| 666 |
from email import message_from_binary_file |
| 667 |
from os.path import join, dirname |
| 668 |
lib_dir = dirname(dirname(email.__file__)) |
| 669 |
file_path = join(lib_dir, 'test/test_email/data/msg_16.txt') |
| 670 |
with open(file_path, 'rb') as f: |
| 671 |
msg = message_from_binary_file(f) |
| 672 |
from email.iterators import _structure |
| 673 |
|
| 674 |
.. doctest:: |
| 675 |
|
| 676 |
>>> for part in msg.walk(): |
| 677 |
... print(part.get_content_type()) |
| 678 |
multipart/report |
| 679 |
text/plain |
| 680 |
message/delivery-status |
| 681 |
text/plain |
| 682 |
text/plain |
| 683 |
message/rfc822 |
| 684 |
text/plain |
| 685 |
|
| 686 |
``walk`` iterates over the subparts of any part where |
| 687 |
:meth:`is_multipart` returns ``True``, even though |
| 688 |
``msg.get_content_maintype() == 'multipart'`` may return ``False``. We |
| 689 |
can see this in our example by making use of the ``_structure`` debug |
| 690 |
helper function: |
| 691 |
|
| 692 |
.. doctest:: |
| 693 |
|
| 694 |
>>> for part in msg.walk(): |
| 695 |
... print(part.get_content_maintype() == 'multipart', |
| 696 |
... part.is_multipart()) |
| 697 |
True True |
| 698 |
False False |
| 699 |
False True |
| 700 |
False False |
| 701 |
False False |
| 702 |
False True |
| 703 |
False False |
| 704 |
>>> _structure(msg) |
| 705 |
multipart/report |
| 706 |
text/plain |
| 707 |
message/delivery-status |
| 708 |
text/plain |
| 709 |
text/plain |
| 710 |
message/rfc822 |
| 711 |
text/plain |
| 712 |
|
| 713 |
Here the ``message`` parts are not ``multiparts``, but they do contain |
| 714 |
subparts. ``is_multipart()`` returns ``True`` and ``walk`` descends |
| 715 |
into the subparts. |
| 716 |
|
| 717 |
|
| 718 |
:class:`Message` objects can also optionally contain two instance attributes, |
| 719 |
which can be used when generating the plain text of a MIME message. |
| 720 |
|
| 721 |
|
| 722 |
.. attribute:: preamble |
| 723 |
|
| 724 |
The format of a MIME document allows for some text between the blank line |
| 725 |
following the headers, and the first multipart boundary string. Normally, |
| 726 |
this text is never visible in a MIME-aware mail reader because it falls |
| 727 |
outside the standard MIME armor. However, when viewing the raw text of |
| 728 |
the message, or when viewing the message in a non-MIME aware reader, this |
| 729 |
text can become visible. |
| 730 |
|
| 731 |
The *preamble* attribute contains this leading extra-armor text for MIME |
| 732 |
documents. When the :class:`~email.parser.Parser` discovers some text |
| 733 |
after the headers but before the first boundary string, it assigns this |
| 734 |
text to the message's *preamble* attribute. When the |
| 735 |
:class:`~email.generator.Generator` is writing out the plain text |
| 736 |
representation of a MIME message, and it finds the |
| 737 |
message has a *preamble* attribute, it will write this text in the area |
| 738 |
between the headers and the first boundary. See :mod:`email.parser` and |
| 739 |
:mod:`email.generator` for details. |
| 740 |
|
| 741 |
Note that if the message object has no preamble, the *preamble* attribute |
| 742 |
will be ``None``. |
| 743 |
|
| 744 |
|
| 745 |
.. attribute:: epilogue |
| 746 |
|
| 747 |
The *epilogue* attribute acts the same way as the *preamble* attribute, |
| 748 |
except that it contains text that appears between the last boundary and |
| 749 |
the end of the message. |
| 750 |
|
| 751 |
You do not need to set the epilogue to the empty string in order for the |
| 752 |
:class:`~email.generator.Generator` to print a newline at the end of the |
| 753 |
file. |
| 754 |
|
| 755 |
|
| 756 |
.. attribute:: defects |
| 757 |
|
| 758 |
The *defects* attribute contains a list of all the problems found when |
| 759 |
parsing this message. See :mod:`email.errors` for a detailed description |
| 760 |
of the possible parsing defects. |