blob: 91976f14a9bcf07ebee216469caf81eccbef7240 [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
20Charset = _charset.Charset
Guido van Rossum8b3febe2007-08-30 01:15:14 +000021
22SEMISPACE = '; '
23
Guido van Rossum8b3febe2007-08-30 01:15:14 +000024# Regular expression that matches `special' characters in parameters, the
Mark Dickinson934896d2009-02-21 20:59:32 +000025# existence of which force quoting of the parameter value.
Guido van Rossum8b3febe2007-08-30 01:15:14 +000026tspecials = re.compile(r'[ \(\)<>@,;:\\"/\[\]\?=]')
27
R. David Murray96fd54e2010-10-08 15:55:28 +000028
Benjamin Peterson4cd6a952008-08-17 20:23:46 +000029def _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
R David Murraya2150232011-03-16 21:11:23 -040032 # 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(';')
Benjamin Peterson4cd6a952008-08-17 20:23:46 +000035 if not sep:
36 return a.strip(), None
37 return a.strip(), b.strip()
38
Guido van Rossum8b3febe2007-08-30 01:15:14 +000039def _formatparam(param, value=None, quote=True):
40 """Convenience function to format and return a key=value pair.
41
R. David Murray7ec754b2010-12-13 23:51:19 +000042 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.
Guido van Rossum8b3febe2007-08-30 01:15:14 +000047 """
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
R. David Murraydfd7eb02010-12-24 22:36:49 +000051 # instance. RFC 2231 encoded values are never quoted, per RFC.
Guido van Rossum8b3febe2007-08-30 01:15:14 +000052 if isinstance(value, tuple):
53 # Encode as per RFC 2231
54 param += '*'
55 value = utils.encode_rfc2231(value[2], value[0], value[1])
R. David Murraydfd7eb02010-12-24 22:36:49 +000056 return '%s=%s' % (param, value)
R. David Murray7ec754b2010-12-13 23:51:19 +000057 else:
58 try:
59 value.encode('ascii')
60 except UnicodeEncodeError:
61 param += '*'
62 value = utils.encode_rfc2231(value, 'utf-8', '')
R. David Murraydfd7eb02010-12-24 22:36:49 +000063 return '%s=%s' % (param, value)
Guido van Rossum8b3febe2007-08-30 01:15:14 +000064 # 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
73def _parseparam(s):
R David Murraya2150232011-03-16 21:11:23 -040074 # RDM This might be a Header, so for now stringify it.
75 s = ';' + str(s)
Guido van Rossum8b3febe2007-08-30 01:15:14 +000076 plist = []
77 while s[:1] == ';':
78 s = s[1:]
79 end = s.find(';')
R. David Murrayd48739f2010-04-14 18:59:18 +000080 while end > 0 and (s.count('"', 0, end) - s.count('\\"', 0, end)) % 2:
Guido van Rossum8b3febe2007-08-30 01:15:14 +000081 end = s.find(';', end + 1)
82 if end < 0:
83 end = len(s)
84 f = s[:end]
85 if '=' in f:
86 i = f.index('=')
87 f = f[:i].strip().lower() + '=' + f[i+1:].strip()
88 plist.append(f.strip())
89 s = s[end:]
90 return plist
91
92
93def _unquotevalue(value):
94 # This is different than utils.collapse_rfc2231_value() because it doesn't
95 # try to convert the value to a unicode. Message.get_param() and
96 # Message.get_params() are both currently defined to return the tuple in
97 # the face of RFC 2231 parameters.
98 if isinstance(value, tuple):
99 return value[0], value[1], utils.unquote(value[2])
100 else:
101 return utils.unquote(value)
102
103
104
105class Message:
106 """Basic message object.
107
108 A message object is defined as something that has a bunch of RFC 2822
109 headers and a payload. It may optionally have an envelope header
110 (a.k.a. Unix-From or From_ header). If the message is a container (i.e. a
111 multipart or a message/rfc822), then the payload is a list of Message
112 objects, otherwise it is a string.
113
114 Message objects implement part of the `mapping' interface, which assumes
R. David Murrayd2c310f2010-10-01 02:08:02 +0000115 there is exactly one occurrence of the header per message. Some headers
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000116 do in fact appear multiple times (e.g. Received) and for those headers,
117 you must use the explicit API to set or get all the headers. Not all of
118 the mapping methods are implemented.
119 """
R David Murrayc27e5222012-05-25 15:01:48 -0400120 def __init__(self, policy=compat32):
121 self.policy = policy
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000122 self._headers = []
123 self._unixfrom = None
124 self._payload = None
125 self._charset = None
126 # Defaults for multipart messages
127 self.preamble = self.epilogue = None
128 self.defects = []
129 # Default content type
130 self._default_type = 'text/plain'
131
132 def __str__(self):
133 """Return the entire formatted message as a string.
134 This includes the headers, body, and envelope header.
135 """
136 return self.as_string()
137
138 def as_string(self, unixfrom=False, maxheaderlen=0):
139 """Return the entire formatted message as a string.
140 Optional `unixfrom' when True, means include the Unix From_ envelope
141 header.
142
143 This is a convenience method and may not generate the message exactly
R David Murray7dedcb42011-03-15 14:01:18 -0400144 as you intend. For more flexibility, use the flatten() method of a
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000145 Generator instance.
146 """
147 from email.generator import Generator
148 fp = StringIO()
149 g = Generator(fp, mangle_from_=False, maxheaderlen=maxheaderlen)
150 g.flatten(self, unixfrom=unixfrom)
151 return fp.getvalue()
152
153 def is_multipart(self):
154 """Return True if the message consists of multiple parts."""
155 return isinstance(self._payload, list)
156
157 #
158 # Unix From_ line
159 #
160 def set_unixfrom(self, unixfrom):
161 self._unixfrom = unixfrom
162
163 def get_unixfrom(self):
164 return self._unixfrom
165
166 #
167 # Payload manipulation.
168 #
169 def attach(self, payload):
170 """Add the given payload to the current payload.
171
172 The current payload will always be a list of objects after this method
173 is called. If you want to set the payload to a scalar object, use
174 set_payload() instead.
175 """
176 if self._payload is None:
177 self._payload = [payload]
178 else:
179 self._payload.append(payload)
180
181 def get_payload(self, i=None, decode=False):
182 """Return a reference to the payload.
183
184 The payload will either be a list object or a string. If you mutate
185 the list object, you modify the message's payload in place. Optional
186 i returns that index into the payload.
187
188 Optional decode is a flag indicating whether the payload should be
189 decoded or not, according to the Content-Transfer-Encoding header
190 (default is False).
191
192 When True and the message is not a multipart, the payload will be
193 decoded if this header's value is `quoted-printable' or `base64'. If
194 some other encoding is used, or the header is missing, or if the
195 payload has bogus data (i.e. bogus base64 or uuencoded data), the
196 payload is returned as-is.
197
198 If the message is a multipart and the decode flag is True, then None
199 is returned.
200 """
R. David Murray96fd54e2010-10-08 15:55:28 +0000201 # Here is the logic table for this code, based on the email5.0.0 code:
202 # i decode is_multipart result
203 # ------ ------ ------------ ------------------------------
204 # None True True None
205 # i True True None
206 # None False True _payload (a list)
207 # i False True _payload element i (a Message)
208 # i False False error (not a list)
209 # i True False error (not a list)
210 # None False False _payload
211 # None True False _payload decoded (bytes)
212 # Note that Barry planned to factor out the 'decode' case, but that
213 # isn't so easy now that we handle the 8 bit data, which needs to be
214 # converted in both the decode and non-decode path.
215 if self.is_multipart():
216 if decode:
217 return None
218 if i is None:
219 return self._payload
220 else:
221 return self._payload[i]
222 # For backward compatibility, Use isinstance and this error message
223 # instead of the more logical is_multipart test.
224 if i is not None and not isinstance(self._payload, list):
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000225 raise TypeError('Expected list, got %s' % type(self._payload))
R. David Murray96fd54e2010-10-08 15:55:28 +0000226 payload = self._payload
R David Murraya2150232011-03-16 21:11:23 -0400227 # cte might be a Header, so for now stringify it.
228 cte = str(self.get('content-transfer-encoding', '')).lower()
R David Murray106f8e32011-03-15 12:48:41 -0400229 # payload may be bytes here.
R. David Murray96fd54e2010-10-08 15:55:28 +0000230 if isinstance(payload, str):
R David Murrayc27e5222012-05-25 15:01:48 -0400231 if utils._has_surrogates(payload):
R. David Murray96fd54e2010-10-08 15:55:28 +0000232 bpayload = payload.encode('ascii', 'surrogateescape')
233 if not decode:
234 try:
235 payload = bpayload.decode(self.get_param('charset', 'ascii'), 'replace')
236 except LookupError:
237 payload = bpayload.decode('ascii', 'replace')
238 elif decode:
239 try:
240 bpayload = payload.encode('ascii')
241 except UnicodeError:
242 # This won't happen for RFC compliant messages (messages
243 # containing only ASCII codepoints in the unicode input).
244 # If it does happen, turn the string into bytes in a way
245 # guaranteed not to fail.
246 bpayload = payload.encode('raw-unicode-escape')
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000247 if not decode:
248 return payload
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000249 if cte == 'quoted-printable':
R. David Murray96fd54e2010-10-08 15:55:28 +0000250 return utils._qdecode(bpayload)
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000251 elif cte == 'base64':
252 try:
R. David Murray96fd54e2010-10-08 15:55:28 +0000253 return base64.b64decode(bpayload)
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000254 except binascii.Error:
255 # Incorrect padding
R. David Murray96fd54e2010-10-08 15:55:28 +0000256 return bpayload
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000257 elif cte in ('x-uuencode', 'uuencode', 'uue', 'x-uue'):
R. David Murray96fd54e2010-10-08 15:55:28 +0000258 in_file = BytesIO(bpayload)
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000259 out_file = BytesIO()
260 try:
261 uu.decode(in_file, out_file, quiet=True)
262 return out_file.getvalue()
263 except uu.Error:
264 # Some decoding problem
R. David Murray96fd54e2010-10-08 15:55:28 +0000265 return bpayload
Barry Warsaw8b2af272007-08-31 03:04:26 +0000266 if isinstance(payload, str):
R. David Murray96fd54e2010-10-08 15:55:28 +0000267 return bpayload
Barry Warsaw8b2af272007-08-31 03:04:26 +0000268 return payload
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000269
270 def set_payload(self, payload, charset=None):
271 """Set the payload to the given value.
272
273 Optional charset sets the message's default character set. See
274 set_charset() for details.
275 """
276 self._payload = payload
277 if charset is not None:
278 self.set_charset(charset)
279
280 def set_charset(self, charset):
281 """Set the charset of the payload to a given character set.
282
283 charset can be a Charset instance, a string naming a character set, or
284 None. If it is a string it will be converted to a Charset instance.
285 If charset is None, the charset parameter will be removed from the
286 Content-Type field. Anything else will generate a TypeError.
287
288 The message will be assumed to be of type text/* encoded with
289 charset.input_charset. It will be converted to charset.output_charset
290 and encoded properly, if needed, when generating the plain text
291 representation of the message. MIME headers (MIME-Version,
292 Content-Type, Content-Transfer-Encoding) will be added as needed.
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000293 """
294 if charset is None:
295 self.del_param('charset')
296 self._charset = None
297 return
Guido van Rossum9604e662007-08-30 03:46:43 +0000298 if not isinstance(charset, Charset):
299 charset = Charset(charset)
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000300 self._charset = charset
301 if 'MIME-Version' not in self:
302 self.add_header('MIME-Version', '1.0')
303 if 'Content-Type' not in self:
304 self.add_header('Content-Type', 'text/plain',
305 charset=charset.get_output_charset())
306 else:
307 self.set_param('charset', charset.get_output_charset())
Guido van Rossum9604e662007-08-30 03:46:43 +0000308 if charset != charset.get_output_charset():
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000309 self._payload = charset.body_encode(self._payload)
310 if 'Content-Transfer-Encoding' not in self:
311 cte = charset.get_body_encoding()
312 try:
313 cte(self)
314 except TypeError:
315 self._payload = charset.body_encode(self._payload)
316 self.add_header('Content-Transfer-Encoding', cte)
317
318 def get_charset(self):
319 """Return the Charset instance associated with the message's payload.
320 """
321 return self._charset
322
323 #
324 # MAPPING INTERFACE (partial)
325 #
326 def __len__(self):
327 """Return the total number of headers, including duplicates."""
328 return len(self._headers)
329
330 def __getitem__(self, name):
331 """Get a header value.
332
333 Return None if the header is missing instead of raising an exception.
334
335 Note that if the header appeared multiple times, exactly which
R. David Murrayd2c310f2010-10-01 02:08:02 +0000336 occurrence gets returned is undefined. Use get_all() to get all
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000337 the values matching a header field name.
338 """
339 return self.get(name)
340
341 def __setitem__(self, name, val):
342 """Set the value of a header.
343
344 Note: this does not overwrite an existing header with the same field
345 name. Use __delitem__() first to delete any existing headers.
346 """
R David Murrayc27e5222012-05-25 15:01:48 -0400347 self._headers.append(self.policy.header_store_parse(name, val))
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000348
349 def __delitem__(self, name):
350 """Delete all occurrences of a header, if present.
351
352 Does not raise an exception if the header is missing.
353 """
354 name = name.lower()
355 newheaders = []
356 for k, v in self._headers:
357 if k.lower() != name:
358 newheaders.append((k, v))
359 self._headers = newheaders
360
361 def __contains__(self, name):
362 return name.lower() in [k.lower() for k, v in self._headers]
363
364 def __iter__(self):
365 for field, value in self._headers:
366 yield field
367
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000368 def keys(self):
369 """Return a list of all the message's header field names.
370
371 These will be sorted in the order they appeared in the original
372 message, or were added to the message, and may contain duplicates.
373 Any fields deleted and re-inserted are always appended to the header
374 list.
375 """
376 return [k for k, v in self._headers]
377
378 def values(self):
379 """Return a list of all the message's header values.
380
381 These will be sorted in the order they appeared in the original
382 message, or were added to the message, and may contain duplicates.
383 Any fields deleted and re-inserted are always appended to the header
384 list.
385 """
R David Murrayc27e5222012-05-25 15:01:48 -0400386 return [self.policy.header_fetch_parse(k, v)
387 for k, v in self._headers]
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000388
389 def items(self):
390 """Get all the message's header fields and values.
391
392 These will be sorted in the order they appeared in the original
393 message, or were added to the message, and may contain duplicates.
394 Any fields deleted and re-inserted are always appended to the header
395 list.
396 """
R David Murrayc27e5222012-05-25 15:01:48 -0400397 return [(k, self.policy.header_fetch_parse(k, v))
398 for k, v in self._headers]
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000399
400 def get(self, name, failobj=None):
401 """Get a header value.
402
403 Like __getitem__() but return failobj instead of None when the field
404 is missing.
405 """
406 name = name.lower()
407 for k, v in self._headers:
408 if k.lower() == name:
R David Murrayc27e5222012-05-25 15:01:48 -0400409 return self.policy.header_fetch_parse(k, v)
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000410 return failobj
411
412 #
R David Murrayc27e5222012-05-25 15:01:48 -0400413 # "Internal" methods (public API, but only intended for use by a parser
414 # or generator, not normal application code.
415 #
416
417 def set_raw(self, name, value):
418 """Store name and value in the model without modification.
419
420 This is an "internal" API, intended only for use by a parser.
421 """
422 self._headers.append((name, value))
423
424 def raw_items(self):
425 """Return the (name, value) header pairs without modification.
426
427 This is an "internal" API, intended only for use by a generator.
428 """
429 return iter(self._headers.copy())
430
431 #
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000432 # Additional useful stuff
433 #
434
435 def get_all(self, name, failobj=None):
436 """Return a list of all the values for the named field.
437
438 These will be sorted in the order they appeared in the original
439 message, and may contain duplicates. Any fields deleted and
440 re-inserted are always appended to the header list.
441
442 If no such fields exist, failobj is returned (defaults to None).
443 """
444 values = []
445 name = name.lower()
446 for k, v in self._headers:
447 if k.lower() == name:
R David Murrayc27e5222012-05-25 15:01:48 -0400448 values.append(self.policy.header_fetch_parse(k, v))
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000449 if not values:
450 return failobj
451 return values
452
453 def add_header(self, _name, _value, **_params):
454 """Extended header setting.
455
456 name is the header field to add. keyword arguments can be used to set
457 additional parameters for the header field, with underscores converted
458 to dashes. Normally the parameter will be added as key="value" unless
R. David Murray7ec754b2010-12-13 23:51:19 +0000459 value is None, in which case only the key will be added. If a
460 parameter value contains non-ASCII characters it can be specified as a
461 three-tuple of (charset, language, value), in which case it will be
462 encoded according to RFC2231 rules. Otherwise it will be encoded using
463 the utf-8 charset and a language of ''.
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000464
R. David Murray7ec754b2010-12-13 23:51:19 +0000465 Examples:
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000466
467 msg.add_header('content-disposition', 'attachment', filename='bud.gif')
R. David Murray7ec754b2010-12-13 23:51:19 +0000468 msg.add_header('content-disposition', 'attachment',
469 filename=('utf-8', '', Fußballer.ppt'))
470 msg.add_header('content-disposition', 'attachment',
471 filename='Fußballer.ppt'))
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000472 """
473 parts = []
474 for k, v in _params.items():
475 if v is None:
476 parts.append(k.replace('_', '-'))
477 else:
478 parts.append(_formatparam(k.replace('_', '-'), v))
479 if _value is not None:
480 parts.insert(0, _value)
R David Murrayc27e5222012-05-25 15:01:48 -0400481 self[_name] = SEMISPACE.join(parts)
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000482
483 def replace_header(self, _name, _value):
484 """Replace a header.
485
486 Replace the first matching header found in the message, retaining
487 header order and case. If no matching header was found, a KeyError is
488 raised.
489 """
490 _name = _name.lower()
491 for i, (k, v) in zip(range(len(self._headers)), self._headers):
492 if k.lower() == _name:
R David Murrayc27e5222012-05-25 15:01:48 -0400493 self._headers[i] = self.policy.header_store_parse(k, _value)
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000494 break
495 else:
496 raise KeyError(_name)
497
498 #
499 # Use these three methods instead of the three above.
500 #
501
502 def get_content_type(self):
503 """Return the message's content type.
504
505 The returned string is coerced to lower case of the form
506 `maintype/subtype'. If there was no Content-Type header in the
507 message, the default type as given by get_default_type() will be
508 returned. Since according to RFC 2045, messages always have a default
509 type this will always return a value.
510
511 RFC 2045 defines a message's default type to be text/plain unless it
512 appears inside a multipart/digest container, in which case it would be
513 message/rfc822.
514 """
515 missing = object()
516 value = self.get('content-type', missing)
517 if value is missing:
518 # This should have no parameters
519 return self.get_default_type()
Benjamin Peterson4cd6a952008-08-17 20:23:46 +0000520 ctype = _splitparam(value)[0].lower()
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000521 # RFC 2045, section 5.2 says if its invalid, use text/plain
522 if ctype.count('/') != 1:
523 return 'text/plain'
524 return ctype
525
526 def get_content_maintype(self):
527 """Return the message's main content type.
528
529 This is the `maintype' part of the string returned by
530 get_content_type().
531 """
532 ctype = self.get_content_type()
533 return ctype.split('/')[0]
534
535 def get_content_subtype(self):
536 """Returns the message's sub-content type.
537
538 This is the `subtype' part of the string returned by
539 get_content_type().
540 """
541 ctype = self.get_content_type()
542 return ctype.split('/')[1]
543
544 def get_default_type(self):
545 """Return the `default' content type.
546
547 Most messages have a default content type of text/plain, except for
548 messages that are subparts of multipart/digest containers. Such
549 subparts have a default content type of message/rfc822.
550 """
551 return self._default_type
552
553 def set_default_type(self, ctype):
554 """Set the `default' content type.
555
556 ctype should be either "text/plain" or "message/rfc822", although this
557 is not enforced. The default content type is not stored in the
558 Content-Type header.
559 """
560 self._default_type = ctype
561
562 def _get_params_preserve(self, failobj, header):
563 # Like get_params() but preserves the quoting of values. BAW:
564 # should this be part of the public interface?
565 missing = object()
566 value = self.get(header, missing)
567 if value is missing:
568 return failobj
569 params = []
R David Murraya2150232011-03-16 21:11:23 -0400570 for p in _parseparam(value):
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000571 try:
572 name, val = p.split('=', 1)
573 name = name.strip()
574 val = val.strip()
575 except ValueError:
576 # Must have been a bare attribute
577 name = p.strip()
578 val = ''
579 params.append((name, val))
580 params = utils.decode_params(params)
581 return params
582
583 def get_params(self, failobj=None, header='content-type', unquote=True):
584 """Return the message's Content-Type parameters, as a list.
585
586 The elements of the returned list are 2-tuples of key/value pairs, as
587 split on the `=' sign. The left hand side of the `=' is the key,
588 while the right hand side is the value. If there is no `=' sign in
589 the parameter the value is the empty string. The value is as
590 described in the get_param() method.
591
592 Optional failobj is the object to return if there is no Content-Type
593 header. Optional header is the header to search instead of
594 Content-Type. If unquote is True, the value is unquoted.
595 """
596 missing = object()
597 params = self._get_params_preserve(missing, header)
598 if params is missing:
599 return failobj
600 if unquote:
601 return [(k, _unquotevalue(v)) for k, v in params]
602 else:
603 return params
604
605 def get_param(self, param, failobj=None, header='content-type',
606 unquote=True):
607 """Return the parameter value if found in the Content-Type header.
608
609 Optional failobj is the object to return if there is no Content-Type
610 header, or the Content-Type header has no such parameter. Optional
611 header is the header to search instead of Content-Type.
612
613 Parameter keys are always compared case insensitively. The return
614 value can either be a string, or a 3-tuple if the parameter was RFC
615 2231 encoded. When it's a 3-tuple, the elements of the value are of
616 the form (CHARSET, LANGUAGE, VALUE). Note that both CHARSET and
617 LANGUAGE can be None, in which case you should consider VALUE to be
618 encoded in the us-ascii charset. You can usually ignore LANGUAGE.
619
620 Your application should be prepared to deal with 3-tuple return
621 values, and can convert the parameter to a Unicode string like so:
622
623 param = msg.get_param('foo')
624 if isinstance(param, tuple):
625 param = unicode(param[2], param[0] or 'us-ascii')
626
627 In any case, the parameter value (either the returned string, or the
628 VALUE item in the 3-tuple) is always unquoted, unless unquote is set
629 to False.
630 """
631 if header not in self:
632 return failobj
633 for k, v in self._get_params_preserve(failobj, header):
634 if k.lower() == param.lower():
635 if unquote:
636 return _unquotevalue(v)
637 else:
638 return v
639 return failobj
640
641 def set_param(self, param, value, header='Content-Type', requote=True,
642 charset=None, language=''):
643 """Set a parameter in the Content-Type header.
644
645 If the parameter already exists in the header, its value will be
646 replaced with the new value.
647
648 If header is Content-Type and has not yet been defined for this
649 message, it will be set to "text/plain" and the new parameter and
650 value will be appended as per RFC 2045.
651
652 An alternate header can specified in the header argument, and all
653 parameters will be quoted as necessary unless requote is False.
654
655 If charset is specified, the parameter will be encoded according to RFC
656 2231. Optional language specifies the RFC 2231 language, defaulting
657 to the empty string. Both charset and language should be strings.
658 """
659 if not isinstance(value, tuple) and charset:
660 value = (charset, language, value)
661
662 if header not in self and header.lower() == 'content-type':
663 ctype = 'text/plain'
664 else:
665 ctype = self.get(header)
666 if not self.get_param(param, header=header):
667 if not ctype:
668 ctype = _formatparam(param, value, requote)
669 else:
670 ctype = SEMISPACE.join(
671 [ctype, _formatparam(param, value, requote)])
672 else:
673 ctype = ''
674 for old_param, old_value in self.get_params(header=header,
675 unquote=requote):
676 append_param = ''
677 if old_param.lower() == param.lower():
678 append_param = _formatparam(param, value, requote)
679 else:
680 append_param = _formatparam(old_param, old_value, requote)
681 if not ctype:
682 ctype = append_param
683 else:
684 ctype = SEMISPACE.join([ctype, append_param])
685 if ctype != self.get(header):
686 del self[header]
687 self[header] = ctype
688
689 def del_param(self, param, header='content-type', requote=True):
690 """Remove the given parameter completely from the Content-Type header.
691
692 The header will be re-written in place without the parameter or its
693 value. All values will be quoted as necessary unless requote is
694 False. Optional header specifies an alternative to the Content-Type
695 header.
696 """
697 if header not in self:
698 return
699 new_ctype = ''
700 for p, v in self.get_params(header=header, unquote=requote):
701 if p.lower() != param.lower():
702 if not new_ctype:
703 new_ctype = _formatparam(p, v, requote)
704 else:
705 new_ctype = SEMISPACE.join([new_ctype,
706 _formatparam(p, v, requote)])
707 if new_ctype != self.get(header):
708 del self[header]
709 self[header] = new_ctype
710
711 def set_type(self, type, header='Content-Type', requote=True):
712 """Set the main type and subtype for the Content-Type header.
713
714 type must be a string in the form "maintype/subtype", otherwise a
715 ValueError is raised.
716
717 This method replaces the Content-Type header, keeping all the
718 parameters in place. If requote is False, this leaves the existing
719 header's quoting as is. Otherwise, the parameters will be quoted (the
720 default).
721
722 An alternative header can be specified in the header argument. When
723 the Content-Type header is set, we'll always also add a MIME-Version
724 header.
725 """
726 # BAW: should we be strict?
727 if not type.count('/') == 1:
728 raise ValueError
729 # Set the Content-Type, you get a MIME-Version
730 if header.lower() == 'content-type':
731 del self['mime-version']
732 self['MIME-Version'] = '1.0'
733 if header not in self:
734 self[header] = type
735 return
736 params = self.get_params(header=header, unquote=requote)
737 del self[header]
738 self[header] = type
739 # Skip the first param; it's the old type.
740 for p, v in params[1:]:
741 self.set_param(p, v, header, requote)
742
743 def get_filename(self, failobj=None):
744 """Return the filename associated with the payload if present.
745
746 The filename is extracted from the Content-Disposition header's
747 `filename' parameter, and it is unquoted. If that header is missing
748 the `filename' parameter, this method falls back to looking for the
749 `name' parameter.
750 """
751 missing = object()
752 filename = self.get_param('filename', missing, 'content-disposition')
753 if filename is missing:
R. David Murraybf2e0aa2009-10-10 00:13:32 +0000754 filename = self.get_param('name', missing, 'content-type')
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000755 if filename is missing:
756 return failobj
757 return utils.collapse_rfc2231_value(filename).strip()
758
759 def get_boundary(self, failobj=None):
760 """Return the boundary associated with the payload if present.
761
762 The boundary is extracted from the Content-Type header's `boundary'
763 parameter, and it is unquoted.
764 """
765 missing = object()
766 boundary = self.get_param('boundary', missing)
767 if boundary is missing:
768 return failobj
769 # RFC 2046 says that boundaries may begin but not end in w/s
770 return utils.collapse_rfc2231_value(boundary).rstrip()
771
772 def set_boundary(self, boundary):
773 """Set the boundary parameter in Content-Type to 'boundary'.
774
775 This is subtly different than deleting the Content-Type header and
776 adding a new one with a new boundary parameter via add_header(). The
777 main difference is that using the set_boundary() method preserves the
778 order of the Content-Type header in the original message.
779
780 HeaderParseError is raised if the message has no Content-Type header.
781 """
782 missing = object()
783 params = self._get_params_preserve(missing, 'content-type')
784 if params is missing:
785 # There was no Content-Type header, and we don't know what type
786 # to set it to, so raise an exception.
787 raise errors.HeaderParseError('No Content-Type header found')
788 newparams = []
789 foundp = False
790 for pk, pv in params:
791 if pk.lower() == 'boundary':
792 newparams.append(('boundary', '"%s"' % boundary))
793 foundp = True
794 else:
795 newparams.append((pk, pv))
796 if not foundp:
797 # The original Content-Type header had no boundary attribute.
798 # Tack one on the end. BAW: should we raise an exception
799 # instead???
800 newparams.append(('boundary', '"%s"' % boundary))
801 # Replace the existing Content-Type header with the new value
802 newheaders = []
803 for h, v in self._headers:
804 if h.lower() == 'content-type':
805 parts = []
806 for k, v in newparams:
807 if v == '':
808 parts.append(k)
809 else:
810 parts.append('%s=%s' % (k, v))
R David Murrayc27e5222012-05-25 15:01:48 -0400811 val = SEMISPACE.join(parts)
812 newheaders.append(self.policy.header_store_parse(h, val))
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000813
814 else:
815 newheaders.append((h, v))
816 self._headers = newheaders
817
818 def get_content_charset(self, failobj=None):
819 """Return the charset parameter of the Content-Type header.
820
821 The returned string is always coerced to lower case. If there is no
822 Content-Type header, or if that header has no charset parameter,
823 failobj is returned.
824 """
825 missing = object()
826 charset = self.get_param('charset', missing)
827 if charset is missing:
828 return failobj
829 if isinstance(charset, tuple):
830 # RFC 2231 encoded, so decode it, and it better end up as ascii.
831 pcharset = charset[0] or 'us-ascii'
832 try:
833 # LookupError will be raised if the charset isn't known to
834 # Python. UnicodeError will be raised if the encoded text
835 # contains a character not in the charset.
Barry Warsaw2cc1f6d2007-08-30 14:28:55 +0000836 as_bytes = charset[2].encode('raw-unicode-escape')
837 charset = str(as_bytes, pcharset)
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000838 except (LookupError, UnicodeError):
839 charset = charset[2]
840 # charset characters must be in us-ascii range
841 try:
842 charset.encode('us-ascii')
843 except UnicodeError:
844 return failobj
845 # RFC 2046, $4.1.2 says charsets are not case sensitive
846 return charset.lower()
847
848 def get_charsets(self, failobj=None):
849 """Return a list containing the charset(s) used in this message.
850
851 The returned list of items describes the Content-Type headers'
852 charset parameter for this message and all the subparts in its
853 payload.
854
855 Each item will either be a string (the value of the charset parameter
856 in the Content-Type header of that part) or the value of the
857 'failobj' parameter (defaults to None), if the part does not have a
858 main MIME type of "text", or the charset is not defined.
859
860 The list will contain one string for each part of the message, plus
861 one for the container message (i.e. self), so that a non-multipart
862 message will still return a list of length 1.
863 """
864 return [part.get_content_charset(failobj) for part in self.walk()]
865
866 # I.e. def walk(self): ...
867 from email.iterators import walk