jpayne@68: # Copyright (C) 2001-2007 Python Software Foundation jpayne@68: # Author: Barry Warsaw jpayne@68: # Contact: email-sig@python.org jpayne@68: jpayne@68: """Basic message object for the email package object model.""" jpayne@68: jpayne@68: __all__ = ['Message', 'EmailMessage'] jpayne@68: jpayne@68: import re jpayne@68: import uu jpayne@68: import quopri jpayne@68: from io import BytesIO, StringIO jpayne@68: jpayne@68: # Intrapackage imports jpayne@68: from email import utils jpayne@68: from email import errors jpayne@68: from email._policybase import Policy, compat32 jpayne@68: from email import charset as _charset jpayne@68: from email._encoded_words import decode_b jpayne@68: Charset = _charset.Charset jpayne@68: jpayne@68: SEMISPACE = '; ' jpayne@68: jpayne@68: # Regular expression that matches `special' characters in parameters, the jpayne@68: # existence of which force quoting of the parameter value. jpayne@68: tspecials = re.compile(r'[ \(\)<>@,;:\\"/\[\]\?=]') jpayne@68: jpayne@68: jpayne@68: def _splitparam(param): jpayne@68: # Split header parameters. BAW: this may be too simple. It isn't jpayne@68: # strictly RFC 2045 (section 5.1) compliant, but it catches most headers jpayne@68: # found in the wild. We may eventually need a full fledged parser. jpayne@68: # RDM: we might have a Header here; for now just stringify it. jpayne@68: a, sep, b = str(param).partition(';') jpayne@68: if not sep: jpayne@68: return a.strip(), None jpayne@68: return a.strip(), b.strip() jpayne@68: jpayne@68: def _formatparam(param, value=None, quote=True): jpayne@68: """Convenience function to format and return a key=value pair. jpayne@68: jpayne@68: This will quote the value if needed or if quote is true. If value is a jpayne@68: three tuple (charset, language, value), it will be encoded according jpayne@68: to RFC2231 rules. If it contains non-ascii characters it will likewise jpayne@68: be encoded according to RFC2231 rules, using the utf-8 charset and jpayne@68: a null language. jpayne@68: """ jpayne@68: if value is not None and len(value) > 0: jpayne@68: # A tuple is used for RFC 2231 encoded parameter values where items jpayne@68: # are (charset, language, value). charset is a string, not a Charset jpayne@68: # instance. RFC 2231 encoded values are never quoted, per RFC. jpayne@68: if isinstance(value, tuple): jpayne@68: # Encode as per RFC 2231 jpayne@68: param += '*' jpayne@68: value = utils.encode_rfc2231(value[2], value[0], value[1]) jpayne@68: return '%s=%s' % (param, value) jpayne@68: else: jpayne@68: try: jpayne@68: value.encode('ascii') jpayne@68: except UnicodeEncodeError: jpayne@68: param += '*' jpayne@68: value = utils.encode_rfc2231(value, 'utf-8', '') jpayne@68: return '%s=%s' % (param, value) jpayne@68: # BAW: Please check this. I think that if quote is set it should jpayne@68: # force quoting even if not necessary. jpayne@68: if quote or tspecials.search(value): jpayne@68: return '%s="%s"' % (param, utils.quote(value)) jpayne@68: else: jpayne@68: return '%s=%s' % (param, value) jpayne@68: else: jpayne@68: return param jpayne@68: jpayne@68: def _parseparam(s): jpayne@68: # RDM This might be a Header, so for now stringify it. jpayne@68: s = ';' + str(s) jpayne@68: plist = [] jpayne@68: while s[:1] == ';': jpayne@68: s = s[1:] jpayne@68: end = s.find(';') jpayne@68: while end > 0 and (s.count('"', 0, end) - s.count('\\"', 0, end)) % 2: jpayne@68: end = s.find(';', end + 1) jpayne@68: if end < 0: jpayne@68: end = len(s) jpayne@68: f = s[:end] jpayne@68: if '=' in f: jpayne@68: i = f.index('=') jpayne@68: f = f[:i].strip().lower() + '=' + f[i+1:].strip() jpayne@68: plist.append(f.strip()) jpayne@68: s = s[end:] jpayne@68: return plist jpayne@68: jpayne@68: jpayne@68: def _unquotevalue(value): jpayne@68: # This is different than utils.collapse_rfc2231_value() because it doesn't jpayne@68: # try to convert the value to a unicode. Message.get_param() and jpayne@68: # Message.get_params() are both currently defined to return the tuple in jpayne@68: # the face of RFC 2231 parameters. jpayne@68: if isinstance(value, tuple): jpayne@68: return value[0], value[1], utils.unquote(value[2]) jpayne@68: else: jpayne@68: return utils.unquote(value) jpayne@68: jpayne@68: jpayne@68: jpayne@68: class Message: jpayne@68: """Basic message object. jpayne@68: jpayne@68: A message object is defined as something that has a bunch of RFC 2822 jpayne@68: headers and a payload. It may optionally have an envelope header jpayne@68: (a.k.a. Unix-From or From_ header). If the message is a container (i.e. a jpayne@68: multipart or a message/rfc822), then the payload is a list of Message jpayne@68: objects, otherwise it is a string. jpayne@68: jpayne@68: Message objects implement part of the `mapping' interface, which assumes jpayne@68: there is exactly one occurrence of the header per message. Some headers jpayne@68: do in fact appear multiple times (e.g. Received) and for those headers, jpayne@68: you must use the explicit API to set or get all the headers. Not all of jpayne@68: the mapping methods are implemented. jpayne@68: """ jpayne@68: def __init__(self, policy=compat32): jpayne@68: self.policy = policy jpayne@68: self._headers = [] jpayne@68: self._unixfrom = None jpayne@68: self._payload = None jpayne@68: self._charset = None jpayne@68: # Defaults for multipart messages jpayne@68: self.preamble = self.epilogue = None jpayne@68: self.defects = [] jpayne@68: # Default content type jpayne@68: self._default_type = 'text/plain' jpayne@68: jpayne@68: def __str__(self): jpayne@68: """Return the entire formatted message as a string. jpayne@68: """ jpayne@68: return self.as_string() jpayne@68: jpayne@68: def as_string(self, unixfrom=False, maxheaderlen=0, policy=None): jpayne@68: """Return the entire formatted message as a string. jpayne@68: jpayne@68: Optional 'unixfrom', when true, means include the Unix From_ envelope jpayne@68: header. For backward compatibility reasons, if maxheaderlen is jpayne@68: not specified it defaults to 0, so you must override it explicitly jpayne@68: if you want a different maxheaderlen. 'policy' is passed to the jpayne@68: Generator instance used to serialize the mesasge; if it is not jpayne@68: specified the policy associated with the message instance is used. jpayne@68: jpayne@68: If the message object contains binary data that is not encoded jpayne@68: according to RFC standards, the non-compliant data will be replaced by jpayne@68: unicode "unknown character" code points. jpayne@68: """ jpayne@68: from email.generator import Generator jpayne@68: policy = self.policy if policy is None else policy jpayne@68: fp = StringIO() jpayne@68: g = Generator(fp, jpayne@68: mangle_from_=False, jpayne@68: maxheaderlen=maxheaderlen, jpayne@68: policy=policy) jpayne@68: g.flatten(self, unixfrom=unixfrom) jpayne@68: return fp.getvalue() jpayne@68: jpayne@68: def __bytes__(self): jpayne@68: """Return the entire formatted message as a bytes object. jpayne@68: """ jpayne@68: return self.as_bytes() jpayne@68: jpayne@68: def as_bytes(self, unixfrom=False, policy=None): jpayne@68: """Return the entire formatted message as a bytes object. jpayne@68: jpayne@68: Optional 'unixfrom', when true, means include the Unix From_ envelope jpayne@68: header. 'policy' is passed to the BytesGenerator instance used to jpayne@68: serialize the message; if not specified the policy associated with jpayne@68: the message instance is used. jpayne@68: """ jpayne@68: from email.generator import BytesGenerator jpayne@68: policy = self.policy if policy is None else policy jpayne@68: fp = BytesIO() jpayne@68: g = BytesGenerator(fp, mangle_from_=False, policy=policy) jpayne@68: g.flatten(self, unixfrom=unixfrom) jpayne@68: return fp.getvalue() jpayne@68: jpayne@68: def is_multipart(self): jpayne@68: """Return True if the message consists of multiple parts.""" jpayne@68: return isinstance(self._payload, list) jpayne@68: jpayne@68: # jpayne@68: # Unix From_ line jpayne@68: # jpayne@68: def set_unixfrom(self, unixfrom): jpayne@68: self._unixfrom = unixfrom jpayne@68: jpayne@68: def get_unixfrom(self): jpayne@68: return self._unixfrom jpayne@68: jpayne@68: # jpayne@68: # Payload manipulation. jpayne@68: # jpayne@68: def attach(self, payload): jpayne@68: """Add the given payload to the current payload. jpayne@68: jpayne@68: The current payload will always be a list of objects after this method jpayne@68: is called. If you want to set the payload to a scalar object, use jpayne@68: set_payload() instead. jpayne@68: """ jpayne@68: if self._payload is None: jpayne@68: self._payload = [payload] jpayne@68: else: jpayne@68: try: jpayne@68: self._payload.append(payload) jpayne@68: except AttributeError: jpayne@68: raise TypeError("Attach is not valid on a message with a" jpayne@68: " non-multipart payload") jpayne@68: jpayne@68: def get_payload(self, i=None, decode=False): jpayne@68: """Return a reference to the payload. jpayne@68: jpayne@68: The payload will either be a list object or a string. If you mutate jpayne@68: the list object, you modify the message's payload in place. Optional jpayne@68: i returns that index into the payload. jpayne@68: jpayne@68: Optional decode is a flag indicating whether the payload should be jpayne@68: decoded or not, according to the Content-Transfer-Encoding header jpayne@68: (default is False). jpayne@68: jpayne@68: When True and the message is not a multipart, the payload will be jpayne@68: decoded if this header's value is `quoted-printable' or `base64'. If jpayne@68: some other encoding is used, or the header is missing, or if the jpayne@68: payload has bogus data (i.e. bogus base64 or uuencoded data), the jpayne@68: payload is returned as-is. jpayne@68: jpayne@68: If the message is a multipart and the decode flag is True, then None jpayne@68: is returned. jpayne@68: """ jpayne@68: # Here is the logic table for this code, based on the email5.0.0 code: jpayne@68: # i decode is_multipart result jpayne@68: # ------ ------ ------------ ------------------------------ jpayne@68: # None True True None jpayne@68: # i True True None jpayne@68: # None False True _payload (a list) jpayne@68: # i False True _payload element i (a Message) jpayne@68: # i False False error (not a list) jpayne@68: # i True False error (not a list) jpayne@68: # None False False _payload jpayne@68: # None True False _payload decoded (bytes) jpayne@68: # Note that Barry planned to factor out the 'decode' case, but that jpayne@68: # isn't so easy now that we handle the 8 bit data, which needs to be jpayne@68: # converted in both the decode and non-decode path. jpayne@68: if self.is_multipart(): jpayne@68: if decode: jpayne@68: return None jpayne@68: if i is None: jpayne@68: return self._payload jpayne@68: else: jpayne@68: return self._payload[i] jpayne@68: # For backward compatibility, Use isinstance and this error message jpayne@68: # instead of the more logical is_multipart test. jpayne@68: if i is not None and not isinstance(self._payload, list): jpayne@68: raise TypeError('Expected list, got %s' % type(self._payload)) jpayne@68: payload = self._payload jpayne@68: # cte might be a Header, so for now stringify it. jpayne@68: cte = str(self.get('content-transfer-encoding', '')).lower() jpayne@68: # payload may be bytes here. jpayne@68: if isinstance(payload, str): jpayne@68: if utils._has_surrogates(payload): jpayne@68: bpayload = payload.encode('ascii', 'surrogateescape') jpayne@68: if not decode: jpayne@68: try: jpayne@68: payload = bpayload.decode(self.get_param('charset', 'ascii'), 'replace') jpayne@68: except LookupError: jpayne@68: payload = bpayload.decode('ascii', 'replace') jpayne@68: elif decode: jpayne@68: try: jpayne@68: bpayload = payload.encode('ascii') jpayne@68: except UnicodeError: jpayne@68: # This won't happen for RFC compliant messages (messages jpayne@68: # containing only ASCII code points in the unicode input). jpayne@68: # If it does happen, turn the string into bytes in a way jpayne@68: # guaranteed not to fail. jpayne@68: bpayload = payload.encode('raw-unicode-escape') jpayne@68: if not decode: jpayne@68: return payload jpayne@68: if cte == 'quoted-printable': jpayne@68: return quopri.decodestring(bpayload) jpayne@68: elif cte == 'base64': jpayne@68: # XXX: this is a bit of a hack; decode_b should probably be factored jpayne@68: # out somewhere, but I haven't figured out where yet. jpayne@68: value, defects = decode_b(b''.join(bpayload.splitlines())) jpayne@68: for defect in defects: jpayne@68: self.policy.handle_defect(self, defect) jpayne@68: return value jpayne@68: elif cte in ('x-uuencode', 'uuencode', 'uue', 'x-uue'): jpayne@68: in_file = BytesIO(bpayload) jpayne@68: out_file = BytesIO() jpayne@68: try: jpayne@68: uu.decode(in_file, out_file, quiet=True) jpayne@68: return out_file.getvalue() jpayne@68: except uu.Error: jpayne@68: # Some decoding problem jpayne@68: return bpayload jpayne@68: if isinstance(payload, str): jpayne@68: return bpayload jpayne@68: return payload jpayne@68: jpayne@68: def set_payload(self, payload, charset=None): jpayne@68: """Set the payload to the given value. jpayne@68: jpayne@68: Optional charset sets the message's default character set. See jpayne@68: set_charset() for details. jpayne@68: """ jpayne@68: if hasattr(payload, 'encode'): jpayne@68: if charset is None: jpayne@68: self._payload = payload jpayne@68: return jpayne@68: if not isinstance(charset, Charset): jpayne@68: charset = Charset(charset) jpayne@68: payload = payload.encode(charset.output_charset) jpayne@68: if hasattr(payload, 'decode'): jpayne@68: self._payload = payload.decode('ascii', 'surrogateescape') jpayne@68: else: jpayne@68: self._payload = payload jpayne@68: if charset is not None: jpayne@68: self.set_charset(charset) jpayne@68: jpayne@68: def set_charset(self, charset): jpayne@68: """Set the charset of the payload to a given character set. jpayne@68: jpayne@68: charset can be a Charset instance, a string naming a character set, or jpayne@68: None. If it is a string it will be converted to a Charset instance. jpayne@68: If charset is None, the charset parameter will be removed from the jpayne@68: Content-Type field. Anything else will generate a TypeError. jpayne@68: jpayne@68: The message will be assumed to be of type text/* encoded with jpayne@68: charset.input_charset. It will be converted to charset.output_charset jpayne@68: and encoded properly, if needed, when generating the plain text jpayne@68: representation of the message. MIME headers (MIME-Version, jpayne@68: Content-Type, Content-Transfer-Encoding) will be added as needed. jpayne@68: """ jpayne@68: if charset is None: jpayne@68: self.del_param('charset') jpayne@68: self._charset = None jpayne@68: return jpayne@68: if not isinstance(charset, Charset): jpayne@68: charset = Charset(charset) jpayne@68: self._charset = charset jpayne@68: if 'MIME-Version' not in self: jpayne@68: self.add_header('MIME-Version', '1.0') jpayne@68: if 'Content-Type' not in self: jpayne@68: self.add_header('Content-Type', 'text/plain', jpayne@68: charset=charset.get_output_charset()) jpayne@68: else: jpayne@68: self.set_param('charset', charset.get_output_charset()) jpayne@68: if charset != charset.get_output_charset(): jpayne@68: self._payload = charset.body_encode(self._payload) jpayne@68: if 'Content-Transfer-Encoding' not in self: jpayne@68: cte = charset.get_body_encoding() jpayne@68: try: jpayne@68: cte(self) jpayne@68: except TypeError: jpayne@68: # This 'if' is for backward compatibility, it allows unicode jpayne@68: # through even though that won't work correctly if the jpayne@68: # message is serialized. jpayne@68: payload = self._payload jpayne@68: if payload: jpayne@68: try: jpayne@68: payload = payload.encode('ascii', 'surrogateescape') jpayne@68: except UnicodeError: jpayne@68: payload = payload.encode(charset.output_charset) jpayne@68: self._payload = charset.body_encode(payload) jpayne@68: self.add_header('Content-Transfer-Encoding', cte) jpayne@68: jpayne@68: def get_charset(self): jpayne@68: """Return the Charset instance associated with the message's payload. jpayne@68: """ jpayne@68: return self._charset jpayne@68: jpayne@68: # jpayne@68: # MAPPING INTERFACE (partial) jpayne@68: # jpayne@68: def __len__(self): jpayne@68: """Return the total number of headers, including duplicates.""" jpayne@68: return len(self._headers) jpayne@68: jpayne@68: def __getitem__(self, name): jpayne@68: """Get a header value. jpayne@68: jpayne@68: Return None if the header is missing instead of raising an exception. jpayne@68: jpayne@68: Note that if the header appeared multiple times, exactly which jpayne@68: occurrence gets returned is undefined. Use get_all() to get all jpayne@68: the values matching a header field name. jpayne@68: """ jpayne@68: return self.get(name) jpayne@68: jpayne@68: def __setitem__(self, name, val): jpayne@68: """Set the value of a header. jpayne@68: jpayne@68: Note: this does not overwrite an existing header with the same field jpayne@68: name. Use __delitem__() first to delete any existing headers. jpayne@68: """ jpayne@68: max_count = self.policy.header_max_count(name) jpayne@68: if max_count: jpayne@68: lname = name.lower() jpayne@68: found = 0 jpayne@68: for k, v in self._headers: jpayne@68: if k.lower() == lname: jpayne@68: found += 1 jpayne@68: if found >= max_count: jpayne@68: raise ValueError("There may be at most {} {} headers " jpayne@68: "in a message".format(max_count, name)) jpayne@68: self._headers.append(self.policy.header_store_parse(name, val)) jpayne@68: jpayne@68: def __delitem__(self, name): jpayne@68: """Delete all occurrences of a header, if present. jpayne@68: jpayne@68: Does not raise an exception if the header is missing. jpayne@68: """ jpayne@68: name = name.lower() jpayne@68: newheaders = [] jpayne@68: for k, v in self._headers: jpayne@68: if k.lower() != name: jpayne@68: newheaders.append((k, v)) jpayne@68: self._headers = newheaders jpayne@68: jpayne@68: def __contains__(self, name): jpayne@68: return name.lower() in [k.lower() for k, v in self._headers] jpayne@68: jpayne@68: def __iter__(self): jpayne@68: for field, value in self._headers: jpayne@68: yield field jpayne@68: jpayne@68: def keys(self): jpayne@68: """Return a list of all the message's header field names. jpayne@68: jpayne@68: These will be sorted in the order they appeared in the original jpayne@68: message, or were added to the message, and may contain duplicates. jpayne@68: Any fields deleted and re-inserted are always appended to the header jpayne@68: list. jpayne@68: """ jpayne@68: return [k for k, v in self._headers] jpayne@68: jpayne@68: def values(self): jpayne@68: """Return a list of all the message's header values. jpayne@68: jpayne@68: These will be sorted in the order they appeared in the original jpayne@68: message, or were added to the message, and may contain duplicates. jpayne@68: Any fields deleted and re-inserted are always appended to the header jpayne@68: list. jpayne@68: """ jpayne@68: return [self.policy.header_fetch_parse(k, v) jpayne@68: for k, v in self._headers] jpayne@68: jpayne@68: def items(self): jpayne@68: """Get all the message's header fields and values. jpayne@68: jpayne@68: These will be sorted in the order they appeared in the original jpayne@68: message, or were added to the message, and may contain duplicates. jpayne@68: Any fields deleted and re-inserted are always appended to the header jpayne@68: list. jpayne@68: """ jpayne@68: return [(k, self.policy.header_fetch_parse(k, v)) jpayne@68: for k, v in self._headers] jpayne@68: jpayne@68: def get(self, name, failobj=None): jpayne@68: """Get a header value. jpayne@68: jpayne@68: Like __getitem__() but return failobj instead of None when the field jpayne@68: is missing. jpayne@68: """ jpayne@68: name = name.lower() jpayne@68: for k, v in self._headers: jpayne@68: if k.lower() == name: jpayne@68: return self.policy.header_fetch_parse(k, v) jpayne@68: return failobj jpayne@68: jpayne@68: # jpayne@68: # "Internal" methods (public API, but only intended for use by a parser jpayne@68: # or generator, not normal application code. jpayne@68: # jpayne@68: jpayne@68: def set_raw(self, name, value): jpayne@68: """Store name and value in the model without modification. jpayne@68: jpayne@68: This is an "internal" API, intended only for use by a parser. jpayne@68: """ jpayne@68: self._headers.append((name, value)) jpayne@68: jpayne@68: def raw_items(self): jpayne@68: """Return the (name, value) header pairs without modification. jpayne@68: jpayne@68: This is an "internal" API, intended only for use by a generator. jpayne@68: """ jpayne@68: return iter(self._headers.copy()) jpayne@68: jpayne@68: # jpayne@68: # Additional useful stuff jpayne@68: # jpayne@68: jpayne@68: def get_all(self, name, failobj=None): jpayne@68: """Return a list of all the values for the named field. jpayne@68: jpayne@68: These will be sorted in the order they appeared in the original jpayne@68: message, and may contain duplicates. Any fields deleted and jpayne@68: re-inserted are always appended to the header list. jpayne@68: jpayne@68: If no such fields exist, failobj is returned (defaults to None). jpayne@68: """ jpayne@68: values = [] jpayne@68: name = name.lower() jpayne@68: for k, v in self._headers: jpayne@68: if k.lower() == name: jpayne@68: values.append(self.policy.header_fetch_parse(k, v)) jpayne@68: if not values: jpayne@68: return failobj jpayne@68: return values jpayne@68: jpayne@68: def add_header(self, _name, _value, **_params): jpayne@68: """Extended header setting. jpayne@68: jpayne@68: name is the header field to add. keyword arguments can be used to set jpayne@68: additional parameters for the header field, with underscores converted jpayne@68: to dashes. Normally the parameter will be added as key="value" unless jpayne@68: value is None, in which case only the key will be added. If a jpayne@68: parameter value contains non-ASCII characters it can be specified as a jpayne@68: three-tuple of (charset, language, value), in which case it will be jpayne@68: encoded according to RFC2231 rules. Otherwise it will be encoded using jpayne@68: the utf-8 charset and a language of ''. jpayne@68: jpayne@68: Examples: jpayne@68: jpayne@68: msg.add_header('content-disposition', 'attachment', filename='bud.gif') jpayne@68: msg.add_header('content-disposition', 'attachment', jpayne@68: filename=('utf-8', '', Fußballer.ppt')) jpayne@68: msg.add_header('content-disposition', 'attachment', jpayne@68: filename='Fußballer.ppt')) jpayne@68: """ jpayne@68: parts = [] jpayne@68: for k, v in _params.items(): jpayne@68: if v is None: jpayne@68: parts.append(k.replace('_', '-')) jpayne@68: else: jpayne@68: parts.append(_formatparam(k.replace('_', '-'), v)) jpayne@68: if _value is not None: jpayne@68: parts.insert(0, _value) jpayne@68: self[_name] = SEMISPACE.join(parts) jpayne@68: jpayne@68: def replace_header(self, _name, _value): jpayne@68: """Replace a header. jpayne@68: jpayne@68: Replace the first matching header found in the message, retaining jpayne@68: header order and case. If no matching header was found, a KeyError is jpayne@68: raised. jpayne@68: """ jpayne@68: _name = _name.lower() jpayne@68: for i, (k, v) in zip(range(len(self._headers)), self._headers): jpayne@68: if k.lower() == _name: jpayne@68: self._headers[i] = self.policy.header_store_parse(k, _value) jpayne@68: break jpayne@68: else: jpayne@68: raise KeyError(_name) jpayne@68: jpayne@68: # jpayne@68: # Use these three methods instead of the three above. jpayne@68: # jpayne@68: jpayne@68: def get_content_type(self): jpayne@68: """Return the message's content type. jpayne@68: jpayne@68: The returned string is coerced to lower case of the form jpayne@68: `maintype/subtype'. If there was no Content-Type header in the jpayne@68: message, the default type as given by get_default_type() will be jpayne@68: returned. Since according to RFC 2045, messages always have a default jpayne@68: type this will always return a value. jpayne@68: jpayne@68: RFC 2045 defines a message's default type to be text/plain unless it jpayne@68: appears inside a multipart/digest container, in which case it would be jpayne@68: message/rfc822. jpayne@68: """ jpayne@68: missing = object() jpayne@68: value = self.get('content-type', missing) jpayne@68: if value is missing: jpayne@68: # This should have no parameters jpayne@68: return self.get_default_type() jpayne@68: ctype = _splitparam(value)[0].lower() jpayne@68: # RFC 2045, section 5.2 says if its invalid, use text/plain jpayne@68: if ctype.count('/') != 1: jpayne@68: return 'text/plain' jpayne@68: return ctype jpayne@68: jpayne@68: def get_content_maintype(self): jpayne@68: """Return the message's main content type. jpayne@68: jpayne@68: This is the `maintype' part of the string returned by jpayne@68: get_content_type(). jpayne@68: """ jpayne@68: ctype = self.get_content_type() jpayne@68: return ctype.split('/')[0] jpayne@68: jpayne@68: def get_content_subtype(self): jpayne@68: """Returns the message's sub-content type. jpayne@68: jpayne@68: This is the `subtype' part of the string returned by jpayne@68: get_content_type(). jpayne@68: """ jpayne@68: ctype = self.get_content_type() jpayne@68: return ctype.split('/')[1] jpayne@68: jpayne@68: def get_default_type(self): jpayne@68: """Return the `default' content type. jpayne@68: jpayne@68: Most messages have a default content type of text/plain, except for jpayne@68: messages that are subparts of multipart/digest containers. Such jpayne@68: subparts have a default content type of message/rfc822. jpayne@68: """ jpayne@68: return self._default_type jpayne@68: jpayne@68: def set_default_type(self, ctype): jpayne@68: """Set the `default' content type. jpayne@68: jpayne@68: ctype should be either "text/plain" or "message/rfc822", although this jpayne@68: is not enforced. The default content type is not stored in the jpayne@68: Content-Type header. jpayne@68: """ jpayne@68: self._default_type = ctype jpayne@68: jpayne@68: def _get_params_preserve(self, failobj, header): jpayne@68: # Like get_params() but preserves the quoting of values. BAW: jpayne@68: # should this be part of the public interface? jpayne@68: missing = object() jpayne@68: value = self.get(header, missing) jpayne@68: if value is missing: jpayne@68: return failobj jpayne@68: params = [] jpayne@68: for p in _parseparam(value): jpayne@68: try: jpayne@68: name, val = p.split('=', 1) jpayne@68: name = name.strip() jpayne@68: val = val.strip() jpayne@68: except ValueError: jpayne@68: # Must have been a bare attribute jpayne@68: name = p.strip() jpayne@68: val = '' jpayne@68: params.append((name, val)) jpayne@68: params = utils.decode_params(params) jpayne@68: return params jpayne@68: jpayne@68: def get_params(self, failobj=None, header='content-type', unquote=True): jpayne@68: """Return the message's Content-Type parameters, as a list. jpayne@68: jpayne@68: The elements of the returned list are 2-tuples of key/value pairs, as jpayne@68: split on the `=' sign. The left hand side of the `=' is the key, jpayne@68: while the right hand side is the value. If there is no `=' sign in jpayne@68: the parameter the value is the empty string. The value is as jpayne@68: described in the get_param() method. jpayne@68: jpayne@68: Optional failobj is the object to return if there is no Content-Type jpayne@68: header. Optional header is the header to search instead of jpayne@68: Content-Type. If unquote is True, the value is unquoted. jpayne@68: """ jpayne@68: missing = object() jpayne@68: params = self._get_params_preserve(missing, header) jpayne@68: if params is missing: jpayne@68: return failobj jpayne@68: if unquote: jpayne@68: return [(k, _unquotevalue(v)) for k, v in params] jpayne@68: else: jpayne@68: return params jpayne@68: jpayne@68: def get_param(self, param, failobj=None, header='content-type', jpayne@68: unquote=True): jpayne@68: """Return the parameter value if found in the Content-Type header. jpayne@68: jpayne@68: Optional failobj is the object to return if there is no Content-Type jpayne@68: header, or the Content-Type header has no such parameter. Optional jpayne@68: header is the header to search instead of Content-Type. jpayne@68: jpayne@68: Parameter keys are always compared case insensitively. The return jpayne@68: value can either be a string, or a 3-tuple if the parameter was RFC jpayne@68: 2231 encoded. When it's a 3-tuple, the elements of the value are of jpayne@68: the form (CHARSET, LANGUAGE, VALUE). Note that both CHARSET and jpayne@68: LANGUAGE can be None, in which case you should consider VALUE to be jpayne@68: encoded in the us-ascii charset. You can usually ignore LANGUAGE. jpayne@68: The parameter value (either the returned string, or the VALUE item in jpayne@68: the 3-tuple) is always unquoted, unless unquote is set to False. jpayne@68: jpayne@68: If your application doesn't care whether the parameter was RFC 2231 jpayne@68: encoded, it can turn the return value into a string as follows: jpayne@68: jpayne@68: rawparam = msg.get_param('foo') jpayne@68: param = email.utils.collapse_rfc2231_value(rawparam) jpayne@68: jpayne@68: """ jpayne@68: if header not in self: jpayne@68: return failobj jpayne@68: for k, v in self._get_params_preserve(failobj, header): jpayne@68: if k.lower() == param.lower(): jpayne@68: if unquote: jpayne@68: return _unquotevalue(v) jpayne@68: else: jpayne@68: return v jpayne@68: return failobj jpayne@68: jpayne@68: def set_param(self, param, value, header='Content-Type', requote=True, jpayne@68: charset=None, language='', replace=False): jpayne@68: """Set a parameter in the Content-Type header. jpayne@68: jpayne@68: If the parameter already exists in the header, its value will be jpayne@68: replaced with the new value. jpayne@68: jpayne@68: If header is Content-Type and has not yet been defined for this jpayne@68: message, it will be set to "text/plain" and the new parameter and jpayne@68: value will be appended as per RFC 2045. jpayne@68: jpayne@68: An alternate header can be specified in the header argument, and all jpayne@68: parameters will be quoted as necessary unless requote is False. jpayne@68: jpayne@68: If charset is specified, the parameter will be encoded according to RFC jpayne@68: 2231. Optional language specifies the RFC 2231 language, defaulting jpayne@68: to the empty string. Both charset and language should be strings. jpayne@68: """ jpayne@68: if not isinstance(value, tuple) and charset: jpayne@68: value = (charset, language, value) jpayne@68: jpayne@68: if header not in self and header.lower() == 'content-type': jpayne@68: ctype = 'text/plain' jpayne@68: else: jpayne@68: ctype = self.get(header) jpayne@68: if not self.get_param(param, header=header): jpayne@68: if not ctype: jpayne@68: ctype = _formatparam(param, value, requote) jpayne@68: else: jpayne@68: ctype = SEMISPACE.join( jpayne@68: [ctype, _formatparam(param, value, requote)]) jpayne@68: else: jpayne@68: ctype = '' jpayne@68: for old_param, old_value in self.get_params(header=header, jpayne@68: unquote=requote): jpayne@68: append_param = '' jpayne@68: if old_param.lower() == param.lower(): jpayne@68: append_param = _formatparam(param, value, requote) jpayne@68: else: jpayne@68: append_param = _formatparam(old_param, old_value, requote) jpayne@68: if not ctype: jpayne@68: ctype = append_param jpayne@68: else: jpayne@68: ctype = SEMISPACE.join([ctype, append_param]) jpayne@68: if ctype != self.get(header): jpayne@68: if replace: jpayne@68: self.replace_header(header, ctype) jpayne@68: else: jpayne@68: del self[header] jpayne@68: self[header] = ctype jpayne@68: jpayne@68: def del_param(self, param, header='content-type', requote=True): jpayne@68: """Remove the given parameter completely from the Content-Type header. jpayne@68: jpayne@68: The header will be re-written in place without the parameter or its jpayne@68: value. All values will be quoted as necessary unless requote is jpayne@68: False. Optional header specifies an alternative to the Content-Type jpayne@68: header. jpayne@68: """ jpayne@68: if header not in self: jpayne@68: return jpayne@68: new_ctype = '' jpayne@68: for p, v in self.get_params(header=header, unquote=requote): jpayne@68: if p.lower() != param.lower(): jpayne@68: if not new_ctype: jpayne@68: new_ctype = _formatparam(p, v, requote) jpayne@68: else: jpayne@68: new_ctype = SEMISPACE.join([new_ctype, jpayne@68: _formatparam(p, v, requote)]) jpayne@68: if new_ctype != self.get(header): jpayne@68: del self[header] jpayne@68: self[header] = new_ctype jpayne@68: jpayne@68: def set_type(self, type, header='Content-Type', requote=True): jpayne@68: """Set the main type and subtype for the Content-Type header. jpayne@68: jpayne@68: type must be a string in the form "maintype/subtype", otherwise a jpayne@68: ValueError is raised. jpayne@68: jpayne@68: This method replaces the Content-Type header, keeping all the jpayne@68: parameters in place. If requote is False, this leaves the existing jpayne@68: header's quoting as is. Otherwise, the parameters will be quoted (the jpayne@68: default). jpayne@68: jpayne@68: An alternative header can be specified in the header argument. When jpayne@68: the Content-Type header is set, we'll always also add a MIME-Version jpayne@68: header. jpayne@68: """ jpayne@68: # BAW: should we be strict? jpayne@68: if not type.count('/') == 1: jpayne@68: raise ValueError jpayne@68: # Set the Content-Type, you get a MIME-Version jpayne@68: if header.lower() == 'content-type': jpayne@68: del self['mime-version'] jpayne@68: self['MIME-Version'] = '1.0' jpayne@68: if header not in self: jpayne@68: self[header] = type jpayne@68: return jpayne@68: params = self.get_params(header=header, unquote=requote) jpayne@68: del self[header] jpayne@68: self[header] = type jpayne@68: # Skip the first param; it's the old type. jpayne@68: for p, v in params[1:]: jpayne@68: self.set_param(p, v, header, requote) jpayne@68: jpayne@68: def get_filename(self, failobj=None): jpayne@68: """Return the filename associated with the payload if present. jpayne@68: jpayne@68: The filename is extracted from the Content-Disposition header's jpayne@68: `filename' parameter, and it is unquoted. If that header is missing jpayne@68: the `filename' parameter, this method falls back to looking for the jpayne@68: `name' parameter. jpayne@68: """ jpayne@68: missing = object() jpayne@68: filename = self.get_param('filename', missing, 'content-disposition') jpayne@68: if filename is missing: jpayne@68: filename = self.get_param('name', missing, 'content-type') jpayne@68: if filename is missing: jpayne@68: return failobj jpayne@68: return utils.collapse_rfc2231_value(filename).strip() jpayne@68: jpayne@68: def get_boundary(self, failobj=None): jpayne@68: """Return the boundary associated with the payload if present. jpayne@68: jpayne@68: The boundary is extracted from the Content-Type header's `boundary' jpayne@68: parameter, and it is unquoted. jpayne@68: """ jpayne@68: missing = object() jpayne@68: boundary = self.get_param('boundary', missing) jpayne@68: if boundary is missing: jpayne@68: return failobj jpayne@68: # RFC 2046 says that boundaries may begin but not end in w/s jpayne@68: return utils.collapse_rfc2231_value(boundary).rstrip() jpayne@68: jpayne@68: def set_boundary(self, boundary): jpayne@68: """Set the boundary parameter in Content-Type to 'boundary'. jpayne@68: jpayne@68: This is subtly different than deleting the Content-Type header and jpayne@68: adding a new one with a new boundary parameter via add_header(). The jpayne@68: main difference is that using the set_boundary() method preserves the jpayne@68: order of the Content-Type header in the original message. jpayne@68: jpayne@68: HeaderParseError is raised if the message has no Content-Type header. jpayne@68: """ jpayne@68: missing = object() jpayne@68: params = self._get_params_preserve(missing, 'content-type') jpayne@68: if params is missing: jpayne@68: # There was no Content-Type header, and we don't know what type jpayne@68: # to set it to, so raise an exception. jpayne@68: raise errors.HeaderParseError('No Content-Type header found') jpayne@68: newparams = [] jpayne@68: foundp = False jpayne@68: for pk, pv in params: jpayne@68: if pk.lower() == 'boundary': jpayne@68: newparams.append(('boundary', '"%s"' % boundary)) jpayne@68: foundp = True jpayne@68: else: jpayne@68: newparams.append((pk, pv)) jpayne@68: if not foundp: jpayne@68: # The original Content-Type header had no boundary attribute. jpayne@68: # Tack one on the end. BAW: should we raise an exception jpayne@68: # instead??? jpayne@68: newparams.append(('boundary', '"%s"' % boundary)) jpayne@68: # Replace the existing Content-Type header with the new value jpayne@68: newheaders = [] jpayne@68: for h, v in self._headers: jpayne@68: if h.lower() == 'content-type': jpayne@68: parts = [] jpayne@68: for k, v in newparams: jpayne@68: if v == '': jpayne@68: parts.append(k) jpayne@68: else: jpayne@68: parts.append('%s=%s' % (k, v)) jpayne@68: val = SEMISPACE.join(parts) jpayne@68: newheaders.append(self.policy.header_store_parse(h, val)) jpayne@68: jpayne@68: else: jpayne@68: newheaders.append((h, v)) jpayne@68: self._headers = newheaders jpayne@68: jpayne@68: def get_content_charset(self, failobj=None): jpayne@68: """Return the charset parameter of the Content-Type header. jpayne@68: jpayne@68: The returned string is always coerced to lower case. If there is no jpayne@68: Content-Type header, or if that header has no charset parameter, jpayne@68: failobj is returned. jpayne@68: """ jpayne@68: missing = object() jpayne@68: charset = self.get_param('charset', missing) jpayne@68: if charset is missing: jpayne@68: return failobj jpayne@68: if isinstance(charset, tuple): jpayne@68: # RFC 2231 encoded, so decode it, and it better end up as ascii. jpayne@68: pcharset = charset[0] or 'us-ascii' jpayne@68: try: jpayne@68: # LookupError will be raised if the charset isn't known to jpayne@68: # Python. UnicodeError will be raised if the encoded text jpayne@68: # contains a character not in the charset. jpayne@68: as_bytes = charset[2].encode('raw-unicode-escape') jpayne@68: charset = str(as_bytes, pcharset) jpayne@68: except (LookupError, UnicodeError): jpayne@68: charset = charset[2] jpayne@68: # charset characters must be in us-ascii range jpayne@68: try: jpayne@68: charset.encode('us-ascii') jpayne@68: except UnicodeError: jpayne@68: return failobj jpayne@68: # RFC 2046, $4.1.2 says charsets are not case sensitive jpayne@68: return charset.lower() jpayne@68: jpayne@68: def get_charsets(self, failobj=None): jpayne@68: """Return a list containing the charset(s) used in this message. jpayne@68: jpayne@68: The returned list of items describes the Content-Type headers' jpayne@68: charset parameter for this message and all the subparts in its jpayne@68: payload. jpayne@68: jpayne@68: Each item will either be a string (the value of the charset parameter jpayne@68: in the Content-Type header of that part) or the value of the jpayne@68: 'failobj' parameter (defaults to None), if the part does not have a jpayne@68: main MIME type of "text", or the charset is not defined. jpayne@68: jpayne@68: The list will contain one string for each part of the message, plus jpayne@68: one for the container message (i.e. self), so that a non-multipart jpayne@68: message will still return a list of length 1. jpayne@68: """ jpayne@68: return [part.get_content_charset(failobj) for part in self.walk()] jpayne@68: jpayne@68: def get_content_disposition(self): jpayne@68: """Return the message's content-disposition if it exists, or None. jpayne@68: jpayne@68: The return values can be either 'inline', 'attachment' or None jpayne@68: according to the rfc2183. jpayne@68: """ jpayne@68: value = self.get('content-disposition') jpayne@68: if value is None: jpayne@68: return None jpayne@68: c_d = _splitparam(value)[0].lower() jpayne@68: return c_d jpayne@68: jpayne@68: # I.e. def walk(self): ... jpayne@68: from email.iterators import walk jpayne@68: jpayne@68: jpayne@68: class MIMEPart(Message): jpayne@68: jpayne@68: def __init__(self, policy=None): jpayne@68: if policy is None: jpayne@68: from email.policy import default jpayne@68: policy = default jpayne@68: Message.__init__(self, policy) jpayne@68: jpayne@68: jpayne@68: def as_string(self, unixfrom=False, maxheaderlen=None, policy=None): jpayne@68: """Return the entire formatted message as a string. jpayne@68: jpayne@68: Optional 'unixfrom', when true, means include the Unix From_ envelope jpayne@68: header. maxheaderlen is retained for backward compatibility with the jpayne@68: base Message class, but defaults to None, meaning that the policy value jpayne@68: for max_line_length controls the header maximum length. 'policy' is jpayne@68: passed to the Generator instance used to serialize the mesasge; if it jpayne@68: is not specified the policy associated with the message instance is jpayne@68: used. jpayne@68: """ jpayne@68: policy = self.policy if policy is None else policy jpayne@68: if maxheaderlen is None: jpayne@68: maxheaderlen = policy.max_line_length jpayne@68: return super().as_string(maxheaderlen=maxheaderlen, policy=policy) jpayne@68: jpayne@68: def __str__(self): jpayne@68: return self.as_string(policy=self.policy.clone(utf8=True)) jpayne@68: jpayne@68: def is_attachment(self): jpayne@68: c_d = self.get('content-disposition') jpayne@68: return False if c_d is None else c_d.content_disposition == 'attachment' jpayne@68: jpayne@68: def _find_body(self, part, preferencelist): jpayne@68: if part.is_attachment(): jpayne@68: return jpayne@68: maintype, subtype = part.get_content_type().split('/') jpayne@68: if maintype == 'text': jpayne@68: if subtype in preferencelist: jpayne@68: yield (preferencelist.index(subtype), part) jpayne@68: return jpayne@68: if maintype != 'multipart': jpayne@68: return jpayne@68: if subtype != 'related': jpayne@68: for subpart in part.iter_parts(): jpayne@68: yield from self._find_body(subpart, preferencelist) jpayne@68: return jpayne@68: if 'related' in preferencelist: jpayne@68: yield (preferencelist.index('related'), part) jpayne@68: candidate = None jpayne@68: start = part.get_param('start') jpayne@68: if start: jpayne@68: for subpart in part.iter_parts(): jpayne@68: if subpart['content-id'] == start: jpayne@68: candidate = subpart jpayne@68: break jpayne@68: if candidate is None: jpayne@68: subparts = part.get_payload() jpayne@68: candidate = subparts[0] if subparts else None jpayne@68: if candidate is not None: jpayne@68: yield from self._find_body(candidate, preferencelist) jpayne@68: jpayne@68: def get_body(self, preferencelist=('related', 'html', 'plain')): jpayne@68: """Return best candidate mime part for display as 'body' of message. jpayne@68: jpayne@68: Do a depth first search, starting with self, looking for the first part jpayne@68: matching each of the items in preferencelist, and return the part jpayne@68: corresponding to the first item that has a match, or None if no items jpayne@68: have a match. If 'related' is not included in preferencelist, consider jpayne@68: the root part of any multipart/related encountered as a candidate jpayne@68: match. Ignore parts with 'Content-Disposition: attachment'. jpayne@68: """ jpayne@68: best_prio = len(preferencelist) jpayne@68: body = None jpayne@68: for prio, part in self._find_body(self, preferencelist): jpayne@68: if prio < best_prio: jpayne@68: best_prio = prio jpayne@68: body = part jpayne@68: if prio == 0: jpayne@68: break jpayne@68: return body jpayne@68: jpayne@68: _body_types = {('text', 'plain'), jpayne@68: ('text', 'html'), jpayne@68: ('multipart', 'related'), jpayne@68: ('multipart', 'alternative')} jpayne@68: def iter_attachments(self): jpayne@68: """Return an iterator over the non-main parts of a multipart. jpayne@68: jpayne@68: Skip the first of each occurrence of text/plain, text/html, jpayne@68: multipart/related, or multipart/alternative in the multipart (unless jpayne@68: they have a 'Content-Disposition: attachment' header) and include all jpayne@68: remaining subparts in the returned iterator. When applied to a jpayne@68: multipart/related, return all parts except the root part. Return an jpayne@68: empty iterator when applied to a multipart/alternative or a jpayne@68: non-multipart. jpayne@68: """ jpayne@68: maintype, subtype = self.get_content_type().split('/') jpayne@68: if maintype != 'multipart' or subtype == 'alternative': jpayne@68: return jpayne@68: payload = self.get_payload() jpayne@68: # Certain malformed messages can have content type set to `multipart/*` jpayne@68: # but still have single part body, in which case payload.copy() can jpayne@68: # fail with AttributeError. jpayne@68: try: jpayne@68: parts = payload.copy() jpayne@68: except AttributeError: jpayne@68: # payload is not a list, it is most probably a string. jpayne@68: return jpayne@68: jpayne@68: if maintype == 'multipart' and subtype == 'related': jpayne@68: # For related, we treat everything but the root as an attachment. jpayne@68: # The root may be indicated by 'start'; if there's no start or we jpayne@68: # can't find the named start, treat the first subpart as the root. jpayne@68: start = self.get_param('start') jpayne@68: if start: jpayne@68: found = False jpayne@68: attachments = [] jpayne@68: for part in parts: jpayne@68: if part.get('content-id') == start: jpayne@68: found = True jpayne@68: else: jpayne@68: attachments.append(part) jpayne@68: if found: jpayne@68: yield from attachments jpayne@68: return jpayne@68: parts.pop(0) jpayne@68: yield from parts jpayne@68: return jpayne@68: # Otherwise we more or less invert the remaining logic in get_body. jpayne@68: # This only really works in edge cases (ex: non-text related or jpayne@68: # alternatives) if the sending agent sets content-disposition. jpayne@68: seen = [] # Only skip the first example of each candidate type. jpayne@68: for part in parts: jpayne@68: maintype, subtype = part.get_content_type().split('/') jpayne@68: if ((maintype, subtype) in self._body_types and jpayne@68: not part.is_attachment() and subtype not in seen): jpayne@68: seen.append(subtype) jpayne@68: continue jpayne@68: yield part jpayne@68: jpayne@68: def iter_parts(self): jpayne@68: """Return an iterator over all immediate subparts of a multipart. jpayne@68: jpayne@68: Return an empty iterator for a non-multipart. jpayne@68: """ jpayne@68: if self.get_content_maintype() == 'multipart': jpayne@68: yield from self.get_payload() jpayne@68: jpayne@68: def get_content(self, *args, content_manager=None, **kw): jpayne@68: if content_manager is None: jpayne@68: content_manager = self.policy.content_manager jpayne@68: return content_manager.get_content(self, *args, **kw) jpayne@68: jpayne@68: def set_content(self, *args, content_manager=None, **kw): jpayne@68: if content_manager is None: jpayne@68: content_manager = self.policy.content_manager jpayne@68: content_manager.set_content(self, *args, **kw) jpayne@68: jpayne@68: def _make_multipart(self, subtype, disallowed_subtypes, boundary): jpayne@68: if self.get_content_maintype() == 'multipart': jpayne@68: existing_subtype = self.get_content_subtype() jpayne@68: disallowed_subtypes = disallowed_subtypes + (subtype,) jpayne@68: if existing_subtype in disallowed_subtypes: jpayne@68: raise ValueError("Cannot convert {} to {}".format( jpayne@68: existing_subtype, subtype)) jpayne@68: keep_headers = [] jpayne@68: part_headers = [] jpayne@68: for name, value in self._headers: jpayne@68: if name.lower().startswith('content-'): jpayne@68: part_headers.append((name, value)) jpayne@68: else: jpayne@68: keep_headers.append((name, value)) jpayne@68: if part_headers: jpayne@68: # There is existing content, move it to the first subpart. jpayne@68: part = type(self)(policy=self.policy) jpayne@68: part._headers = part_headers jpayne@68: part._payload = self._payload jpayne@68: self._payload = [part] jpayne@68: else: jpayne@68: self._payload = [] jpayne@68: self._headers = keep_headers jpayne@68: self['Content-Type'] = 'multipart/' + subtype jpayne@68: if boundary is not None: jpayne@68: self.set_param('boundary', boundary) jpayne@68: jpayne@68: def make_related(self, boundary=None): jpayne@68: self._make_multipart('related', ('alternative', 'mixed'), boundary) jpayne@68: jpayne@68: def make_alternative(self, boundary=None): jpayne@68: self._make_multipart('alternative', ('mixed',), boundary) jpayne@68: jpayne@68: def make_mixed(self, boundary=None): jpayne@68: self._make_multipart('mixed', (), boundary) jpayne@68: jpayne@68: def _add_multipart(self, _subtype, *args, _disp=None, **kw): jpayne@68: if (self.get_content_maintype() != 'multipart' or jpayne@68: self.get_content_subtype() != _subtype): jpayne@68: getattr(self, 'make_' + _subtype)() jpayne@68: part = type(self)(policy=self.policy) jpayne@68: part.set_content(*args, **kw) jpayne@68: if _disp and 'content-disposition' not in part: jpayne@68: part['Content-Disposition'] = _disp jpayne@68: self.attach(part) jpayne@68: jpayne@68: def add_related(self, *args, **kw): jpayne@68: self._add_multipart('related', *args, _disp='inline', **kw) jpayne@68: jpayne@68: def add_alternative(self, *args, **kw): jpayne@68: self._add_multipart('alternative', *args, **kw) jpayne@68: jpayne@68: def add_attachment(self, *args, **kw): jpayne@68: self._add_multipart('mixed', *args, _disp='attachment', **kw) jpayne@68: jpayne@68: def clear(self): jpayne@68: self._headers = [] jpayne@68: self._payload = None jpayne@68: jpayne@68: def clear_content(self): jpayne@68: self._headers = [(n, v) for n, v in self._headers jpayne@68: if not n.lower().startswith('content-')] jpayne@68: self._payload = None jpayne@68: jpayne@68: jpayne@68: class EmailMessage(MIMEPart): jpayne@68: jpayne@68: def set_content(self, *args, **kw): jpayne@68: super().set_content(*args, **kw) jpayne@68: if 'MIME-Version' not in self: jpayne@68: self['MIME-Version'] = '1.0'