/Doc/library/email.message.rst

http://unladen-swallow.googlecode.com/ · ReStructuredText · 569 lines · 377 code · 192 blank · 0 comment · 0 complexity · 0b6ec975eaafe5fd0fd43f97383d00b0 MD5 · raw file

  1. :mod:`email`: Representing an email message
  2. -------------------------------------------
  3. .. module:: email.message
  4. :synopsis: The base class representing email messages.
  5. The central class in the :mod:`email` package is the :class:`Message` class,
  6. imported from the :mod:`email.message` module. It is the base class for the
  7. :mod:`email` object model. :class:`Message` provides the core functionality for
  8. setting and querying header fields, and for accessing message bodies.
  9. Conceptually, a :class:`Message` object consists of *headers* and *payloads*.
  10. Headers are :rfc:`2822` style field names and values where the field name and
  11. value are separated by a colon. The colon is not part of either the field name
  12. or the field value.
  13. Headers are stored and returned in case-preserving form but are matched
  14. case-insensitively. There may also be a single envelope header, also known as
  15. the *Unix-From* header or the ``From_`` header. The payload is either a string
  16. in the case of simple message objects or a list of :class:`Message` objects for
  17. MIME container documents (e.g. :mimetype:`multipart/\*` and
  18. :mimetype:`message/rfc822`).
  19. :class:`Message` objects provide a mapping style interface for accessing the
  20. message headers, and an explicit interface for accessing both the headers and
  21. the payload. It provides convenience methods for generating a flat text
  22. representation of the message object tree, for accessing commonly used header
  23. parameters, and for recursively walking over the object tree.
  24. Here are the methods of the :class:`Message` class:
  25. .. class:: Message()
  26. The constructor takes no arguments.
  27. .. method:: as_string([unixfrom])
  28. Return the entire message flattened as a string. When optional *unixfrom*
  29. is ``True``, the envelope header is included in the returned string.
  30. *unixfrom* defaults to ``False``.
  31. Note that this method is provided as a convenience and may not always
  32. format the message the way you want. For example, by default it mangles
  33. lines that begin with ``From``. For more flexibility, instantiate a
  34. :class:`~email.generator.Generator` instance and use its :meth:`flatten`
  35. method directly. For example::
  36. from cStringIO import StringIO
  37. from email.generator import Generator
  38. fp = StringIO()
  39. g = Generator(fp, mangle_from_=False, maxheaderlen=60)
  40. g.flatten(msg)
  41. text = fp.getvalue()
  42. .. method:: __str__()
  43. Equivalent to ``as_string(unixfrom=True)``.
  44. .. method:: is_multipart()
  45. Return ``True`` if the message's payload is a list of sub-\
  46. :class:`Message` objects, otherwise return ``False``. When
  47. :meth:`is_multipart` returns False, the payload should be a string object.
  48. .. method:: set_unixfrom(unixfrom)
  49. Set the message's envelope header to *unixfrom*, which should be a string.
  50. .. method:: get_unixfrom()
  51. Return the message's envelope header. Defaults to ``None`` if the
  52. envelope header was never set.
  53. .. method:: attach(payload)
  54. Add the given *payload* to the current payload, which must be ``None`` or
  55. a list of :class:`Message` objects before the call. After the call, the
  56. payload will always be a list of :class:`Message` objects. If you want to
  57. set the payload to a scalar object (e.g. a string), use
  58. :meth:`set_payload` instead.
  59. .. method:: get_payload([i[, decode]])
  60. Return the current payload, which will be a list of
  61. :class:`Message` objects when :meth:`is_multipart` is ``True``, or a
  62. string when :meth:`is_multipart` is ``False``. If the payload is a list
  63. and you mutate the list object, you modify the message's payload in place.
  64. With optional argument *i*, :meth:`get_payload` will return the *i*-th
  65. element of the payload, counting from zero, if :meth:`is_multipart` is
  66. ``True``. An :exc:`IndexError` will be raised if *i* is less than 0 or
  67. greater than or equal to the number of items in the payload. If the
  68. payload is a string (i.e. :meth:`is_multipart` is ``False``) and *i* is
  69. given, a :exc:`TypeError` is raised.
  70. Optional *decode* is a flag indicating whether the payload should be
  71. decoded or not, according to the :mailheader:`Content-Transfer-Encoding`
  72. header. When ``True`` and the message is not a multipart, the payload will
  73. be decoded if this header's value is ``quoted-printable`` or ``base64``.
  74. If some other encoding is used, or :mailheader:`Content-Transfer-Encoding`
  75. header is missing, or if the payload has bogus base64 data, the payload is
  76. returned as-is (undecoded). If the message is a multipart and the
  77. *decode* flag is ``True``, then ``None`` is returned. The default for
  78. *decode* is ``False``.
  79. .. method:: set_payload(payload[, charset])
  80. Set the entire message object's payload to *payload*. It is the client's
  81. responsibility to ensure the payload invariants. Optional *charset* sets
  82. the message's default character set; see :meth:`set_charset` for details.
  83. .. versionchanged:: 2.2.2
  84. *charset* argument added.
  85. .. method:: set_charset(charset)
  86. Set the character set of the payload to *charset*, which can either be a
  87. :class:`~email.charset.Charset` instance (see :mod:`email.charset`), a
  88. string naming a character set, or ``None``. If it is a string, it will
  89. be converted to a :class:`~email.charset.Charset` instance. If *charset*
  90. is ``None``, the ``charset`` parameter will be removed from the
  91. :mailheader:`Content-Type` header. Anything else will generate a
  92. :exc:`TypeError`.
  93. The message will be assumed to be of type :mimetype:`text/\*` encoded with
  94. *charset.input_charset*. It will be converted to *charset.output_charset*
  95. and encoded properly, if needed, when generating the plain text
  96. representation of the message. MIME headers (:mailheader:`MIME-Version`,
  97. :mailheader:`Content-Type`, :mailheader:`Content-Transfer-Encoding`) will
  98. be added as needed.
  99. .. versionadded:: 2.2.2
  100. .. method:: get_charset()
  101. Return the :class:`~email.charset.Charset` instance associated with the
  102. message's payload.
  103. .. versionadded:: 2.2.2
  104. The following methods implement a mapping-like interface for accessing the
  105. message's :rfc:`2822` headers. Note that there are some semantic differences
  106. between these methods and a normal mapping (i.e. dictionary) interface. For
  107. example, in a dictionary there are no duplicate keys, but here there may be
  108. duplicate message headers. Also, in dictionaries there is no guaranteed
  109. order to the keys returned by :meth:`keys`, but in a :class:`Message` object,
  110. headers are always returned in the order they appeared in the original
  111. message, or were added to the message later. Any header deleted and then
  112. re-added are always appended to the end of the header list.
  113. These semantic differences are intentional and are biased toward maximal
  114. convenience.
  115. Note that in all cases, any envelope header present in the message is not
  116. included in the mapping interface.
  117. .. method:: __len__()
  118. Return the total number of headers, including duplicates.
  119. .. method:: __contains__(name)
  120. Return true if the message object has a field named *name*. Matching is
  121. done case-insensitively and *name* should not include the trailing colon.
  122. Used for the ``in`` operator, e.g.::
  123. if 'message-id' in myMessage:
  124. print 'Message-ID:', myMessage['message-id']
  125. .. method:: __getitem__(name)
  126. Return the value of the named header field. *name* should not include the
  127. colon field separator. If the header is missing, ``None`` is returned; a
  128. :exc:`KeyError` is never raised.
  129. Note that if the named field appears more than once in the message's
  130. headers, exactly which of those field values will be returned is
  131. undefined. Use the :meth:`get_all` method to get the values of all the
  132. extant named headers.
  133. .. method:: __setitem__(name, val)
  134. Add a header to the message with field name *name* and value *val*. The
  135. field is appended to the end of the message's existing fields.
  136. Note that this does *not* overwrite or delete any existing header with the same
  137. name. If you want to ensure that the new header is the only one present in the
  138. message with field name *name*, delete the field first, e.g.::
  139. del msg['subject']
  140. msg['subject'] = 'Python roolz!'
  141. .. method:: __delitem__(name)
  142. Delete all occurrences of the field with name *name* from the message's
  143. headers. No exception is raised if the named field isn't present in the headers.
  144. .. method:: has_key(name)
  145. Return true if the message contains a header field named *name*, otherwise
  146. return false.
  147. .. method:: keys()
  148. Return a list of all the message's header field names.
  149. .. method:: values()
  150. Return a list of all the message's field values.
  151. .. method:: items()
  152. Return a list of 2-tuples containing all the message's field headers and
  153. values.
  154. .. method:: get(name[, failobj])
  155. Return the value of the named header field. This is identical to
  156. :meth:`__getitem__` except that optional *failobj* is returned if the
  157. named header is missing (defaults to ``None``).
  158. Here are some additional useful methods:
  159. .. method:: get_all(name[, failobj])
  160. Return a list of all the values for the field named *name*. If there are
  161. no such named headers in the message, *failobj* is returned (defaults to
  162. ``None``).
  163. .. method:: add_header(_name, _value, **_params)
  164. Extended header setting. This method is similar to :meth:`__setitem__`
  165. except that additional header parameters can be provided as keyword
  166. arguments. *_name* is the header field to add and *_value* is the
  167. *primary* value for the header.
  168. For each item in the keyword argument dictionary *_params*, the key is
  169. taken as the parameter name, with underscores converted to dashes (since
  170. dashes are illegal in Python identifiers). Normally, the parameter will
  171. be added as ``key="value"`` unless the value is ``None``, in which case
  172. only the key will be added.
  173. Here's an example::
  174. msg.add_header('Content-Disposition', 'attachment', filename='bud.gif')
  175. This will add a header that looks like ::
  176. Content-Disposition: attachment; filename="bud.gif"
  177. .. method:: replace_header(_name, _value)
  178. Replace a header. Replace the first header found in the message that
  179. matches *_name*, retaining header order and field name case. If no
  180. matching header was found, a :exc:`KeyError` is raised.
  181. .. versionadded:: 2.2.2
  182. .. method:: get_content_type()
  183. Return the message's content type. The returned string is coerced to
  184. lower case of the form :mimetype:`maintype/subtype`. If there was no
  185. :mailheader:`Content-Type` header in the message the default type as given
  186. by :meth:`get_default_type` will be returned. Since according to
  187. :rfc:`2045`, messages always have a default type, :meth:`get_content_type`
  188. will always return a value.
  189. :rfc:`2045` defines a message's default type to be :mimetype:`text/plain`
  190. unless it appears inside a :mimetype:`multipart/digest` container, in
  191. which case it would be :mimetype:`message/rfc822`. If the
  192. :mailheader:`Content-Type` header has an invalid type specification,
  193. :rfc:`2045` mandates that the default type be :mimetype:`text/plain`.
  194. .. versionadded:: 2.2.2
  195. .. method:: get_content_maintype()
  196. Return the message's main content type. This is the :mimetype:`maintype`
  197. part of the string returned by :meth:`get_content_type`.
  198. .. versionadded:: 2.2.2
  199. .. method:: get_content_subtype()
  200. Return the message's sub-content type. This is the :mimetype:`subtype`
  201. part of the string returned by :meth:`get_content_type`.
  202. .. versionadded:: 2.2.2
  203. .. method:: get_default_type()
  204. Return the default content type. Most messages have a default content
  205. type of :mimetype:`text/plain`, except for messages that are subparts of
  206. :mimetype:`multipart/digest` containers. Such subparts have a default
  207. content type of :mimetype:`message/rfc822`.
  208. .. versionadded:: 2.2.2
  209. .. method:: set_default_type(ctype)
  210. Set the default content type. *ctype* should either be
  211. :mimetype:`text/plain` or :mimetype:`message/rfc822`, although this is not
  212. enforced. The default content type is not stored in the
  213. :mailheader:`Content-Type` header.
  214. .. versionadded:: 2.2.2
  215. .. method:: get_params([failobj[, header[, unquote]]])
  216. Return the message's :mailheader:`Content-Type` parameters, as a list.
  217. The elements of the returned list are 2-tuples of key/value pairs, as
  218. split on the ``'='`` sign. The left hand side of the ``'='`` is the key,
  219. while the right hand side is the value. If there is no ``'='`` sign in
  220. the parameter the value is the empty string, otherwise the value is as
  221. described in :meth:`get_param` and is unquoted if optional *unquote* is
  222. ``True`` (the default).
  223. Optional *failobj* is the object to return if there is no
  224. :mailheader:`Content-Type` header. Optional *header* is the header to
  225. search instead of :mailheader:`Content-Type`.
  226. .. versionchanged:: 2.2.2
  227. *unquote* argument added.
  228. .. method:: get_param(param[, failobj[, header[, unquote]]])
  229. Return the value of the :mailheader:`Content-Type` header's parameter
  230. *param* as a string. If the message has no :mailheader:`Content-Type`
  231. header or if there is no such parameter, then *failobj* is returned
  232. (defaults to ``None``).
  233. Optional *header* if given, specifies the message header to use instead of
  234. :mailheader:`Content-Type`.
  235. Parameter keys are always compared case insensitively. The return value
  236. can either be a string, or a 3-tuple if the parameter was :rfc:`2231`
  237. encoded. When it's a 3-tuple, the elements of the value are of the form
  238. ``(CHARSET, LANGUAGE, VALUE)``. Note that both ``CHARSET`` and
  239. ``LANGUAGE`` can be ``None``, in which case you should consider ``VALUE``
  240. to be encoded in the ``us-ascii`` charset. You can usually ignore
  241. ``LANGUAGE``.
  242. If your application doesn't care whether the parameter was encoded as in
  243. :rfc:`2231`, you can collapse the parameter value by calling
  244. :func:`email.utils.collapse_rfc2231_value`, passing in the return value
  245. from :meth:`get_param`. This will return a suitably decoded Unicode
  246. string whn the value is a tuple, or the original string unquoted if it
  247. isn't. For example::
  248. rawparam = msg.get_param('foo')
  249. param = email.utils.collapse_rfc2231_value(rawparam)
  250. In any case, the parameter value (either the returned string, or the
  251. ``VALUE`` item in the 3-tuple) is always unquoted, unless *unquote* is set
  252. to ``False``.
  253. .. versionchanged:: 2.2.2
  254. *unquote* argument added, and 3-tuple return value possible.
  255. .. method:: set_param(param, value[, header[, requote[, charset[, language]]]])
  256. Set a parameter in the :mailheader:`Content-Type` header. If the
  257. parameter already exists in the header, its value will be replaced with
  258. *value*. If the :mailheader:`Content-Type` header as not yet been defined
  259. for this message, it will be set to :mimetype:`text/plain` and the new
  260. parameter value will be appended as per :rfc:`2045`.
  261. Optional *header* specifies an alternative header to
  262. :mailheader:`Content-Type`, and all parameters will be quoted as necessary
  263. unless optional *requote* is ``False`` (the default is ``True``).
  264. If optional *charset* is specified, the parameter will be encoded
  265. according to :rfc:`2231`. Optional *language* specifies the RFC 2231
  266. language, defaulting to the empty string. Both *charset* and *language*
  267. should be strings.
  268. .. versionadded:: 2.2.2
  269. .. method:: del_param(param[, header[, requote]])
  270. Remove the given parameter completely from the :mailheader:`Content-Type`
  271. header. The header will be re-written in place without the parameter or
  272. its value. All values will be quoted as necessary unless *requote* is
  273. ``False`` (the default is ``True``). Optional *header* specifies an
  274. alternative to :mailheader:`Content-Type`.
  275. .. versionadded:: 2.2.2
  276. .. method:: set_type(type[, header][, requote])
  277. Set the main type and subtype for the :mailheader:`Content-Type`
  278. header. *type* must be a string in the form :mimetype:`maintype/subtype`,
  279. otherwise a :exc:`ValueError` is raised.
  280. This method replaces the :mailheader:`Content-Type` header, keeping all
  281. the parameters in place. If *requote* is ``False``, this leaves the
  282. existing header's quoting as is, otherwise the parameters will be quoted
  283. (the default).
  284. An alternative header can be specified in the *header* argument. When the
  285. :mailheader:`Content-Type` header is set a :mailheader:`MIME-Version`
  286. header is also added.
  287. .. versionadded:: 2.2.2
  288. .. method:: get_filename([failobj])
  289. Return the value of the ``filename`` parameter of the
  290. :mailheader:`Content-Disposition` header of the message. If the header
  291. does not have a ``filename`` parameter, this method falls back to looking
  292. for the ``name`` parameter. If neither is found, or the header is
  293. missing, then *failobj* is returned. The returned string will always be
  294. unquoted as per :func:`email.utils.unquote`.
  295. .. method:: get_boundary([failobj])
  296. Return the value of the ``boundary`` parameter of the
  297. :mailheader:`Content-Type` header of the message, or *failobj* if either
  298. the header is missing, or has no ``boundary`` parameter. The returned
  299. string will always be unquoted as per :func:`email.utils.unquote`.
  300. .. method:: set_boundary(boundary)
  301. Set the ``boundary`` parameter of the :mailheader:`Content-Type` header to
  302. *boundary*. :meth:`set_boundary` will always quote *boundary* if
  303. necessary. A :exc:`HeaderParseError` is raised if the message object has
  304. no :mailheader:`Content-Type` header.
  305. Note that using this method is subtly different than deleting the old
  306. :mailheader:`Content-Type` header and adding a new one with the new
  307. boundary via :meth:`add_header`, because :meth:`set_boundary` preserves
  308. the order of the :mailheader:`Content-Type` header in the list of
  309. headers. However, it does *not* preserve any continuation lines which may
  310. have been present in the original :mailheader:`Content-Type` header.
  311. .. method:: get_content_charset([failobj])
  312. Return the ``charset`` parameter of the :mailheader:`Content-Type` header,
  313. coerced to lower case. If there is no :mailheader:`Content-Type` header, or if
  314. that header has no ``charset`` parameter, *failobj* is returned.
  315. Note that this method differs from :meth:`get_charset` which returns the
  316. :class:`~email.charset.Charset` instance for the default encoding of the message body.
  317. .. versionadded:: 2.2.2
  318. .. method:: get_charsets([failobj])
  319. Return a list containing the character set names in the message. If the
  320. message is a :mimetype:`multipart`, then the list will contain one element
  321. for each subpart in the payload, otherwise, it will be a list of length 1.
  322. Each item in the list will be a string which is the value of the
  323. ``charset`` parameter in the :mailheader:`Content-Type` header for the
  324. represented subpart. However, if the subpart has no
  325. :mailheader:`Content-Type` header, no ``charset`` parameter, or is not of
  326. the :mimetype:`text` main MIME type, then that item in the returned list
  327. will be *failobj*.
  328. .. method:: walk()
  329. The :meth:`walk` method is an all-purpose generator which can be used to
  330. iterate over all the parts and subparts of a message object tree, in
  331. depth-first traversal order. You will typically use :meth:`walk` as the
  332. iterator in a ``for`` loop; each iteration returns the next subpart.
  333. Here's an example that prints the MIME type of every part of a multipart
  334. message structure::
  335. >>> for part in msg.walk():
  336. ... print part.get_content_type()
  337. multipart/report
  338. text/plain
  339. message/delivery-status
  340. text/plain
  341. text/plain
  342. message/rfc822
  343. .. versionchanged:: 2.5
  344. The previously deprecated methods :meth:`get_type`, :meth:`get_main_type`, and
  345. :meth:`get_subtype` were removed.
  346. :class:`Message` objects can also optionally contain two instance attributes,
  347. which can be used when generating the plain text of a MIME message.
  348. .. attribute:: preamble
  349. The format of a MIME document allows for some text between the blank line
  350. following the headers, and the first multipart boundary string. Normally,
  351. this text is never visible in a MIME-aware mail reader because it falls
  352. outside the standard MIME armor. However, when viewing the raw text of
  353. the message, or when viewing the message in a non-MIME aware reader, this
  354. text can become visible.
  355. The *preamble* attribute contains this leading extra-armor text for MIME
  356. documents. When the :class:`~email.parser.Parser` discovers some text
  357. after the headers but before the first boundary string, it assigns this
  358. text to the message's *preamble* attribute. When the
  359. :class:`~email.generator.Generator` is writing out the plain text
  360. representation of a MIME message, and it finds the
  361. message has a *preamble* attribute, it will write this text in the area
  362. between the headers and the first boundary. See :mod:`email.parser` and
  363. :mod:`email.generator` for details.
  364. Note that if the message object has no preamble, the *preamble* attribute
  365. will be ``None``.
  366. .. attribute:: epilogue
  367. The *epilogue* attribute acts the same way as the *preamble* attribute,
  368. except that it contains text that appears between the last boundary and
  369. the end of the message.
  370. .. versionchanged:: 2.5
  371. You do not need to set the epilogue to the empty string in order for the
  372. :class:`Generator` to print a newline at the end of the file.
  373. .. attribute:: defects
  374. The *defects* attribute contains a list of all the problems found when
  375. parsing this message. See :mod:`email.errors` for a detailed description
  376. of the possible parsing defects.
  377. .. versionadded:: 2.4