message.py 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204
  1. # Copyright (C) 2001-2007 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', 'EmailMessage']
  6. import binascii
  7. import re
  8. import quopri
  9. from io import BytesIO, StringIO
  10. # Intrapackage imports
  11. from email import utils
  12. from email import errors
  13. from email._policybase import compat32
  14. from email import charset as _charset
  15. from email._encoded_words import decode_b
  16. Charset = _charset.Charset
  17. SEMISPACE = '; '
  18. # Regular expression that matches `special' characters in parameters, the
  19. # existence of which force quoting of the parameter value.
  20. tspecials = re.compile(r'[ \(\)<>@,;:\\"/\[\]\?=]')
  21. def _splitparam(param):
  22. # Split header parameters. BAW: this may be too simple. It isn't
  23. # strictly RFC 2045 (section 5.1) compliant, but it catches most headers
  24. # found in the wild. We may eventually need a full fledged parser.
  25. # RDM: we might have a Header here; for now just stringify it.
  26. a, sep, b = str(param).partition(';')
  27. if not sep:
  28. return a.strip(), None
  29. return a.strip(), b.strip()
  30. def _formatparam(param, value=None, quote=True):
  31. """Convenience function to format and return a key=value pair.
  32. This will quote the value if needed or if quote is true. If value is a
  33. three tuple (charset, language, value), it will be encoded according
  34. to RFC2231 rules. If it contains non-ascii characters it will likewise
  35. be encoded according to RFC2231 rules, using the utf-8 charset and
  36. a null language.
  37. """
  38. if value is not None and len(value) > 0:
  39. # A tuple is used for RFC 2231 encoded parameter values where items
  40. # are (charset, language, value). charset is a string, not a Charset
  41. # instance. RFC 2231 encoded values are never quoted, per RFC.
  42. if isinstance(value, tuple):
  43. # Encode as per RFC 2231
  44. param += '*'
  45. value = utils.encode_rfc2231(value[2], value[0], value[1])
  46. return '%s=%s' % (param, value)
  47. else:
  48. try:
  49. value.encode('ascii')
  50. except UnicodeEncodeError:
  51. param += '*'
  52. value = utils.encode_rfc2231(value, 'utf-8', '')
  53. return '%s=%s' % (param, value)
  54. # BAW: Please check this. I think that if quote is set it should
  55. # force quoting even if not necessary.
  56. if quote or tspecials.search(value):
  57. return '%s="%s"' % (param, utils.quote(value))
  58. else:
  59. return '%s=%s' % (param, value)
  60. else:
  61. return param
  62. def _parseparam(s):
  63. # RDM This might be a Header, so for now stringify it.
  64. s = ';' + str(s)
  65. plist = []
  66. while s[:1] == ';':
  67. s = s[1:]
  68. end = s.find(';')
  69. while end > 0 and (s.count('"', 0, end) - s.count('\\"', 0, end)) % 2:
  70. end = s.find(';', end + 1)
  71. if end < 0:
  72. end = len(s)
  73. f = s[:end]
  74. if '=' in f:
  75. i = f.index('=')
  76. f = f[:i].strip().lower() + '=' + f[i+1:].strip()
  77. plist.append(f.strip())
  78. s = s[end:]
  79. return plist
  80. def _unquotevalue(value):
  81. # This is different than utils.collapse_rfc2231_value() because it doesn't
  82. # try to convert the value to a unicode. Message.get_param() and
  83. # Message.get_params() are both currently defined to return the tuple in
  84. # the face of RFC 2231 parameters.
  85. if isinstance(value, tuple):
  86. return value[0], value[1], utils.unquote(value[2])
  87. else:
  88. return utils.unquote(value)
  89. def _decode_uu(encoded):
  90. """Decode uuencoded data."""
  91. decoded_lines = []
  92. encoded_lines_iter = iter(encoded.splitlines())
  93. for line in encoded_lines_iter:
  94. if line.startswith(b"begin "):
  95. mode, _, path = line.removeprefix(b"begin ").partition(b" ")
  96. try:
  97. int(mode, base=8)
  98. except ValueError:
  99. continue
  100. else:
  101. break
  102. else:
  103. raise ValueError("`begin` line not found")
  104. for line in encoded_lines_iter:
  105. if not line:
  106. raise ValueError("Truncated input")
  107. elif line.strip(b' \t\r\n\f') == b'end':
  108. break
  109. try:
  110. decoded_line = binascii.a2b_uu(line)
  111. except binascii.Error:
  112. # Workaround for broken uuencoders by /Fredrik Lundh
  113. nbytes = (((line[0]-32) & 63) * 4 + 5) // 3
  114. decoded_line = binascii.a2b_uu(line[:nbytes])
  115. decoded_lines.append(decoded_line)
  116. return b''.join(decoded_lines)
  117. class Message:
  118. """Basic message object.
  119. A message object is defined as something that has a bunch of RFC 2822
  120. headers and a payload. It may optionally have an envelope header
  121. (a.k.a. Unix-From or From_ header). If the message is a container (i.e. a
  122. multipart or a message/rfc822), then the payload is a list of Message
  123. objects, otherwise it is a string.
  124. Message objects implement part of the `mapping' interface, which assumes
  125. there is exactly one occurrence of the header per message. Some headers
  126. do in fact appear multiple times (e.g. Received) and for those headers,
  127. you must use the explicit API to set or get all the headers. Not all of
  128. the mapping methods are implemented.
  129. """
  130. def __init__(self, policy=compat32):
  131. self.policy = policy
  132. self._headers = []
  133. self._unixfrom = None
  134. self._payload = None
  135. self._charset = None
  136. # Defaults for multipart messages
  137. self.preamble = self.epilogue = None
  138. self.defects = []
  139. # Default content type
  140. self._default_type = 'text/plain'
  141. def __str__(self):
  142. """Return the entire formatted message as a string.
  143. """
  144. return self.as_string()
  145. def as_string(self, unixfrom=False, maxheaderlen=0, policy=None):
  146. """Return the entire formatted message as a string.
  147. Optional 'unixfrom', when true, means include the Unix From_ envelope
  148. header. For backward compatibility reasons, if maxheaderlen is
  149. not specified it defaults to 0, so you must override it explicitly
  150. if you want a different maxheaderlen. 'policy' is passed to the
  151. Generator instance used to serialize the message; if it is not
  152. specified the policy associated with the message instance is used.
  153. If the message object contains binary data that is not encoded
  154. according to RFC standards, the non-compliant data will be replaced by
  155. unicode "unknown character" code points.
  156. """
  157. from email.generator import Generator
  158. policy = self.policy if policy is None else policy
  159. fp = StringIO()
  160. g = Generator(fp,
  161. mangle_from_=False,
  162. maxheaderlen=maxheaderlen,
  163. policy=policy)
  164. g.flatten(self, unixfrom=unixfrom)
  165. return fp.getvalue()
  166. def __bytes__(self):
  167. """Return the entire formatted message as a bytes object.
  168. """
  169. return self.as_bytes()
  170. def as_bytes(self, unixfrom=False, policy=None):
  171. """Return the entire formatted message as a bytes object.
  172. Optional 'unixfrom', when true, means include the Unix From_ envelope
  173. header. 'policy' is passed to the BytesGenerator instance used to
  174. serialize the message; if not specified the policy associated with
  175. the message instance is used.
  176. """
  177. from email.generator import BytesGenerator
  178. policy = self.policy if policy is None else policy
  179. fp = BytesIO()
  180. g = BytesGenerator(fp, mangle_from_=False, policy=policy)
  181. g.flatten(self, unixfrom=unixfrom)
  182. return fp.getvalue()
  183. def is_multipart(self):
  184. """Return True if the message consists of multiple parts."""
  185. return isinstance(self._payload, list)
  186. #
  187. # Unix From_ line
  188. #
  189. def set_unixfrom(self, unixfrom):
  190. self._unixfrom = unixfrom
  191. def get_unixfrom(self):
  192. return self._unixfrom
  193. #
  194. # Payload manipulation.
  195. #
  196. def attach(self, payload):
  197. """Add the given payload to the current payload.
  198. The current payload will always be a list of objects after this method
  199. is called. If you want to set the payload to a scalar object, use
  200. set_payload() instead.
  201. """
  202. if self._payload is None:
  203. self._payload = [payload]
  204. else:
  205. try:
  206. self._payload.append(payload)
  207. except AttributeError:
  208. raise TypeError("Attach is not valid on a message with a"
  209. " non-multipart payload")
  210. def get_payload(self, i=None, decode=False):
  211. """Return a reference to the payload.
  212. The payload will either be a list object or a string. If you mutate
  213. the list object, you modify the message's payload in place. Optional
  214. i returns that index into the payload.
  215. Optional decode is a flag indicating whether the payload should be
  216. decoded or not, according to the Content-Transfer-Encoding header
  217. (default is False).
  218. When True and the message is not a multipart, the payload will be
  219. decoded if this header's value is `quoted-printable' or `base64'. If
  220. some other encoding is used, or the header is missing, or if the
  221. payload has bogus data (i.e. bogus base64 or uuencoded data), the
  222. payload is returned as-is.
  223. If the message is a multipart and the decode flag is True, then None
  224. is returned.
  225. """
  226. # Here is the logic table for this code, based on the email5.0.0 code:
  227. # i decode is_multipart result
  228. # ------ ------ ------------ ------------------------------
  229. # None True True None
  230. # i True True None
  231. # None False True _payload (a list)
  232. # i False True _payload element i (a Message)
  233. # i False False error (not a list)
  234. # i True False error (not a list)
  235. # None False False _payload
  236. # None True False _payload decoded (bytes)
  237. # Note that Barry planned to factor out the 'decode' case, but that
  238. # isn't so easy now that we handle the 8 bit data, which needs to be
  239. # converted in both the decode and non-decode path.
  240. if self.is_multipart():
  241. if decode:
  242. return None
  243. if i is None:
  244. return self._payload
  245. else:
  246. return self._payload[i]
  247. # For backward compatibility, Use isinstance and this error message
  248. # instead of the more logical is_multipart test.
  249. if i is not None and not isinstance(self._payload, list):
  250. raise TypeError('Expected list, got %s' % type(self._payload))
  251. payload = self._payload
  252. # cte might be a Header, so for now stringify it.
  253. cte = str(self.get('content-transfer-encoding', '')).lower()
  254. # payload may be bytes here.
  255. if isinstance(payload, str):
  256. if utils._has_surrogates(payload):
  257. bpayload = payload.encode('ascii', 'surrogateescape')
  258. if not decode:
  259. try:
  260. payload = bpayload.decode(self.get_param('charset', 'ascii'), 'replace')
  261. except LookupError:
  262. payload = bpayload.decode('ascii', 'replace')
  263. elif decode:
  264. try:
  265. bpayload = payload.encode('ascii')
  266. except UnicodeError:
  267. # This won't happen for RFC compliant messages (messages
  268. # containing only ASCII code points in the unicode input).
  269. # If it does happen, turn the string into bytes in a way
  270. # guaranteed not to fail.
  271. bpayload = payload.encode('raw-unicode-escape')
  272. if not decode:
  273. return payload
  274. if cte == 'quoted-printable':
  275. return quopri.decodestring(bpayload)
  276. elif cte == 'base64':
  277. # XXX: this is a bit of a hack; decode_b should probably be factored
  278. # out somewhere, but I haven't figured out where yet.
  279. value, defects = decode_b(b''.join(bpayload.splitlines()))
  280. for defect in defects:
  281. self.policy.handle_defect(self, defect)
  282. return value
  283. elif cte in ('x-uuencode', 'uuencode', 'uue', 'x-uue'):
  284. try:
  285. return _decode_uu(bpayload)
  286. except ValueError:
  287. # Some decoding problem.
  288. return bpayload
  289. if isinstance(payload, str):
  290. return bpayload
  291. return payload
  292. def set_payload(self, payload, charset=None):
  293. """Set the payload to the given value.
  294. Optional charset sets the message's default character set. See
  295. set_charset() for details.
  296. """
  297. if hasattr(payload, 'encode'):
  298. if charset is None:
  299. self._payload = payload
  300. return
  301. if not isinstance(charset, Charset):
  302. charset = Charset(charset)
  303. payload = payload.encode(charset.output_charset)
  304. if hasattr(payload, 'decode'):
  305. self._payload = payload.decode('ascii', 'surrogateescape')
  306. else:
  307. self._payload = payload
  308. if charset is not None:
  309. self.set_charset(charset)
  310. def set_charset(self, charset):
  311. """Set the charset of the payload to a given character set.
  312. charset can be a Charset instance, a string naming a character set, or
  313. None. If it is a string it will be converted to a Charset instance.
  314. If charset is None, the charset parameter will be removed from the
  315. Content-Type field. Anything else will generate a TypeError.
  316. The message will be assumed to be of type text/* encoded with
  317. charset.input_charset. It will be converted to charset.output_charset
  318. and encoded properly, if needed, when generating the plain text
  319. representation of the message. MIME headers (MIME-Version,
  320. Content-Type, Content-Transfer-Encoding) will be added as needed.
  321. """
  322. if charset is None:
  323. self.del_param('charset')
  324. self._charset = None
  325. return
  326. if not isinstance(charset, Charset):
  327. charset = Charset(charset)
  328. self._charset = charset
  329. if 'MIME-Version' not in self:
  330. self.add_header('MIME-Version', '1.0')
  331. if 'Content-Type' not in self:
  332. self.add_header('Content-Type', 'text/plain',
  333. charset=charset.get_output_charset())
  334. else:
  335. self.set_param('charset', charset.get_output_charset())
  336. if charset != charset.get_output_charset():
  337. self._payload = charset.body_encode(self._payload)
  338. if 'Content-Transfer-Encoding' not in self:
  339. cte = charset.get_body_encoding()
  340. try:
  341. cte(self)
  342. except TypeError:
  343. # This 'if' is for backward compatibility, it allows unicode
  344. # through even though that won't work correctly if the
  345. # message is serialized.
  346. payload = self._payload
  347. if payload:
  348. try:
  349. payload = payload.encode('ascii', 'surrogateescape')
  350. except UnicodeError:
  351. payload = payload.encode(charset.output_charset)
  352. self._payload = charset.body_encode(payload)
  353. self.add_header('Content-Transfer-Encoding', cte)
  354. def get_charset(self):
  355. """Return the Charset instance associated with the message's payload.
  356. """
  357. return self._charset
  358. #
  359. # MAPPING INTERFACE (partial)
  360. #
  361. def __len__(self):
  362. """Return the total number of headers, including duplicates."""
  363. return len(self._headers)
  364. def __getitem__(self, name):
  365. """Get a header value.
  366. Return None if the header is missing instead of raising an exception.
  367. Note that if the header appeared multiple times, exactly which
  368. occurrence gets returned is undefined. Use get_all() to get all
  369. the values matching a header field name.
  370. """
  371. return self.get(name)
  372. def __setitem__(self, name, val):
  373. """Set the value of a header.
  374. Note: this does not overwrite an existing header with the same field
  375. name. Use __delitem__() first to delete any existing headers.
  376. """
  377. max_count = self.policy.header_max_count(name)
  378. if max_count:
  379. lname = name.lower()
  380. found = 0
  381. for k, v in self._headers:
  382. if k.lower() == lname:
  383. found += 1
  384. if found >= max_count:
  385. raise ValueError("There may be at most {} {} headers "
  386. "in a message".format(max_count, name))
  387. self._headers.append(self.policy.header_store_parse(name, val))
  388. def __delitem__(self, name):
  389. """Delete all occurrences of a header, if present.
  390. Does not raise an exception if the header is missing.
  391. """
  392. name = name.lower()
  393. newheaders = []
  394. for k, v in self._headers:
  395. if k.lower() != name:
  396. newheaders.append((k, v))
  397. self._headers = newheaders
  398. def __contains__(self, name):
  399. name_lower = name.lower()
  400. for k, v in self._headers:
  401. if name_lower == k.lower():
  402. return True
  403. return False
  404. def __iter__(self):
  405. for field, value in self._headers:
  406. yield field
  407. def keys(self):
  408. """Return a list of all the message's header field names.
  409. These will be sorted in the order they appeared in the original
  410. message, or were added to the message, and may contain duplicates.
  411. Any fields deleted and re-inserted are always appended to the header
  412. list.
  413. """
  414. return [k for k, v in self._headers]
  415. def values(self):
  416. """Return a list of all the message's header values.
  417. These will be sorted in the order they appeared in the original
  418. message, or were added to the message, and may contain duplicates.
  419. Any fields deleted and re-inserted are always appended to the header
  420. list.
  421. """
  422. return [self.policy.header_fetch_parse(k, v)
  423. for k, v in self._headers]
  424. def items(self):
  425. """Get all the message's header fields and values.
  426. These will be sorted in the order they appeared in the original
  427. message, or were added to the message, and may contain duplicates.
  428. Any fields deleted and re-inserted are always appended to the header
  429. list.
  430. """
  431. return [(k, self.policy.header_fetch_parse(k, v))
  432. for k, v in self._headers]
  433. def get(self, name, failobj=None):
  434. """Get a header value.
  435. Like __getitem__() but return failobj instead of None when the field
  436. is missing.
  437. """
  438. name = name.lower()
  439. for k, v in self._headers:
  440. if k.lower() == name:
  441. return self.policy.header_fetch_parse(k, v)
  442. return failobj
  443. #
  444. # "Internal" methods (public API, but only intended for use by a parser
  445. # or generator, not normal application code.
  446. #
  447. def set_raw(self, name, value):
  448. """Store name and value in the model without modification.
  449. This is an "internal" API, intended only for use by a parser.
  450. """
  451. self._headers.append((name, value))
  452. def raw_items(self):
  453. """Return the (name, value) header pairs without modification.
  454. This is an "internal" API, intended only for use by a generator.
  455. """
  456. return iter(self._headers.copy())
  457. #
  458. # Additional useful stuff
  459. #
  460. def get_all(self, name, failobj=None):
  461. """Return a list of all the values for the named field.
  462. These will be sorted in the order they appeared in the original
  463. message, and may contain duplicates. Any fields deleted and
  464. re-inserted are always appended to the header list.
  465. If no such fields exist, failobj is returned (defaults to None).
  466. """
  467. values = []
  468. name = name.lower()
  469. for k, v in self._headers:
  470. if k.lower() == name:
  471. values.append(self.policy.header_fetch_parse(k, v))
  472. if not values:
  473. return failobj
  474. return values
  475. def add_header(self, _name, _value, **_params):
  476. """Extended header setting.
  477. name is the header field to add. keyword arguments can be used to set
  478. additional parameters for the header field, with underscores converted
  479. to dashes. Normally the parameter will be added as key="value" unless
  480. value is None, in which case only the key will be added. If a
  481. parameter value contains non-ASCII characters it can be specified as a
  482. three-tuple of (charset, language, value), in which case it will be
  483. encoded according to RFC2231 rules. Otherwise it will be encoded using
  484. the utf-8 charset and a language of ''.
  485. Examples:
  486. msg.add_header('content-disposition', 'attachment', filename='bud.gif')
  487. msg.add_header('content-disposition', 'attachment',
  488. filename=('utf-8', '', Fußballer.ppt'))
  489. msg.add_header('content-disposition', 'attachment',
  490. filename='Fußballer.ppt'))
  491. """
  492. parts = []
  493. for k, v in _params.items():
  494. if v is None:
  495. parts.append(k.replace('_', '-'))
  496. else:
  497. parts.append(_formatparam(k.replace('_', '-'), v))
  498. if _value is not None:
  499. parts.insert(0, _value)
  500. self[_name] = SEMISPACE.join(parts)
  501. def replace_header(self, _name, _value):
  502. """Replace a header.
  503. Replace the first matching header found in the message, retaining
  504. header order and case. If no matching header was found, a KeyError is
  505. raised.
  506. """
  507. _name = _name.lower()
  508. for i, (k, v) in zip(range(len(self._headers)), self._headers):
  509. if k.lower() == _name:
  510. self._headers[i] = self.policy.header_store_parse(k, _value)
  511. break
  512. else:
  513. raise KeyError(_name)
  514. #
  515. # Use these three methods instead of the three above.
  516. #
  517. def get_content_type(self):
  518. """Return the message's content type.
  519. The returned string is coerced to lower case of the form
  520. `maintype/subtype'. If there was no Content-Type header in the
  521. message, the default type as given by get_default_type() will be
  522. returned. Since according to RFC 2045, messages always have a default
  523. type this will always return a value.
  524. RFC 2045 defines a message's default type to be text/plain unless it
  525. appears inside a multipart/digest container, in which case it would be
  526. message/rfc822.
  527. """
  528. missing = object()
  529. value = self.get('content-type', missing)
  530. if value is missing:
  531. # This should have no parameters
  532. return self.get_default_type()
  533. ctype = _splitparam(value)[0].lower()
  534. # RFC 2045, section 5.2 says if its invalid, use text/plain
  535. if ctype.count('/') != 1:
  536. return 'text/plain'
  537. return ctype
  538. def get_content_maintype(self):
  539. """Return the message's main content type.
  540. This is the `maintype' part of the string returned by
  541. get_content_type().
  542. """
  543. ctype = self.get_content_type()
  544. return ctype.split('/')[0]
  545. def get_content_subtype(self):
  546. """Returns the message's sub-content type.
  547. This is the `subtype' part of the string returned by
  548. get_content_type().
  549. """
  550. ctype = self.get_content_type()
  551. return ctype.split('/')[1]
  552. def get_default_type(self):
  553. """Return the `default' content type.
  554. Most messages have a default content type of text/plain, except for
  555. messages that are subparts of multipart/digest containers. Such
  556. subparts have a default content type of message/rfc822.
  557. """
  558. return self._default_type
  559. def set_default_type(self, ctype):
  560. """Set the `default' content type.
  561. ctype should be either "text/plain" or "message/rfc822", although this
  562. is not enforced. The default content type is not stored in the
  563. Content-Type header.
  564. """
  565. self._default_type = ctype
  566. def _get_params_preserve(self, failobj, header):
  567. # Like get_params() but preserves the quoting of values. BAW:
  568. # should this be part of the public interface?
  569. missing = object()
  570. value = self.get(header, missing)
  571. if value is missing:
  572. return failobj
  573. params = []
  574. for p in _parseparam(value):
  575. try:
  576. name, val = p.split('=', 1)
  577. name = name.strip()
  578. val = val.strip()
  579. except ValueError:
  580. # Must have been a bare attribute
  581. name = p.strip()
  582. val = ''
  583. params.append((name, val))
  584. params = utils.decode_params(params)
  585. return params
  586. def get_params(self, failobj=None, header='content-type', unquote=True):
  587. """Return the message's Content-Type parameters, as a list.
  588. The elements of the returned list are 2-tuples of key/value pairs, as
  589. split on the `=' sign. The left hand side of the `=' is the key,
  590. while the right hand side is the value. If there is no `=' sign in
  591. the parameter the value is the empty string. The value is as
  592. described in the get_param() method.
  593. Optional failobj is the object to return if there is no Content-Type
  594. header. Optional header is the header to search instead of
  595. Content-Type. If unquote is True, the value is unquoted.
  596. """
  597. missing = object()
  598. params = self._get_params_preserve(missing, header)
  599. if params is missing:
  600. return failobj
  601. if unquote:
  602. return [(k, _unquotevalue(v)) for k, v in params]
  603. else:
  604. return params
  605. def get_param(self, param, failobj=None, header='content-type',
  606. unquote=True):
  607. """Return the parameter value if found in the Content-Type header.
  608. Optional failobj is the object to return if there is no Content-Type
  609. header, or the Content-Type header has no such parameter. Optional
  610. header is the header to search instead of Content-Type.
  611. Parameter keys are always compared case insensitively. The return
  612. value can either be a string, or a 3-tuple if the parameter was RFC
  613. 2231 encoded. When it's a 3-tuple, the elements of the value are of
  614. the form (CHARSET, LANGUAGE, VALUE). Note that both CHARSET and
  615. LANGUAGE can be None, in which case you should consider VALUE to be
  616. encoded in the us-ascii charset. You can usually ignore LANGUAGE.
  617. The parameter value (either the returned string, or the VALUE item in
  618. the 3-tuple) is always unquoted, unless unquote is set to False.
  619. If your application doesn't care whether the parameter was RFC 2231
  620. encoded, it can turn the return value into a string as follows:
  621. rawparam = msg.get_param('foo')
  622. param = email.utils.collapse_rfc2231_value(rawparam)
  623. """
  624. if header not in self:
  625. return failobj
  626. for k, v in self._get_params_preserve(failobj, header):
  627. if k.lower() == param.lower():
  628. if unquote:
  629. return _unquotevalue(v)
  630. else:
  631. return v
  632. return failobj
  633. def set_param(self, param, value, header='Content-Type', requote=True,
  634. charset=None, language='', replace=False):
  635. """Set a parameter in the Content-Type header.
  636. If the parameter already exists in the header, its value will be
  637. replaced with the new value.
  638. If header is Content-Type and has not yet been defined for this
  639. message, it will be set to "text/plain" and the new parameter and
  640. value will be appended as per RFC 2045.
  641. An alternate header can be specified in the header argument, and all
  642. parameters will be quoted as necessary unless requote is False.
  643. If charset is specified, the parameter will be encoded according to RFC
  644. 2231. Optional language specifies the RFC 2231 language, defaulting
  645. to the empty string. Both charset and language should be strings.
  646. """
  647. if not isinstance(value, tuple) and charset:
  648. value = (charset, language, value)
  649. if header not in self and header.lower() == 'content-type':
  650. ctype = 'text/plain'
  651. else:
  652. ctype = self.get(header)
  653. if not self.get_param(param, header=header):
  654. if not ctype:
  655. ctype = _formatparam(param, value, requote)
  656. else:
  657. ctype = SEMISPACE.join(
  658. [ctype, _formatparam(param, value, requote)])
  659. else:
  660. ctype = ''
  661. for old_param, old_value in self.get_params(header=header,
  662. unquote=requote):
  663. append_param = ''
  664. if old_param.lower() == param.lower():
  665. append_param = _formatparam(param, value, requote)
  666. else:
  667. append_param = _formatparam(old_param, old_value, requote)
  668. if not ctype:
  669. ctype = append_param
  670. else:
  671. ctype = SEMISPACE.join([ctype, append_param])
  672. if ctype != self.get(header):
  673. if replace:
  674. self.replace_header(header, ctype)
  675. else:
  676. del self[header]
  677. self[header] = ctype
  678. def del_param(self, param, header='content-type', requote=True):
  679. """Remove the given parameter completely from the Content-Type header.
  680. The header will be re-written in place without the parameter or its
  681. value. All values will be quoted as necessary unless requote is
  682. False. Optional header specifies an alternative to the Content-Type
  683. header.
  684. """
  685. if header not in self:
  686. return
  687. new_ctype = ''
  688. for p, v in self.get_params(header=header, unquote=requote):
  689. if p.lower() != param.lower():
  690. if not new_ctype:
  691. new_ctype = _formatparam(p, v, requote)
  692. else:
  693. new_ctype = SEMISPACE.join([new_ctype,
  694. _formatparam(p, v, requote)])
  695. if new_ctype != self.get(header):
  696. del self[header]
  697. self[header] = new_ctype
  698. def set_type(self, type, header='Content-Type', requote=True):
  699. """Set the main type and subtype for the Content-Type header.
  700. type must be a string in the form "maintype/subtype", otherwise a
  701. ValueError is raised.
  702. This method replaces the Content-Type header, keeping all the
  703. parameters in place. If requote is False, this leaves the existing
  704. header's quoting as is. Otherwise, the parameters will be quoted (the
  705. default).
  706. An alternative header can be specified in the header argument. When
  707. the Content-Type header is set, we'll always also add a MIME-Version
  708. header.
  709. """
  710. # BAW: should we be strict?
  711. if not type.count('/') == 1:
  712. raise ValueError
  713. # Set the Content-Type, you get a MIME-Version
  714. if header.lower() == 'content-type':
  715. del self['mime-version']
  716. self['MIME-Version'] = '1.0'
  717. if header not in self:
  718. self[header] = type
  719. return
  720. params = self.get_params(header=header, unquote=requote)
  721. del self[header]
  722. self[header] = type
  723. # Skip the first param; it's the old type.
  724. for p, v in params[1:]:
  725. self.set_param(p, v, header, requote)
  726. def get_filename(self, failobj=None):
  727. """Return the filename associated with the payload if present.
  728. The filename is extracted from the Content-Disposition header's
  729. `filename' parameter, and it is unquoted. If that header is missing
  730. the `filename' parameter, this method falls back to looking for the
  731. `name' parameter.
  732. """
  733. missing = object()
  734. filename = self.get_param('filename', missing, 'content-disposition')
  735. if filename is missing:
  736. filename = self.get_param('name', missing, 'content-type')
  737. if filename is missing:
  738. return failobj
  739. return utils.collapse_rfc2231_value(filename).strip()
  740. def get_boundary(self, failobj=None):
  741. """Return the boundary associated with the payload if present.
  742. The boundary is extracted from the Content-Type header's `boundary'
  743. parameter, and it is unquoted.
  744. """
  745. missing = object()
  746. boundary = self.get_param('boundary', missing)
  747. if boundary is missing:
  748. return failobj
  749. # RFC 2046 says that boundaries may begin but not end in w/s
  750. return utils.collapse_rfc2231_value(boundary).rstrip()
  751. def set_boundary(self, boundary):
  752. """Set the boundary parameter in Content-Type to 'boundary'.
  753. This is subtly different than deleting the Content-Type header and
  754. adding a new one with a new boundary parameter via add_header(). The
  755. main difference is that using the set_boundary() method preserves the
  756. order of the Content-Type header in the original message.
  757. HeaderParseError is raised if the message has no Content-Type header.
  758. """
  759. missing = object()
  760. params = self._get_params_preserve(missing, 'content-type')
  761. if params is missing:
  762. # There was no Content-Type header, and we don't know what type
  763. # to set it to, so raise an exception.
  764. raise errors.HeaderParseError('No Content-Type header found')
  765. newparams = []
  766. foundp = False
  767. for pk, pv in params:
  768. if pk.lower() == 'boundary':
  769. newparams.append(('boundary', '"%s"' % boundary))
  770. foundp = True
  771. else:
  772. newparams.append((pk, pv))
  773. if not foundp:
  774. # The original Content-Type header had no boundary attribute.
  775. # Tack one on the end. BAW: should we raise an exception
  776. # instead???
  777. newparams.append(('boundary', '"%s"' % boundary))
  778. # Replace the existing Content-Type header with the new value
  779. newheaders = []
  780. for h, v in self._headers:
  781. if h.lower() == 'content-type':
  782. parts = []
  783. for k, v in newparams:
  784. if v == '':
  785. parts.append(k)
  786. else:
  787. parts.append('%s=%s' % (k, v))
  788. val = SEMISPACE.join(parts)
  789. newheaders.append(self.policy.header_store_parse(h, val))
  790. else:
  791. newheaders.append((h, v))
  792. self._headers = newheaders
  793. def get_content_charset(self, failobj=None):
  794. """Return the charset parameter of the Content-Type header.
  795. The returned string is always coerced to lower case. If there is no
  796. Content-Type header, or if that header has no charset parameter,
  797. failobj is returned.
  798. """
  799. missing = object()
  800. charset = self.get_param('charset', missing)
  801. if charset is missing:
  802. return failobj
  803. if isinstance(charset, tuple):
  804. # RFC 2231 encoded, so decode it, and it better end up as ascii.
  805. pcharset = charset[0] or 'us-ascii'
  806. try:
  807. # LookupError will be raised if the charset isn't known to
  808. # Python. UnicodeError will be raised if the encoded text
  809. # contains a character not in the charset.
  810. as_bytes = charset[2].encode('raw-unicode-escape')
  811. charset = str(as_bytes, pcharset)
  812. except (LookupError, UnicodeError):
  813. charset = charset[2]
  814. # charset characters must be in us-ascii range
  815. try:
  816. charset.encode('us-ascii')
  817. except UnicodeError:
  818. return failobj
  819. # RFC 2046, $4.1.2 says charsets are not case sensitive
  820. return charset.lower()
  821. def get_charsets(self, failobj=None):
  822. """Return a list containing the charset(s) used in this message.
  823. The returned list of items describes the Content-Type headers'
  824. charset parameter for this message and all the subparts in its
  825. payload.
  826. Each item will either be a string (the value of the charset parameter
  827. in the Content-Type header of that part) or the value of the
  828. 'failobj' parameter (defaults to None), if the part does not have a
  829. main MIME type of "text", or the charset is not defined.
  830. The list will contain one string for each part of the message, plus
  831. one for the container message (i.e. self), so that a non-multipart
  832. message will still return a list of length 1.
  833. """
  834. return [part.get_content_charset(failobj) for part in self.walk()]
  835. def get_content_disposition(self):
  836. """Return the message's content-disposition if it exists, or None.
  837. The return values can be either 'inline', 'attachment' or None
  838. according to the rfc2183.
  839. """
  840. value = self.get('content-disposition')
  841. if value is None:
  842. return None
  843. c_d = _splitparam(value)[0].lower()
  844. return c_d
  845. # I.e. def walk(self): ...
  846. from email.iterators import walk
  847. class MIMEPart(Message):
  848. def __init__(self, policy=None):
  849. if policy is None:
  850. from email.policy import default
  851. policy = default
  852. super().__init__(policy)
  853. def as_string(self, unixfrom=False, maxheaderlen=None, policy=None):
  854. """Return the entire formatted message as a string.
  855. Optional 'unixfrom', when true, means include the Unix From_ envelope
  856. header. maxheaderlen is retained for backward compatibility with the
  857. base Message class, but defaults to None, meaning that the policy value
  858. for max_line_length controls the header maximum length. 'policy' is
  859. passed to the Generator instance used to serialize the message; if it
  860. is not specified the policy associated with the message instance is
  861. used.
  862. """
  863. policy = self.policy if policy is None else policy
  864. if maxheaderlen is None:
  865. maxheaderlen = policy.max_line_length
  866. return super().as_string(unixfrom, maxheaderlen, policy)
  867. def __str__(self):
  868. return self.as_string(policy=self.policy.clone(utf8=True))
  869. def is_attachment(self):
  870. c_d = self.get('content-disposition')
  871. return False if c_d is None else c_d.content_disposition == 'attachment'
  872. def _find_body(self, part, preferencelist):
  873. if part.is_attachment():
  874. return
  875. maintype, subtype = part.get_content_type().split('/')
  876. if maintype == 'text':
  877. if subtype in preferencelist:
  878. yield (preferencelist.index(subtype), part)
  879. return
  880. if maintype != 'multipart' or not self.is_multipart():
  881. return
  882. if subtype != 'related':
  883. for subpart in part.iter_parts():
  884. yield from self._find_body(subpart, preferencelist)
  885. return
  886. if 'related' in preferencelist:
  887. yield (preferencelist.index('related'), part)
  888. candidate = None
  889. start = part.get_param('start')
  890. if start:
  891. for subpart in part.iter_parts():
  892. if subpart['content-id'] == start:
  893. candidate = subpart
  894. break
  895. if candidate is None:
  896. subparts = part.get_payload()
  897. candidate = subparts[0] if subparts else None
  898. if candidate is not None:
  899. yield from self._find_body(candidate, preferencelist)
  900. def get_body(self, preferencelist=('related', 'html', 'plain')):
  901. """Return best candidate mime part for display as 'body' of message.
  902. Do a depth first search, starting with self, looking for the first part
  903. matching each of the items in preferencelist, and return the part
  904. corresponding to the first item that has a match, or None if no items
  905. have a match. If 'related' is not included in preferencelist, consider
  906. the root part of any multipart/related encountered as a candidate
  907. match. Ignore parts with 'Content-Disposition: attachment'.
  908. """
  909. best_prio = len(preferencelist)
  910. body = None
  911. for prio, part in self._find_body(self, preferencelist):
  912. if prio < best_prio:
  913. best_prio = prio
  914. body = part
  915. if prio == 0:
  916. break
  917. return body
  918. _body_types = {('text', 'plain'),
  919. ('text', 'html'),
  920. ('multipart', 'related'),
  921. ('multipart', 'alternative')}
  922. def iter_attachments(self):
  923. """Return an iterator over the non-main parts of a multipart.
  924. Skip the first of each occurrence of text/plain, text/html,
  925. multipart/related, or multipart/alternative in the multipart (unless
  926. they have a 'Content-Disposition: attachment' header) and include all
  927. remaining subparts in the returned iterator. When applied to a
  928. multipart/related, return all parts except the root part. Return an
  929. empty iterator when applied to a multipart/alternative or a
  930. non-multipart.
  931. """
  932. maintype, subtype = self.get_content_type().split('/')
  933. if maintype != 'multipart' or subtype == 'alternative':
  934. return
  935. payload = self.get_payload()
  936. # Certain malformed messages can have content type set to `multipart/*`
  937. # but still have single part body, in which case payload.copy() can
  938. # fail with AttributeError.
  939. try:
  940. parts = payload.copy()
  941. except AttributeError:
  942. # payload is not a list, it is most probably a string.
  943. return
  944. if maintype == 'multipart' and subtype == 'related':
  945. # For related, we treat everything but the root as an attachment.
  946. # The root may be indicated by 'start'; if there's no start or we
  947. # can't find the named start, treat the first subpart as the root.
  948. start = self.get_param('start')
  949. if start:
  950. found = False
  951. attachments = []
  952. for part in parts:
  953. if part.get('content-id') == start:
  954. found = True
  955. else:
  956. attachments.append(part)
  957. if found:
  958. yield from attachments
  959. return
  960. parts.pop(0)
  961. yield from parts
  962. return
  963. # Otherwise we more or less invert the remaining logic in get_body.
  964. # This only really works in edge cases (ex: non-text related or
  965. # alternatives) if the sending agent sets content-disposition.
  966. seen = [] # Only skip the first example of each candidate type.
  967. for part in parts:
  968. maintype, subtype = part.get_content_type().split('/')
  969. if ((maintype, subtype) in self._body_types and
  970. not part.is_attachment() and subtype not in seen):
  971. seen.append(subtype)
  972. continue
  973. yield part
  974. def iter_parts(self):
  975. """Return an iterator over all immediate subparts of a multipart.
  976. Return an empty iterator for a non-multipart.
  977. """
  978. if self.is_multipart():
  979. yield from self.get_payload()
  980. def get_content(self, *args, content_manager=None, **kw):
  981. if content_manager is None:
  982. content_manager = self.policy.content_manager
  983. return content_manager.get_content(self, *args, **kw)
  984. def set_content(self, *args, content_manager=None, **kw):
  985. if content_manager is None:
  986. content_manager = self.policy.content_manager
  987. content_manager.set_content(self, *args, **kw)
  988. def _make_multipart(self, subtype, disallowed_subtypes, boundary):
  989. if self.get_content_maintype() == 'multipart':
  990. existing_subtype = self.get_content_subtype()
  991. disallowed_subtypes = disallowed_subtypes + (subtype,)
  992. if existing_subtype in disallowed_subtypes:
  993. raise ValueError("Cannot convert {} to {}".format(
  994. existing_subtype, subtype))
  995. keep_headers = []
  996. part_headers = []
  997. for name, value in self._headers:
  998. if name.lower().startswith('content-'):
  999. part_headers.append((name, value))
  1000. else:
  1001. keep_headers.append((name, value))
  1002. if part_headers:
  1003. # There is existing content, move it to the first subpart.
  1004. part = type(self)(policy=self.policy)
  1005. part._headers = part_headers
  1006. part._payload = self._payload
  1007. self._payload = [part]
  1008. else:
  1009. self._payload = []
  1010. self._headers = keep_headers
  1011. self['Content-Type'] = 'multipart/' + subtype
  1012. if boundary is not None:
  1013. self.set_param('boundary', boundary)
  1014. def make_related(self, boundary=None):
  1015. self._make_multipart('related', ('alternative', 'mixed'), boundary)
  1016. def make_alternative(self, boundary=None):
  1017. self._make_multipart('alternative', ('mixed',), boundary)
  1018. def make_mixed(self, boundary=None):
  1019. self._make_multipart('mixed', (), boundary)
  1020. def _add_multipart(self, _subtype, *args, _disp=None, **kw):
  1021. if (self.get_content_maintype() != 'multipart' or
  1022. self.get_content_subtype() != _subtype):
  1023. getattr(self, 'make_' + _subtype)()
  1024. part = type(self)(policy=self.policy)
  1025. part.set_content(*args, **kw)
  1026. if _disp and 'content-disposition' not in part:
  1027. part['Content-Disposition'] = _disp
  1028. self.attach(part)
  1029. def add_related(self, *args, **kw):
  1030. self._add_multipart('related', *args, _disp='inline', **kw)
  1031. def add_alternative(self, *args, **kw):
  1032. self._add_multipart('alternative', *args, **kw)
  1033. def add_attachment(self, *args, **kw):
  1034. self._add_multipart('mixed', *args, _disp='attachment', **kw)
  1035. def clear(self):
  1036. self._headers = []
  1037. self._payload = None
  1038. def clear_content(self):
  1039. self._headers = [(n, v) for n, v in self._headers
  1040. if not n.lower().startswith('content-')]
  1041. self._payload = None
  1042. class EmailMessage(MIMEPart):
  1043. def set_content(self, *args, **kw):
  1044. super().set_content(*args, **kw)
  1045. if 'MIME-Version' not in self:
  1046. self['MIME-Version'] = '1.0'