/Lib/email/message.py

http://unladen-swallow.googlecode.com/ · Python · 790 lines · 605 code · 40 blank · 145 comment · 73 complexity · d7c39457414798d54a8f90bbca57b8b1 MD5 · raw file

  1. # Copyright (C) 2001-2006 Python Software Foundation
  2. # Author: Barry Warsaw
  3. # Contact: email-sig@python.org
  4. """Basic message object for the email package object model."""
  5. __all__ = ['Message']
  6. import re
  7. import uu
  8. import binascii
  9. import warnings
  10. from cStringIO import StringIO
  11. # Intrapackage imports
  12. import email.charset
  13. from email import utils
  14. from email import errors
  15. SEMISPACE = '; '
  16. # Regular expression that matches `special' characters in parameters, the
  17. # existence of which force quoting of the parameter value.
  18. tspecials = re.compile(r'[ \(\)<>@,;:\\"/\[\]\?=]')
  19. # Helper functions
  20. def _splitparam(param):
  21. # Split header parameters. BAW: this may be too simple. It isn't
  22. # strictly RFC 2045 (section 5.1) compliant, but it catches most headers
  23. # found in the wild. We may eventually need a full fledged parser
  24. # eventually.
  25. a, sep, b = param.partition(';')
  26. if not sep:
  27. return a.strip(), None
  28. return a.strip(), b.strip()
  29. def _formatparam(param, value=None, quote=True):
  30. """Convenience function to format and return a key=value pair.
  31. This will quote the value if needed or if quote is true.
  32. """
  33. if value is not None and len(value) > 0:
  34. # A tuple is used for RFC 2231 encoded parameter values where items
  35. # are (charset, language, value). charset is a string, not a Charset
  36. # instance.
  37. if isinstance(value, tuple):
  38. # Encode as per RFC 2231
  39. param += '*'
  40. value = utils.encode_rfc2231(value[2], value[0], value[1])
  41. # BAW: Please check this. I think that if quote is set it should
  42. # force quoting even if not necessary.
  43. if quote or tspecials.search(value):
  44. return '%s="%s"' % (param, utils.quote(value))
  45. else:
  46. return '%s=%s' % (param, value)
  47. else:
  48. return param
  49. def _parseparam(s):
  50. plist = []
  51. while s[:1] == ';':
  52. s = s[1:]
  53. end = s.find(';')
  54. while end > 0 and s.count('"', 0, end) % 2:
  55. end = s.find(';', end + 1)
  56. if end < 0:
  57. end = len(s)
  58. f = s[:end]
  59. if '=' in f:
  60. i = f.index('=')
  61. f = f[:i].strip().lower() + '=' + f[i+1:].strip()
  62. plist.append(f.strip())
  63. s = s[end:]
  64. return plist
  65. def _unquotevalue(value):
  66. # This is different than utils.collapse_rfc2231_value() because it doesn't
  67. # try to convert the value to a unicode. Message.get_param() and
  68. # Message.get_params() are both currently defined to return the tuple in
  69. # the face of RFC 2231 parameters.
  70. if isinstance(value, tuple):
  71. return value[0], value[1], utils.unquote(value[2])
  72. else:
  73. return utils.unquote(value)
  74. class Message:
  75. """Basic message object.
  76. A message object is defined as something that has a bunch of RFC 2822
  77. headers and a payload. It may optionally have an envelope header
  78. (a.k.a. Unix-From or From_ header). If the message is a container (i.e. a
  79. multipart or a message/rfc822), then the payload is a list of Message
  80. objects, otherwise it is a string.
  81. Message objects implement part of the `mapping' interface, which assumes
  82. there is exactly one occurrance of the header per message. Some headers
  83. do in fact appear multiple times (e.g. Received) and for those headers,
  84. you must use the explicit API to set or get all the headers. Not all of
  85. the mapping methods are implemented.
  86. """
  87. def __init__(self):
  88. self._headers = []
  89. self._unixfrom = None
  90. self._payload = None
  91. self._charset = None
  92. # Defaults for multipart messages
  93. self.preamble = self.epilogue = None
  94. self.defects = []
  95. # Default content type
  96. self._default_type = 'text/plain'
  97. def __str__(self):
  98. """Return the entire formatted message as a string.
  99. This includes the headers, body, and envelope header.
  100. """
  101. return self.as_string(unixfrom=True)
  102. def as_string(self, unixfrom=False):
  103. """Return the entire formatted message as a string.
  104. Optional `unixfrom' when True, means include the Unix From_ envelope
  105. header.
  106. This is a convenience method and may not generate the message exactly
  107. as you intend because by default it mangles lines that begin with
  108. "From ". For more flexibility, use the flatten() method of a
  109. Generator instance.
  110. """
  111. from email.generator import Generator
  112. fp = StringIO()
  113. g = Generator(fp)
  114. g.flatten(self, unixfrom=unixfrom)
  115. return fp.getvalue()
  116. def is_multipart(self):
  117. """Return True if the message consists of multiple parts."""
  118. return isinstance(self._payload, list)
  119. #
  120. # Unix From_ line
  121. #
  122. def set_unixfrom(self, unixfrom):
  123. self._unixfrom = unixfrom
  124. def get_unixfrom(self):
  125. return self._unixfrom
  126. #
  127. # Payload manipulation.
  128. #
  129. def attach(self, payload):
  130. """Add the given payload to the current payload.
  131. The current payload will always be a list of objects after this method
  132. is called. If you want to set the payload to a scalar object, use
  133. set_payload() instead.
  134. """
  135. if self._payload is None:
  136. self._payload = [payload]
  137. else:
  138. self._payload.append(payload)
  139. def get_payload(self, i=None, decode=False):
  140. """Return a reference to the payload.
  141. The payload will either be a list object or a string. If you mutate
  142. the list object, you modify the message's payload in place. Optional
  143. i returns that index into the payload.
  144. Optional decode is a flag indicating whether the payload should be
  145. decoded or not, according to the Content-Transfer-Encoding header
  146. (default is False).
  147. When True and the message is not a multipart, the payload will be
  148. decoded if this header's value is `quoted-printable' or `base64'. If
  149. some other encoding is used, or the header is missing, or if the
  150. payload has bogus data (i.e. bogus base64 or uuencoded data), the
  151. payload is returned as-is.
  152. If the message is a multipart and the decode flag is True, then None
  153. is returned.
  154. """
  155. if i is None:
  156. payload = self._payload
  157. elif not isinstance(self._payload, list):
  158. raise TypeError('Expected list, got %s' % type(self._payload))
  159. else:
  160. payload = self._payload[i]
  161. if decode:
  162. if self.is_multipart():
  163. return None
  164. cte = self.get('content-transfer-encoding', '').lower()
  165. if cte == 'quoted-printable':
  166. return utils._qdecode(payload)
  167. elif cte == 'base64':
  168. try:
  169. return utils._bdecode(payload)
  170. except binascii.Error:
  171. # Incorrect padding
  172. return payload
  173. elif cte in ('x-uuencode', 'uuencode', 'uue', 'x-uue'):
  174. sfp = StringIO()
  175. try:
  176. uu.decode(StringIO(payload+'\n'), sfp, quiet=True)
  177. payload = sfp.getvalue()
  178. except uu.Error:
  179. # Some decoding problem
  180. return payload
  181. # Everything else, including encodings with 8bit or 7bit are returned
  182. # unchanged.
  183. return payload
  184. def set_payload(self, payload, charset=None):
  185. """Set the payload to the given value.
  186. Optional charset sets the message's default character set. See
  187. set_charset() for details.
  188. """
  189. self._payload = payload
  190. if charset is not None:
  191. self.set_charset(charset)
  192. def set_charset(self, charset):
  193. """Set the charset of the payload to a given character set.
  194. charset can be a Charset instance, a string naming a character set, or
  195. None. If it is a string it will be converted to a Charset instance.
  196. If charset is None, the charset parameter will be removed from the
  197. Content-Type field. Anything else will generate a TypeError.
  198. The message will be assumed to be of type text/* encoded with
  199. charset.input_charset. It will be converted to charset.output_charset
  200. and encoded properly, if needed, when generating the plain text
  201. representation of the message. MIME headers (MIME-Version,
  202. Content-Type, Content-Transfer-Encoding) will be added as needed.
  203. """
  204. if charset is None:
  205. self.del_param('charset')
  206. self._charset = None
  207. return
  208. if isinstance(charset, basestring):
  209. charset = email.charset.Charset(charset)
  210. if not isinstance(charset, email.charset.Charset):
  211. raise TypeError(charset)
  212. # BAW: should we accept strings that can serve as arguments to the
  213. # Charset constructor?
  214. self._charset = charset
  215. if not self.has_key('MIME-Version'):
  216. self.add_header('MIME-Version', '1.0')
  217. if not self.has_key('Content-Type'):
  218. self.add_header('Content-Type', 'text/plain',
  219. charset=charset.get_output_charset())
  220. else:
  221. self.set_param('charset', charset.get_output_charset())
  222. if str(charset) != charset.get_output_charset():
  223. self._payload = charset.body_encode(self._payload)
  224. if not self.has_key('Content-Transfer-Encoding'):
  225. cte = charset.get_body_encoding()
  226. try:
  227. cte(self)
  228. except TypeError:
  229. self._payload = charset.body_encode(self._payload)
  230. self.add_header('Content-Transfer-Encoding', cte)
  231. def get_charset(self):
  232. """Return the Charset instance associated with the message's payload.
  233. """
  234. return self._charset
  235. #
  236. # MAPPING INTERFACE (partial)
  237. #
  238. def __len__(self):
  239. """Return the total number of headers, including duplicates."""
  240. return len(self._headers)
  241. def __getitem__(self, name):
  242. """Get a header value.
  243. Return None if the header is missing instead of raising an exception.
  244. Note that if the header appeared multiple times, exactly which
  245. occurrance gets returned is undefined. Use get_all() to get all
  246. the values matching a header field name.
  247. """
  248. return self.get(name)
  249. def __setitem__(self, name, val):
  250. """Set the value of a header.
  251. Note: this does not overwrite an existing header with the same field
  252. name. Use __delitem__() first to delete any existing headers.
  253. """
  254. self._headers.append((name, val))
  255. def __delitem__(self, name):
  256. """Delete all occurrences of a header, if present.
  257. Does not raise an exception if the header is missing.
  258. """
  259. name = name.lower()
  260. newheaders = []
  261. for k, v in self._headers:
  262. if k.lower() != name:
  263. newheaders.append((k, v))
  264. self._headers = newheaders
  265. def __contains__(self, name):
  266. return name.lower() in [k.lower() for k, v in self._headers]
  267. def has_key(self, name):
  268. """Return true if the message contains the header."""
  269. missing = object()
  270. return self.get(name, missing) is not missing
  271. def keys(self):
  272. """Return a list of all the message's header field names.
  273. These will be sorted in the order they appeared in the original
  274. message, or were added to the message, and may contain duplicates.
  275. Any fields deleted and re-inserted are always appended to the header
  276. list.
  277. """
  278. return [k for k, v in self._headers]
  279. def values(self):
  280. """Return a list of all the message's header values.
  281. These will be sorted in the order they appeared in the original
  282. message, or were added to the message, and may contain duplicates.
  283. Any fields deleted and re-inserted are always appended to the header
  284. list.
  285. """
  286. return [v for k, v in self._headers]
  287. def items(self):
  288. """Get all the message's header fields and values.
  289. These will be sorted in the order they appeared in the original
  290. message, or were added to the message, and may contain duplicates.
  291. Any fields deleted and re-inserted are always appended to the header
  292. list.
  293. """
  294. return self._headers[:]
  295. def get(self, name, failobj=None):
  296. """Get a header value.
  297. Like __getitem__() but return failobj instead of None when the field
  298. is missing.
  299. """
  300. name = name.lower()
  301. for k, v in self._headers:
  302. if k.lower() == name:
  303. return v
  304. return failobj
  305. #
  306. # Additional useful stuff
  307. #
  308. def get_all(self, name, failobj=None):
  309. """Return a list of all the values for the named field.
  310. These will be sorted in the order they appeared in the original
  311. message, and may contain duplicates. Any fields deleted and
  312. re-inserted are always appended to the header list.
  313. If no such fields exist, failobj is returned (defaults to None).
  314. """
  315. values = []
  316. name = name.lower()
  317. for k, v in self._headers:
  318. if k.lower() == name:
  319. values.append(v)
  320. if not values:
  321. return failobj
  322. return values
  323. def add_header(self, _name, _value, **_params):
  324. """Extended header setting.
  325. name is the header field to add. keyword arguments can be used to set
  326. additional parameters for the header field, with underscores converted
  327. to dashes. Normally the parameter will be added as key="value" unless
  328. value is None, in which case only the key will be added.
  329. Example:
  330. msg.add_header('content-disposition', 'attachment', filename='bud.gif')
  331. """
  332. parts = []
  333. for k, v in _params.items():
  334. if v is None:
  335. parts.append(k.replace('_', '-'))
  336. else:
  337. parts.append(_formatparam(k.replace('_', '-'), v))
  338. if _value is not None:
  339. parts.insert(0, _value)
  340. self._headers.append((_name, SEMISPACE.join(parts)))
  341. def replace_header(self, _name, _value):
  342. """Replace a header.
  343. Replace the first matching header found in the message, retaining
  344. header order and case. If no matching header was found, a KeyError is
  345. raised.
  346. """
  347. _name = _name.lower()
  348. for i, (k, v) in zip(range(len(self._headers)), self._headers):
  349. if k.lower() == _name:
  350. self._headers[i] = (k, _value)
  351. break
  352. else:
  353. raise KeyError(_name)
  354. #
  355. # Use these three methods instead of the three above.
  356. #
  357. def get_content_type(self):
  358. """Return the message's content type.
  359. The returned string is coerced to lower case of the form
  360. `maintype/subtype'. If there was no Content-Type header in the
  361. message, the default type as given by get_default_type() will be
  362. returned. Since according to RFC 2045, messages always have a default
  363. type this will always return a value.
  364. RFC 2045 defines a message's default type to be text/plain unless it
  365. appears inside a multipart/digest container, in which case it would be
  366. message/rfc822.
  367. """
  368. missing = object()
  369. value = self.get('content-type', missing)
  370. if value is missing:
  371. # This should have no parameters
  372. return self.get_default_type()
  373. ctype = _splitparam(value)[0].lower()
  374. # RFC 2045, section 5.2 says if its invalid, use text/plain
  375. if ctype.count('/') != 1:
  376. return 'text/plain'
  377. return ctype
  378. def get_content_maintype(self):
  379. """Return the message's main content type.
  380. This is the `maintype' part of the string returned by
  381. get_content_type().
  382. """
  383. ctype = self.get_content_type()
  384. return ctype.split('/')[0]
  385. def get_content_subtype(self):
  386. """Returns the message's sub-content type.
  387. This is the `subtype' part of the string returned by
  388. get_content_type().
  389. """
  390. ctype = self.get_content_type()
  391. return ctype.split('/')[1]
  392. def get_default_type(self):
  393. """Return the `default' content type.
  394. Most messages have a default content type of text/plain, except for
  395. messages that are subparts of multipart/digest containers. Such
  396. subparts have a default content type of message/rfc822.
  397. """
  398. return self._default_type
  399. def set_default_type(self, ctype):
  400. """Set the `default' content type.
  401. ctype should be either "text/plain" or "message/rfc822", although this
  402. is not enforced. The default content type is not stored in the
  403. Content-Type header.
  404. """
  405. self._default_type = ctype
  406. def _get_params_preserve(self, failobj, header):
  407. # Like get_params() but preserves the quoting of values. BAW:
  408. # should this be part of the public interface?
  409. missing = object()
  410. value = self.get(header, missing)
  411. if value is missing:
  412. return failobj
  413. params = []
  414. for p in _parseparam(';' + value):
  415. try:
  416. name, val = p.split('=', 1)
  417. name = name.strip()
  418. val = val.strip()
  419. except ValueError:
  420. # Must have been a bare attribute
  421. name = p.strip()
  422. val = ''
  423. params.append((name, val))
  424. params = utils.decode_params(params)
  425. return params
  426. def get_params(self, failobj=None, header='content-type', unquote=True):
  427. """Return the message's Content-Type parameters, as a list.
  428. The elements of the returned list are 2-tuples of key/value pairs, as
  429. split on the `=' sign. The left hand side of the `=' is the key,
  430. while the right hand side is the value. If there is no `=' sign in
  431. the parameter the value is the empty string. The value is as
  432. described in the get_param() method.
  433. Optional failobj is the object to return if there is no Content-Type
  434. header. Optional header is the header to search instead of
  435. Content-Type. If unquote is True, the value is unquoted.
  436. """
  437. missing = object()
  438. params = self._get_params_preserve(missing, header)
  439. if params is missing:
  440. return failobj
  441. if unquote:
  442. return [(k, _unquotevalue(v)) for k, v in params]
  443. else:
  444. return params
  445. def get_param(self, param, failobj=None, header='content-type',
  446. unquote=True):
  447. """Return the parameter value if found in the Content-Type header.
  448. Optional failobj is the object to return if there is no Content-Type
  449. header, or the Content-Type header has no such parameter. Optional
  450. header is the header to search instead of Content-Type.
  451. Parameter keys are always compared case insensitively. The return
  452. value can either be a string, or a 3-tuple if the parameter was RFC
  453. 2231 encoded. When it's a 3-tuple, the elements of the value are of
  454. the form (CHARSET, LANGUAGE, VALUE). Note that both CHARSET and
  455. LANGUAGE can be None, in which case you should consider VALUE to be
  456. encoded in the us-ascii charset. You can usually ignore LANGUAGE.
  457. Your application should be prepared to deal with 3-tuple return
  458. values, and can convert the parameter to a Unicode string like so:
  459. param = msg.get_param('foo')
  460. if isinstance(param, tuple):
  461. param = unicode(param[2], param[0] or 'us-ascii')
  462. In any case, the parameter value (either the returned string, or the
  463. VALUE item in the 3-tuple) is always unquoted, unless unquote is set
  464. to False.
  465. """
  466. if not self.has_key(header):
  467. return failobj
  468. for k, v in self._get_params_preserve(failobj, header):
  469. if k.lower() == param.lower():
  470. if unquote:
  471. return _unquotevalue(v)
  472. else:
  473. return v
  474. return failobj
  475. def set_param(self, param, value, header='Content-Type', requote=True,
  476. charset=None, language=''):
  477. """Set a parameter in the Content-Type header.
  478. If the parameter already exists in the header, its value will be
  479. replaced with the new value.
  480. If header is Content-Type and has not yet been defined for this
  481. message, it will be set to "text/plain" and the new parameter and
  482. value will be appended as per RFC 2045.
  483. An alternate header can specified in the header argument, and all
  484. parameters will be quoted as necessary unless requote is False.
  485. If charset is specified, the parameter will be encoded according to RFC
  486. 2231. Optional language specifies the RFC 2231 language, defaulting
  487. to the empty string. Both charset and language should be strings.
  488. """
  489. if not isinstance(value, tuple) and charset:
  490. value = (charset, language, value)
  491. if not self.has_key(header) and header.lower() == 'content-type':
  492. ctype = 'text/plain'
  493. else:
  494. ctype = self.get(header)
  495. if not self.get_param(param, header=header):
  496. if not ctype:
  497. ctype = _formatparam(param, value, requote)
  498. else:
  499. ctype = SEMISPACE.join(
  500. [ctype, _formatparam(param, value, requote)])
  501. else:
  502. ctype = ''
  503. for old_param, old_value in self.get_params(header=header,
  504. unquote=requote):
  505. append_param = ''
  506. if old_param.lower() == param.lower():
  507. append_param = _formatparam(param, value, requote)
  508. else:
  509. append_param = _formatparam(old_param, old_value, requote)
  510. if not ctype:
  511. ctype = append_param
  512. else:
  513. ctype = SEMISPACE.join([ctype, append_param])
  514. if ctype != self.get(header):
  515. del self[header]
  516. self[header] = ctype
  517. def del_param(self, param, header='content-type', requote=True):
  518. """Remove the given parameter completely from the Content-Type header.
  519. The header will be re-written in place without the parameter or its
  520. value. All values will be quoted as necessary unless requote is
  521. False. Optional header specifies an alternative to the Content-Type
  522. header.
  523. """
  524. if not self.has_key(header):
  525. return
  526. new_ctype = ''
  527. for p, v in self.get_params(header=header, unquote=requote):
  528. if p.lower() != param.lower():
  529. if not new_ctype:
  530. new_ctype = _formatparam(p, v, requote)
  531. else:
  532. new_ctype = SEMISPACE.join([new_ctype,
  533. _formatparam(p, v, requote)])
  534. if new_ctype != self.get(header):
  535. del self[header]
  536. self[header] = new_ctype
  537. def set_type(self, type, header='Content-Type', requote=True):
  538. """Set the main type and subtype for the Content-Type header.
  539. type must be a string in the form "maintype/subtype", otherwise a
  540. ValueError is raised.
  541. This method replaces the Content-Type header, keeping all the
  542. parameters in place. If requote is False, this leaves the existing
  543. header's quoting as is. Otherwise, the parameters will be quoted (the
  544. default).
  545. An alternative header can be specified in the header argument. When
  546. the Content-Type header is set, we'll always also add a MIME-Version
  547. header.
  548. """
  549. # BAW: should we be strict?
  550. if not type.count('/') == 1:
  551. raise ValueError
  552. # Set the Content-Type, you get a MIME-Version
  553. if header.lower() == 'content-type':
  554. del self['mime-version']
  555. self['MIME-Version'] = '1.0'
  556. if not self.has_key(header):
  557. self[header] = type
  558. return
  559. params = self.get_params(header=header, unquote=requote)
  560. del self[header]
  561. self[header] = type
  562. # Skip the first param; it's the old type.
  563. for p, v in params[1:]:
  564. self.set_param(p, v, header, requote)
  565. def get_filename(self, failobj=None):
  566. """Return the filename associated with the payload if present.
  567. The filename is extracted from the Content-Disposition header's
  568. `filename' parameter, and it is unquoted. If that header is missing
  569. the `filename' parameter, this method falls back to looking for the
  570. `name' parameter.
  571. """
  572. missing = object()
  573. filename = self.get_param('filename', missing, 'content-disposition')
  574. if filename is missing:
  575. filename = self.get_param('name', missing, 'content-disposition')
  576. if filename is missing:
  577. return failobj
  578. return utils.collapse_rfc2231_value(filename).strip()
  579. def get_boundary(self, failobj=None):
  580. """Return the boundary associated with the payload if present.
  581. The boundary is extracted from the Content-Type header's `boundary'
  582. parameter, and it is unquoted.
  583. """
  584. missing = object()
  585. boundary = self.get_param('boundary', missing)
  586. if boundary is missing:
  587. return failobj
  588. # RFC 2046 says that boundaries may begin but not end in w/s
  589. return utils.collapse_rfc2231_value(boundary).rstrip()
  590. def set_boundary(self, boundary):
  591. """Set the boundary parameter in Content-Type to 'boundary'.
  592. This is subtly different than deleting the Content-Type header and
  593. adding a new one with a new boundary parameter via add_header(). The
  594. main difference is that using the set_boundary() method preserves the
  595. order of the Content-Type header in the original message.
  596. HeaderParseError is raised if the message has no Content-Type header.
  597. """
  598. missing = object()
  599. params = self._get_params_preserve(missing, 'content-type')
  600. if params is missing:
  601. # There was no Content-Type header, and we don't know what type
  602. # to set it to, so raise an exception.
  603. raise errors.HeaderParseError('No Content-Type header found')
  604. newparams = []
  605. foundp = False
  606. for pk, pv in params:
  607. if pk.lower() == 'boundary':
  608. newparams.append(('boundary', '"%s"' % boundary))
  609. foundp = True
  610. else:
  611. newparams.append((pk, pv))
  612. if not foundp:
  613. # The original Content-Type header had no boundary attribute.
  614. # Tack one on the end. BAW: should we raise an exception
  615. # instead???
  616. newparams.append(('boundary', '"%s"' % boundary))
  617. # Replace the existing Content-Type header with the new value
  618. newheaders = []
  619. for h, v in self._headers:
  620. if h.lower() == 'content-type':
  621. parts = []
  622. for k, v in newparams:
  623. if v == '':
  624. parts.append(k)
  625. else:
  626. parts.append('%s=%s' % (k, v))
  627. newheaders.append((h, SEMISPACE.join(parts)))
  628. else:
  629. newheaders.append((h, v))
  630. self._headers = newheaders
  631. def get_content_charset(self, failobj=None):
  632. """Return the charset parameter of the Content-Type header.
  633. The returned string is always coerced to lower case. If there is no
  634. Content-Type header, or if that header has no charset parameter,
  635. failobj is returned.
  636. """
  637. missing = object()
  638. charset = self.get_param('charset', missing)
  639. if charset is missing:
  640. return failobj
  641. if isinstance(charset, tuple):
  642. # RFC 2231 encoded, so decode it, and it better end up as ascii.
  643. pcharset = charset[0] or 'us-ascii'
  644. try:
  645. # LookupError will be raised if the charset isn't known to
  646. # Python. UnicodeError will be raised if the encoded text
  647. # contains a character not in the charset.
  648. charset = unicode(charset[2], pcharset).encode('us-ascii')
  649. except (LookupError, UnicodeError):
  650. charset = charset[2]
  651. # charset character must be in us-ascii range
  652. try:
  653. if isinstance(charset, str):
  654. charset = unicode(charset, 'us-ascii')
  655. charset = charset.encode('us-ascii')
  656. except UnicodeError:
  657. return failobj
  658. # RFC 2046, $4.1.2 says charsets are not case sensitive
  659. return charset.lower()
  660. def get_charsets(self, failobj=None):
  661. """Return a list containing the charset(s) used in this message.
  662. The returned list of items describes the Content-Type headers'
  663. charset parameter for this message and all the subparts in its
  664. payload.
  665. Each item will either be a string (the value of the charset parameter
  666. in the Content-Type header of that part) or the value of the
  667. 'failobj' parameter (defaults to None), if the part does not have a
  668. main MIME type of "text", or the charset is not defined.
  669. The list will contain one string for each part of the message, plus
  670. one for the container message (i.e. self), so that a non-multipart
  671. message will still return a list of length 1.
  672. """
  673. return [part.get_content_charset(failobj) for part in self.walk()]
  674. # I.e. def walk(self): ...
  675. from email.iterators import walk