PageRenderTime 45ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 1ms

/python/lib/Lib/email/Message.py

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