message.py 34 KB

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