PageRenderTime 58ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/External.LCA_RESTRICTED/Languages/CPython/27/Lib/email/message.py

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