Debian Codegraph @

lib-python/3/email/message.py

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