blob: ebaf1c14307b759fac5e3aaaa5359300b5d4b322 [file] [log] [blame]
Guido van Rossum8b3febe2007-08-30 01:15:14 +00001# Copyright (C) 2001-2007 Python Software Foundation
2# Author: Barry Warsaw
3# Contact: email-sig@python.org
4
5"""Basic message object for the email package object model."""
6
7__all__ = ['Message']
8
9import re
10import uu
Barry Warsaw8b2af272007-08-31 03:04:26 +000011import base64
Guido van Rossum8b3febe2007-08-30 01:15:14 +000012import binascii
Guido van Rossum8b3febe2007-08-30 01:15:14 +000013from io import BytesIO, StringIO
14
15# Intrapackage imports
Guido van Rossum8b3febe2007-08-30 01:15:14 +000016from email import utils
17from email import errors
R David Murrayc27e5222012-05-25 15:01:48 -040018from email._policybase import compat32
R. David Murray92532142011-01-07 23:25:30 +000019from email import charset as _charset
R David Murray80e0aee2012-05-27 21:23:34 -040020from email._encoded_words import decode_b
R. David Murray92532142011-01-07 23:25:30 +000021Charset = _charset.Charset
Guido van Rossum8b3febe2007-08-30 01:15:14 +000022
23SEMISPACE = '; '
24
Guido van Rossum8b3febe2007-08-30 01:15:14 +000025# Regular expression that matches `special' characters in parameters, the
Mark Dickinson934896d2009-02-21 20:59:32 +000026# existence of which force quoting of the parameter value.
Guido van Rossum8b3febe2007-08-30 01:15:14 +000027tspecials = re.compile(r'[ \(\)<>@,;:\\"/\[\]\?=]')
28
R. David Murray96fd54e2010-10-08 15:55:28 +000029
Benjamin Peterson4cd6a952008-08-17 20:23:46 +000030def _splitparam(param):
31 # Split header parameters. BAW: this may be too simple. It isn't
32 # strictly RFC 2045 (section 5.1) compliant, but it catches most headers
R David Murraya2150232011-03-16 21:11:23 -040033 # found in the wild. We may eventually need a full fledged parser.
34 # RDM: we might have a Header here; for now just stringify it.
35 a, sep, b = str(param).partition(';')
Benjamin Peterson4cd6a952008-08-17 20:23:46 +000036 if not sep:
37 return a.strip(), None
38 return a.strip(), b.strip()
39
Guido van Rossum8b3febe2007-08-30 01:15:14 +000040def _formatparam(param, value=None, quote=True):
41 """Convenience function to format and return a key=value pair.
42
R. David Murray7ec754b2010-12-13 23:51:19 +000043 This will quote the value if needed or if quote is true. If value is a
44 three tuple (charset, language, value), it will be encoded according
45 to RFC2231 rules. If it contains non-ascii characters it will likewise
46 be encoded according to RFC2231 rules, using the utf-8 charset and
47 a null language.
Guido van Rossum8b3febe2007-08-30 01:15:14 +000048 """
49 if value is not None and len(value) > 0:
50 # A tuple is used for RFC 2231 encoded parameter values where items
51 # are (charset, language, value). charset is a string, not a Charset
R. David Murraydfd7eb02010-12-24 22:36:49 +000052 # instance. RFC 2231 encoded values are never quoted, per RFC.
Guido van Rossum8b3febe2007-08-30 01:15:14 +000053 if isinstance(value, tuple):
54 # Encode as per RFC 2231
55 param += '*'
56 value = utils.encode_rfc2231(value[2], value[0], value[1])
R. David Murraydfd7eb02010-12-24 22:36:49 +000057 return '%s=%s' % (param, value)
R. David Murray7ec754b2010-12-13 23:51:19 +000058 else:
59 try:
60 value.encode('ascii')
61 except UnicodeEncodeError:
62 param += '*'
63 value = utils.encode_rfc2231(value, 'utf-8', '')
R. David Murraydfd7eb02010-12-24 22:36:49 +000064 return '%s=%s' % (param, value)
Guido van Rossum8b3febe2007-08-30 01:15:14 +000065 # BAW: Please check this. I think that if quote is set it should
66 # force quoting even if not necessary.
67 if quote or tspecials.search(value):
68 return '%s="%s"' % (param, utils.quote(value))
69 else:
70 return '%s=%s' % (param, value)
71 else:
72 return param
73
74def _parseparam(s):
R David Murraya2150232011-03-16 21:11:23 -040075 # RDM This might be a Header, so for now stringify it.
76 s = ';' + str(s)
Guido van Rossum8b3febe2007-08-30 01:15:14 +000077 plist = []
78 while s[:1] == ';':
79 s = s[1:]
80 end = s.find(';')
R. David Murrayd48739f2010-04-14 18:59:18 +000081 while end > 0 and (s.count('"', 0, end) - s.count('\\"', 0, end)) % 2:
Guido van Rossum8b3febe2007-08-30 01:15:14 +000082 end = s.find(';', end + 1)
83 if end < 0:
84 end = len(s)
85 f = s[:end]
86 if '=' in f:
87 i = f.index('=')
88 f = f[:i].strip().lower() + '=' + f[i+1:].strip()
89 plist.append(f.strip())
90 s = s[end:]
91 return plist
92
93
94def _unquotevalue(value):
95 # This is different than utils.collapse_rfc2231_value() because it doesn't
96 # try to convert the value to a unicode. Message.get_param() and
97 # Message.get_params() are both currently defined to return the tuple in
98 # the face of RFC 2231 parameters.
99 if isinstance(value, tuple):
100 return value[0], value[1], utils.unquote(value[2])
101 else:
102 return utils.unquote(value)
103
104
105
106class Message:
107 """Basic message object.
108
109 A message object is defined as something that has a bunch of RFC 2822
110 headers and a payload. It may optionally have an envelope header
111 (a.k.a. Unix-From or From_ header). If the message is a container (i.e. a
112 multipart or a message/rfc822), then the payload is a list of Message
113 objects, otherwise it is a string.
114
115 Message objects implement part of the `mapping' interface, which assumes
R. David Murrayd2c310f2010-10-01 02:08:02 +0000116 there is exactly one occurrence of the header per message. Some headers
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000117 do in fact appear multiple times (e.g. Received) and for those headers,
118 you must use the explicit API to set or get all the headers. Not all of
119 the mapping methods are implemented.
120 """
R David Murrayc27e5222012-05-25 15:01:48 -0400121 def __init__(self, policy=compat32):
122 self.policy = policy
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000123 self._headers = []
124 self._unixfrom = None
125 self._payload = None
126 self._charset = None
127 # Defaults for multipart messages
128 self.preamble = self.epilogue = None
129 self.defects = []
130 # Default content type
131 self._default_type = 'text/plain'
132
133 def __str__(self):
134 """Return the entire formatted message as a string.
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000135 """
136 return self.as_string()
137
R David Murraybb17d2b2013-08-09 16:15:28 -0400138 def as_string(self, unixfrom=False, maxheaderlen=0, policy=None):
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000139 """Return the entire formatted message as a string.
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000140
R David Murraybb17d2b2013-08-09 16:15:28 -0400141 Optional 'unixfrom', when true, means include the Unix From_ envelope
142 header. For backward compatibility reasons, if maxheaderlen is
143 not specified it defaults to 0, so you must override it explicitly
144 if you want a different maxheaderlen. 'policy' is passed to the
145 Generator instance used to serialize the mesasge; if it is not
146 specified the policy associated with the message instance is used.
147
148 If the message object contains binary data that is not encoded
149 according to RFC standards, the non-compliant data will be replaced by
150 unicode "unknown character" code points.
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000151 """
152 from email.generator import Generator
R David Murraybb17d2b2013-08-09 16:15:28 -0400153 policy = self.policy if policy is None else policy
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000154 fp = StringIO()
R David Murraybb17d2b2013-08-09 16:15:28 -0400155 g = Generator(fp,
156 mangle_from_=False,
157 maxheaderlen=maxheaderlen,
158 policy=policy)
159 g.flatten(self, unixfrom=unixfrom)
160 return fp.getvalue()
161
162 def __bytes__(self):
163 """Return the entire formatted message as a bytes object.
164 """
165 return self.as_bytes()
166
167 def as_bytes(self, unixfrom=False, policy=None):
168 """Return the entire formatted message as a bytes object.
169
170 Optional 'unixfrom', when true, means include the Unix From_ envelope
171 header. 'policy' is passed to the BytesGenerator instance used to
172 serialize the message; if not specified the policy associated with
173 the message instance is used.
174 """
175 from email.generator import BytesGenerator
176 policy = self.policy if policy is None else policy
177 fp = BytesIO()
178 g = BytesGenerator(fp, mangle_from_=False, policy=policy)
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000179 g.flatten(self, unixfrom=unixfrom)
180 return fp.getvalue()
181
182 def is_multipart(self):
183 """Return True if the message consists of multiple parts."""
184 return isinstance(self._payload, list)
185
186 #
187 # Unix From_ line
188 #
189 def set_unixfrom(self, unixfrom):
190 self._unixfrom = unixfrom
191
192 def get_unixfrom(self):
193 return self._unixfrom
194
195 #
196 # Payload manipulation.
197 #
198 def attach(self, payload):
199 """Add the given payload to the current payload.
200
201 The current payload will always be a list of objects after this method
202 is called. If you want to set the payload to a scalar object, use
203 set_payload() instead.
204 """
205 if self._payload is None:
206 self._payload = [payload]
207 else:
208 self._payload.append(payload)
209
210 def get_payload(self, i=None, decode=False):
211 """Return a reference to the payload.
212
213 The payload will either be a list object or a string. If you mutate
214 the list object, you modify the message's payload in place. Optional
215 i returns that index into the payload.
216
217 Optional decode is a flag indicating whether the payload should be
218 decoded or not, according to the Content-Transfer-Encoding header
219 (default is False).
220
221 When True and the message is not a multipart, the payload will be
222 decoded if this header's value is `quoted-printable' or `base64'. If
223 some other encoding is used, or the header is missing, or if the
224 payload has bogus data (i.e. bogus base64 or uuencoded data), the
225 payload is returned as-is.
226
227 If the message is a multipart and the decode flag is True, then None
228 is returned.
229 """
R. David Murray96fd54e2010-10-08 15:55:28 +0000230 # Here is the logic table for this code, based on the email5.0.0 code:
231 # i decode is_multipart result
232 # ------ ------ ------------ ------------------------------
233 # None True True None
234 # i True True None
235 # None False True _payload (a list)
236 # i False True _payload element i (a Message)
237 # i False False error (not a list)
238 # i True False error (not a list)
239 # None False False _payload
240 # None True False _payload decoded (bytes)
241 # Note that Barry planned to factor out the 'decode' case, but that
242 # isn't so easy now that we handle the 8 bit data, which needs to be
243 # converted in both the decode and non-decode path.
244 if self.is_multipart():
245 if decode:
246 return None
247 if i is None:
248 return self._payload
249 else:
250 return self._payload[i]
251 # For backward compatibility, Use isinstance and this error message
252 # instead of the more logical is_multipart test.
253 if i is not None and not isinstance(self._payload, list):
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000254 raise TypeError('Expected list, got %s' % type(self._payload))
R. David Murray96fd54e2010-10-08 15:55:28 +0000255 payload = self._payload
R David Murraya2150232011-03-16 21:11:23 -0400256 # cte might be a Header, so for now stringify it.
257 cte = str(self.get('content-transfer-encoding', '')).lower()
R David Murray106f8e32011-03-15 12:48:41 -0400258 # payload may be bytes here.
R. David Murray96fd54e2010-10-08 15:55:28 +0000259 if isinstance(payload, str):
R David Murrayc27e5222012-05-25 15:01:48 -0400260 if utils._has_surrogates(payload):
R. David Murray96fd54e2010-10-08 15:55:28 +0000261 bpayload = payload.encode('ascii', 'surrogateescape')
262 if not decode:
263 try:
264 payload = bpayload.decode(self.get_param('charset', 'ascii'), 'replace')
265 except LookupError:
266 payload = bpayload.decode('ascii', 'replace')
267 elif decode:
268 try:
269 bpayload = payload.encode('ascii')
270 except UnicodeError:
271 # This won't happen for RFC compliant messages (messages
272 # containing only ASCII codepoints in the unicode input).
273 # If it does happen, turn the string into bytes in a way
274 # guaranteed not to fail.
275 bpayload = payload.encode('raw-unicode-escape')
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000276 if not decode:
277 return payload
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000278 if cte == 'quoted-printable':
R. David Murray96fd54e2010-10-08 15:55:28 +0000279 return utils._qdecode(bpayload)
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000280 elif cte == 'base64':
R David Murray80e0aee2012-05-27 21:23:34 -0400281 # XXX: this is a bit of a hack; decode_b should probably be factored
282 # out somewhere, but I haven't figured out where yet.
283 value, defects = decode_b(b''.join(bpayload.splitlines()))
284 for defect in defects:
285 self.policy.handle_defect(self, defect)
286 return value
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000287 elif cte in ('x-uuencode', 'uuencode', 'uue', 'x-uue'):
R. David Murray96fd54e2010-10-08 15:55:28 +0000288 in_file = BytesIO(bpayload)
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000289 out_file = BytesIO()
290 try:
291 uu.decode(in_file, out_file, quiet=True)
292 return out_file.getvalue()
293 except uu.Error:
294 # Some decoding problem
R. David Murray96fd54e2010-10-08 15:55:28 +0000295 return bpayload
Barry Warsaw8b2af272007-08-31 03:04:26 +0000296 if isinstance(payload, str):
R. David Murray96fd54e2010-10-08 15:55:28 +0000297 return bpayload
Barry Warsaw8b2af272007-08-31 03:04:26 +0000298 return payload
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000299
300 def set_payload(self, payload, charset=None):
301 """Set the payload to the given value.
302
303 Optional charset sets the message's default character set. See
304 set_charset() for details.
305 """
R David Murray00ae4352013-08-21 21:10:31 -0400306 if isinstance(payload, bytes):
307 payload = payload.decode('ascii', 'surrogateescape')
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000308 self._payload = payload
309 if charset is not None:
310 self.set_charset(charset)
311
312 def set_charset(self, charset):
313 """Set the charset of the payload to a given character set.
314
315 charset can be a Charset instance, a string naming a character set, or
316 None. If it is a string it will be converted to a Charset instance.
317 If charset is None, the charset parameter will be removed from the
318 Content-Type field. Anything else will generate a TypeError.
319
320 The message will be assumed to be of type text/* encoded with
321 charset.input_charset. It will be converted to charset.output_charset
322 and encoded properly, if needed, when generating the plain text
323 representation of the message. MIME headers (MIME-Version,
324 Content-Type, Content-Transfer-Encoding) will be added as needed.
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000325 """
326 if charset is None:
327 self.del_param('charset')
328 self._charset = None
329 return
Guido van Rossum9604e662007-08-30 03:46:43 +0000330 if not isinstance(charset, Charset):
331 charset = Charset(charset)
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000332 self._charset = charset
333 if 'MIME-Version' not in self:
334 self.add_header('MIME-Version', '1.0')
335 if 'Content-Type' not in self:
336 self.add_header('Content-Type', 'text/plain',
337 charset=charset.get_output_charset())
338 else:
339 self.set_param('charset', charset.get_output_charset())
Guido van Rossum9604e662007-08-30 03:46:43 +0000340 if charset != charset.get_output_charset():
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000341 self._payload = charset.body_encode(self._payload)
342 if 'Content-Transfer-Encoding' not in self:
343 cte = charset.get_body_encoding()
344 try:
345 cte(self)
346 except TypeError:
347 self._payload = charset.body_encode(self._payload)
348 self.add_header('Content-Transfer-Encoding', cte)
349
350 def get_charset(self):
351 """Return the Charset instance associated with the message's payload.
352 """
353 return self._charset
354
355 #
356 # MAPPING INTERFACE (partial)
357 #
358 def __len__(self):
359 """Return the total number of headers, including duplicates."""
360 return len(self._headers)
361
362 def __getitem__(self, name):
363 """Get a header value.
364
365 Return None if the header is missing instead of raising an exception.
366
367 Note that if the header appeared multiple times, exactly which
R. David Murrayd2c310f2010-10-01 02:08:02 +0000368 occurrence gets returned is undefined. Use get_all() to get all
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000369 the values matching a header field name.
370 """
371 return self.get(name)
372
373 def __setitem__(self, name, val):
374 """Set the value of a header.
375
376 Note: this does not overwrite an existing header with the same field
377 name. Use __delitem__() first to delete any existing headers.
378 """
R David Murrayabfc3742012-05-29 09:14:44 -0400379 max_count = self.policy.header_max_count(name)
380 if max_count:
381 lname = name.lower()
382 found = 0
383 for k, v in self._headers:
384 if k.lower() == lname:
385 found += 1
386 if found >= max_count:
387 raise ValueError("There may be at most {} {} headers "
388 "in a message".format(max_count, name))
R David Murrayc27e5222012-05-25 15:01:48 -0400389 self._headers.append(self.policy.header_store_parse(name, val))
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000390
391 def __delitem__(self, name):
392 """Delete all occurrences of a header, if present.
393
394 Does not raise an exception if the header is missing.
395 """
396 name = name.lower()
397 newheaders = []
398 for k, v in self._headers:
399 if k.lower() != name:
400 newheaders.append((k, v))
401 self._headers = newheaders
402
403 def __contains__(self, name):
404 return name.lower() in [k.lower() for k, v in self._headers]
405
406 def __iter__(self):
407 for field, value in self._headers:
408 yield field
409
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000410 def keys(self):
411 """Return a list of all the message's header field names.
412
413 These will be sorted in the order they appeared in the original
414 message, or were added to the message, and may contain duplicates.
415 Any fields deleted and re-inserted are always appended to the header
416 list.
417 """
418 return [k for k, v in self._headers]
419
420 def values(self):
421 """Return a list of all the message's header values.
422
423 These will be sorted in the order they appeared in the original
424 message, or were added to the message, and may contain duplicates.
425 Any fields deleted and re-inserted are always appended to the header
426 list.
427 """
R David Murrayc27e5222012-05-25 15:01:48 -0400428 return [self.policy.header_fetch_parse(k, v)
429 for k, v in self._headers]
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000430
431 def items(self):
432 """Get all the message's header fields and values.
433
434 These will be sorted in the order they appeared in the original
435 message, or were added to the message, and may contain duplicates.
436 Any fields deleted and re-inserted are always appended to the header
437 list.
438 """
R David Murrayc27e5222012-05-25 15:01:48 -0400439 return [(k, self.policy.header_fetch_parse(k, v))
440 for k, v in self._headers]
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000441
442 def get(self, name, failobj=None):
443 """Get a header value.
444
445 Like __getitem__() but return failobj instead of None when the field
446 is missing.
447 """
448 name = name.lower()
449 for k, v in self._headers:
450 if k.lower() == name:
R David Murrayc27e5222012-05-25 15:01:48 -0400451 return self.policy.header_fetch_parse(k, v)
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000452 return failobj
453
454 #
R David Murrayc27e5222012-05-25 15:01:48 -0400455 # "Internal" methods (public API, but only intended for use by a parser
456 # or generator, not normal application code.
457 #
458
459 def set_raw(self, name, value):
460 """Store name and value in the model without modification.
461
462 This is an "internal" API, intended only for use by a parser.
463 """
464 self._headers.append((name, value))
465
466 def raw_items(self):
467 """Return the (name, value) header pairs without modification.
468
469 This is an "internal" API, intended only for use by a generator.
470 """
471 return iter(self._headers.copy())
472
473 #
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000474 # Additional useful stuff
475 #
476
477 def get_all(self, name, failobj=None):
478 """Return a list of all the values for the named field.
479
480 These will be sorted in the order they appeared in the original
481 message, and may contain duplicates. Any fields deleted and
482 re-inserted are always appended to the header list.
483
484 If no such fields exist, failobj is returned (defaults to None).
485 """
486 values = []
487 name = name.lower()
488 for k, v in self._headers:
489 if k.lower() == name:
R David Murrayc27e5222012-05-25 15:01:48 -0400490 values.append(self.policy.header_fetch_parse(k, v))
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000491 if not values:
492 return failobj
493 return values
494
495 def add_header(self, _name, _value, **_params):
496 """Extended header setting.
497
498 name is the header field to add. keyword arguments can be used to set
499 additional parameters for the header field, with underscores converted
500 to dashes. Normally the parameter will be added as key="value" unless
R. David Murray7ec754b2010-12-13 23:51:19 +0000501 value is None, in which case only the key will be added. If a
502 parameter value contains non-ASCII characters it can be specified as a
503 three-tuple of (charset, language, value), in which case it will be
504 encoded according to RFC2231 rules. Otherwise it will be encoded using
505 the utf-8 charset and a language of ''.
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000506
R. David Murray7ec754b2010-12-13 23:51:19 +0000507 Examples:
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000508
509 msg.add_header('content-disposition', 'attachment', filename='bud.gif')
R. David Murray7ec754b2010-12-13 23:51:19 +0000510 msg.add_header('content-disposition', 'attachment',
511 filename=('utf-8', '', Fußballer.ppt'))
512 msg.add_header('content-disposition', 'attachment',
513 filename='Fußballer.ppt'))
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000514 """
515 parts = []
516 for k, v in _params.items():
517 if v is None:
518 parts.append(k.replace('_', '-'))
519 else:
520 parts.append(_formatparam(k.replace('_', '-'), v))
521 if _value is not None:
522 parts.insert(0, _value)
R David Murrayc27e5222012-05-25 15:01:48 -0400523 self[_name] = SEMISPACE.join(parts)
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000524
525 def replace_header(self, _name, _value):
526 """Replace a header.
527
528 Replace the first matching header found in the message, retaining
529 header order and case. If no matching header was found, a KeyError is
530 raised.
531 """
532 _name = _name.lower()
533 for i, (k, v) in zip(range(len(self._headers)), self._headers):
534 if k.lower() == _name:
R David Murrayc27e5222012-05-25 15:01:48 -0400535 self._headers[i] = self.policy.header_store_parse(k, _value)
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000536 break
537 else:
538 raise KeyError(_name)
539
540 #
541 # Use these three methods instead of the three above.
542 #
543
544 def get_content_type(self):
545 """Return the message's content type.
546
547 The returned string is coerced to lower case of the form
548 `maintype/subtype'. If there was no Content-Type header in the
549 message, the default type as given by get_default_type() will be
550 returned. Since according to RFC 2045, messages always have a default
551 type this will always return a value.
552
553 RFC 2045 defines a message's default type to be text/plain unless it
554 appears inside a multipart/digest container, in which case it would be
555 message/rfc822.
556 """
557 missing = object()
558 value = self.get('content-type', missing)
559 if value is missing:
560 # This should have no parameters
561 return self.get_default_type()
Benjamin Peterson4cd6a952008-08-17 20:23:46 +0000562 ctype = _splitparam(value)[0].lower()
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000563 # RFC 2045, section 5.2 says if its invalid, use text/plain
564 if ctype.count('/') != 1:
565 return 'text/plain'
566 return ctype
567
568 def get_content_maintype(self):
569 """Return the message's main content type.
570
571 This is the `maintype' part of the string returned by
572 get_content_type().
573 """
574 ctype = self.get_content_type()
575 return ctype.split('/')[0]
576
577 def get_content_subtype(self):
578 """Returns the message's sub-content type.
579
580 This is the `subtype' part of the string returned by
581 get_content_type().
582 """
583 ctype = self.get_content_type()
584 return ctype.split('/')[1]
585
586 def get_default_type(self):
587 """Return the `default' content type.
588
589 Most messages have a default content type of text/plain, except for
590 messages that are subparts of multipart/digest containers. Such
591 subparts have a default content type of message/rfc822.
592 """
593 return self._default_type
594
595 def set_default_type(self, ctype):
596 """Set the `default' content type.
597
598 ctype should be either "text/plain" or "message/rfc822", although this
599 is not enforced. The default content type is not stored in the
600 Content-Type header.
601 """
602 self._default_type = ctype
603
604 def _get_params_preserve(self, failobj, header):
605 # Like get_params() but preserves the quoting of values. BAW:
606 # should this be part of the public interface?
607 missing = object()
608 value = self.get(header, missing)
609 if value is missing:
610 return failobj
611 params = []
R David Murraya2150232011-03-16 21:11:23 -0400612 for p in _parseparam(value):
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000613 try:
614 name, val = p.split('=', 1)
615 name = name.strip()
616 val = val.strip()
617 except ValueError:
618 # Must have been a bare attribute
619 name = p.strip()
620 val = ''
621 params.append((name, val))
622 params = utils.decode_params(params)
623 return params
624
625 def get_params(self, failobj=None, header='content-type', unquote=True):
626 """Return the message's Content-Type parameters, as a list.
627
628 The elements of the returned list are 2-tuples of key/value pairs, as
629 split on the `=' sign. The left hand side of the `=' is the key,
630 while the right hand side is the value. If there is no `=' sign in
631 the parameter the value is the empty string. The value is as
632 described in the get_param() method.
633
634 Optional failobj is the object to return if there is no Content-Type
635 header. Optional header is the header to search instead of
636 Content-Type. If unquote is True, the value is unquoted.
637 """
638 missing = object()
639 params = self._get_params_preserve(missing, header)
640 if params is missing:
641 return failobj
642 if unquote:
643 return [(k, _unquotevalue(v)) for k, v in params]
644 else:
645 return params
646
647 def get_param(self, param, failobj=None, header='content-type',
648 unquote=True):
649 """Return the parameter value if found in the Content-Type header.
650
651 Optional failobj is the object to return if there is no Content-Type
652 header, or the Content-Type header has no such parameter. Optional
653 header is the header to search instead of Content-Type.
654
655 Parameter keys are always compared case insensitively. The return
656 value can either be a string, or a 3-tuple if the parameter was RFC
657 2231 encoded. When it's a 3-tuple, the elements of the value are of
658 the form (CHARSET, LANGUAGE, VALUE). Note that both CHARSET and
659 LANGUAGE can be None, in which case you should consider VALUE to be
660 encoded in the us-ascii charset. You can usually ignore LANGUAGE.
R David Murray3ac8c782012-06-17 15:26:35 -0400661 The parameter value (either the returned string, or the VALUE item in
662 the 3-tuple) is always unquoted, unless unquote is set to False.
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000663
R David Murray3ac8c782012-06-17 15:26:35 -0400664 If your application doesn't care whether the parameter was RFC 2231
665 encoded, it can turn the return value into a string as follows:
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000666
667 param = msg.get_param('foo')
R David Murray3ac8c782012-06-17 15:26:35 -0400668 param = email.utils.collapse_rfc2231_value(rawparam)
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000669
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000670 """
671 if header not in self:
672 return failobj
673 for k, v in self._get_params_preserve(failobj, header):
674 if k.lower() == param.lower():
675 if unquote:
676 return _unquotevalue(v)
677 else:
678 return v
679 return failobj
680
681 def set_param(self, param, value, header='Content-Type', requote=True,
682 charset=None, language=''):
683 """Set a parameter in the Content-Type header.
684
685 If the parameter already exists in the header, its value will be
686 replaced with the new value.
687
688 If header is Content-Type and has not yet been defined for this
689 message, it will be set to "text/plain" and the new parameter and
690 value will be appended as per RFC 2045.
691
692 An alternate header can specified in the header argument, and all
693 parameters will be quoted as necessary unless requote is False.
694
695 If charset is specified, the parameter will be encoded according to RFC
696 2231. Optional language specifies the RFC 2231 language, defaulting
697 to the empty string. Both charset and language should be strings.
698 """
699 if not isinstance(value, tuple) and charset:
700 value = (charset, language, value)
701
702 if header not in self and header.lower() == 'content-type':
703 ctype = 'text/plain'
704 else:
705 ctype = self.get(header)
706 if not self.get_param(param, header=header):
707 if not ctype:
708 ctype = _formatparam(param, value, requote)
709 else:
710 ctype = SEMISPACE.join(
711 [ctype, _formatparam(param, value, requote)])
712 else:
713 ctype = ''
714 for old_param, old_value in self.get_params(header=header,
715 unquote=requote):
716 append_param = ''
717 if old_param.lower() == param.lower():
718 append_param = _formatparam(param, value, requote)
719 else:
720 append_param = _formatparam(old_param, old_value, requote)
721 if not ctype:
722 ctype = append_param
723 else:
724 ctype = SEMISPACE.join([ctype, append_param])
725 if ctype != self.get(header):
726 del self[header]
727 self[header] = ctype
728
729 def del_param(self, param, header='content-type', requote=True):
730 """Remove the given parameter completely from the Content-Type header.
731
732 The header will be re-written in place without the parameter or its
733 value. All values will be quoted as necessary unless requote is
734 False. Optional header specifies an alternative to the Content-Type
735 header.
736 """
737 if header not in self:
738 return
739 new_ctype = ''
740 for p, v in self.get_params(header=header, unquote=requote):
741 if p.lower() != param.lower():
742 if not new_ctype:
743 new_ctype = _formatparam(p, v, requote)
744 else:
745 new_ctype = SEMISPACE.join([new_ctype,
746 _formatparam(p, v, requote)])
747 if new_ctype != self.get(header):
748 del self[header]
749 self[header] = new_ctype
750
751 def set_type(self, type, header='Content-Type', requote=True):
752 """Set the main type and subtype for the Content-Type header.
753
754 type must be a string in the form "maintype/subtype", otherwise a
755 ValueError is raised.
756
757 This method replaces the Content-Type header, keeping all the
758 parameters in place. If requote is False, this leaves the existing
759 header's quoting as is. Otherwise, the parameters will be quoted (the
760 default).
761
762 An alternative header can be specified in the header argument. When
763 the Content-Type header is set, we'll always also add a MIME-Version
764 header.
765 """
766 # BAW: should we be strict?
767 if not type.count('/') == 1:
768 raise ValueError
769 # Set the Content-Type, you get a MIME-Version
770 if header.lower() == 'content-type':
771 del self['mime-version']
772 self['MIME-Version'] = '1.0'
773 if header not in self:
774 self[header] = type
775 return
776 params = self.get_params(header=header, unquote=requote)
777 del self[header]
778 self[header] = type
779 # Skip the first param; it's the old type.
780 for p, v in params[1:]:
781 self.set_param(p, v, header, requote)
782
783 def get_filename(self, failobj=None):
784 """Return the filename associated with the payload if present.
785
786 The filename is extracted from the Content-Disposition header's
787 `filename' parameter, and it is unquoted. If that header is missing
788 the `filename' parameter, this method falls back to looking for the
789 `name' parameter.
790 """
791 missing = object()
792 filename = self.get_param('filename', missing, 'content-disposition')
793 if filename is missing:
R. David Murraybf2e0aa2009-10-10 00:13:32 +0000794 filename = self.get_param('name', missing, 'content-type')
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000795 if filename is missing:
796 return failobj
797 return utils.collapse_rfc2231_value(filename).strip()
798
799 def get_boundary(self, failobj=None):
800 """Return the boundary associated with the payload if present.
801
802 The boundary is extracted from the Content-Type header's `boundary'
803 parameter, and it is unquoted.
804 """
805 missing = object()
806 boundary = self.get_param('boundary', missing)
807 if boundary is missing:
808 return failobj
809 # RFC 2046 says that boundaries may begin but not end in w/s
810 return utils.collapse_rfc2231_value(boundary).rstrip()
811
812 def set_boundary(self, boundary):
813 """Set the boundary parameter in Content-Type to 'boundary'.
814
815 This is subtly different than deleting the Content-Type header and
816 adding a new one with a new boundary parameter via add_header(). The
817 main difference is that using the set_boundary() method preserves the
818 order of the Content-Type header in the original message.
819
820 HeaderParseError is raised if the message has no Content-Type header.
821 """
822 missing = object()
823 params = self._get_params_preserve(missing, 'content-type')
824 if params is missing:
825 # There was no Content-Type header, and we don't know what type
826 # to set it to, so raise an exception.
827 raise errors.HeaderParseError('No Content-Type header found')
828 newparams = []
829 foundp = False
830 for pk, pv in params:
831 if pk.lower() == 'boundary':
832 newparams.append(('boundary', '"%s"' % boundary))
833 foundp = True
834 else:
835 newparams.append((pk, pv))
836 if not foundp:
837 # The original Content-Type header had no boundary attribute.
838 # Tack one on the end. BAW: should we raise an exception
839 # instead???
840 newparams.append(('boundary', '"%s"' % boundary))
841 # Replace the existing Content-Type header with the new value
842 newheaders = []
843 for h, v in self._headers:
844 if h.lower() == 'content-type':
845 parts = []
846 for k, v in newparams:
847 if v == '':
848 parts.append(k)
849 else:
850 parts.append('%s=%s' % (k, v))
R David Murrayc27e5222012-05-25 15:01:48 -0400851 val = SEMISPACE.join(parts)
852 newheaders.append(self.policy.header_store_parse(h, val))
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000853
854 else:
855 newheaders.append((h, v))
856 self._headers = newheaders
857
858 def get_content_charset(self, failobj=None):
859 """Return the charset parameter of the Content-Type header.
860
861 The returned string is always coerced to lower case. If there is no
862 Content-Type header, or if that header has no charset parameter,
863 failobj is returned.
864 """
865 missing = object()
866 charset = self.get_param('charset', missing)
867 if charset is missing:
868 return failobj
869 if isinstance(charset, tuple):
870 # RFC 2231 encoded, so decode it, and it better end up as ascii.
871 pcharset = charset[0] or 'us-ascii'
872 try:
873 # LookupError will be raised if the charset isn't known to
874 # Python. UnicodeError will be raised if the encoded text
875 # contains a character not in the charset.
Barry Warsaw2cc1f6d2007-08-30 14:28:55 +0000876 as_bytes = charset[2].encode('raw-unicode-escape')
877 charset = str(as_bytes, pcharset)
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000878 except (LookupError, UnicodeError):
879 charset = charset[2]
880 # charset characters must be in us-ascii range
881 try:
882 charset.encode('us-ascii')
883 except UnicodeError:
884 return failobj
885 # RFC 2046, $4.1.2 says charsets are not case sensitive
886 return charset.lower()
887
888 def get_charsets(self, failobj=None):
889 """Return a list containing the charset(s) used in this message.
890
891 The returned list of items describes the Content-Type headers'
892 charset parameter for this message and all the subparts in its
893 payload.
894
895 Each item will either be a string (the value of the charset parameter
896 in the Content-Type header of that part) or the value of the
897 'failobj' parameter (defaults to None), if the part does not have a
898 main MIME type of "text", or the charset is not defined.
899
900 The list will contain one string for each part of the message, plus
901 one for the container message (i.e. self), so that a non-multipart
902 message will still return a list of length 1.
903 """
904 return [part.get_content_charset(failobj) for part in self.walk()]
905
906 # I.e. def walk(self): ...
907 from email.iterators import walk