message.py 47 KB

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