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