message.py 46 KB

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