blob: 7c93370984c0d040dde803bd88101c2bbde0d1ea [file] [log] [blame]
Barry Warsawa0f28ef2006-01-17 04:49:07 +00001# Copyright (C) 2001-2006 Python Software Foundation
Barry Warsawbb113862004-10-03 03:16:19 +00002# Author: Barry Warsaw
3# Contact: email-sig@python.org
Barry Warsawba925802001-09-23 03:17:28 +00004
Barry Warsaw5d840532004-05-09 03:44:55 +00005"""Basic message object for the email package object model."""
Barry Warsawba925802001-09-23 03:17:28 +00006
Barry Warsaw40ef0062006-03-18 15:41:53 +00007__all__ = ['Message']
8
Barry Warsawba925802001-09-23 03:17:28 +00009import re
Barry Warsaw08898492003-03-11 04:33:30 +000010import uu
Barry Warsaw21191d32003-03-10 16:13:14 +000011import binascii
Barry Warsaw409a4c02002-04-10 21:01:31 +000012import warnings
Barry Warsawba925802001-09-23 03:17:28 +000013from cStringIO import StringIO
Barry Warsawba925802001-09-23 03:17:28 +000014
Barry Warsawba925802001-09-23 03:17:28 +000015# Intrapackage imports
Barry Warsaw40ef0062006-03-18 15:41:53 +000016import email.charset
17from email import utils
18from email import errors
Barry Warsawba925802001-09-23 03:17:28 +000019
Barry Warsawbeb59452001-09-26 05:41:51 +000020SEMISPACE = '; '
Barry Warsaw409a4c02002-04-10 21:01:31 +000021
Barry Warsaw409a4c02002-04-10 21:01:31 +000022# Regular expression that matches `special' characters in parameters, the
Mark Dickinson3e4caeb2009-02-21 20:27:01 +000023# existence of which force quoting of the parameter value.
Barry Warsaw409a4c02002-04-10 21:01:31 +000024tspecials = re.compile(r'[ \(\)<>@,;:\\"/\[\]\?=]')
25
26
Barry Warsaw908dc4b2002-06-29 05:56:15 +000027# Helper functions
Antoine Pitroub90a8be2008-08-15 21:03:21 +000028def _splitparam(param):
29 # Split header parameters. BAW: this may be too simple. It isn't
30 # strictly RFC 2045 (section 5.1) compliant, but it catches most headers
31 # found in the wild. We may eventually need a full fledged parser
32 # eventually.
33 a, sep, b = param.partition(';')
34 if not sep:
35 return a.strip(), None
36 return a.strip(), b.strip()
37
Barry Warsawc4945492002-09-28 20:40:25 +000038def _formatparam(param, value=None, quote=True):
Barry Warsaw409a4c02002-04-10 21:01:31 +000039 """Convenience function to format and return a key=value pair.
40
R. David Murraya9aa34c2010-12-14 00:29:27 +000041 This will quote the value if needed or if quote is true. If value is a
42 three tuple (charset, language, value), it will be encoded according
43 to RFC2231 rules.
Barry Warsaw409a4c02002-04-10 21:01:31 +000044 """
45 if value is not None and len(value) > 0:
Barry Warsaw5d840532004-05-09 03:44:55 +000046 # A tuple is used for RFC 2231 encoded parameter values where items
Barry Warsaw908dc4b2002-06-29 05:56:15 +000047 # are (charset, language, value). charset is a string, not a Charset
48 # instance.
Barry Warsaw5d840532004-05-09 03:44:55 +000049 if isinstance(value, tuple):
Barry Warsaw3c255352002-09-06 03:55:04 +000050 # Encode as per RFC 2231
51 param += '*'
Barry Warsaw40ef0062006-03-18 15:41:53 +000052 value = utils.encode_rfc2231(value[2], value[0], value[1])
Barry Warsaw409a4c02002-04-10 21:01:31 +000053 # BAW: Please check this. I think that if quote is set it should
54 # force quoting even if not necessary.
55 if quote or tspecials.search(value):
Barry Warsaw40ef0062006-03-18 15:41:53 +000056 return '%s="%s"' % (param, utils.quote(value))
Barry Warsaw409a4c02002-04-10 21:01:31 +000057 else:
58 return '%s=%s' % (param, value)
59 else:
60 return param
Barry Warsawbeb59452001-09-26 05:41:51 +000061
Barry Warsawa74e8682003-09-03 04:08:13 +000062def _parseparam(s):
63 plist = []
64 while s[:1] == ';':
65 s = s[1:]
66 end = s.find(';')
R. David Murray661303f2010-04-13 20:57:40 +000067 while end > 0 and (s.count('"', 0, end) - s.count('\\"', 0, end)) % 2:
Barry Warsawa74e8682003-09-03 04:08:13 +000068 end = s.find(';', end + 1)
69 if end < 0:
70 end = len(s)
71 f = s[:end]
72 if '=' in f:
73 i = f.index('=')
74 f = f[:i].strip().lower() + '=' + f[i+1:].strip()
75 plist.append(f.strip())
76 s = s[end:]
77 return plist
78
Barry Warsawba925802001-09-23 03:17:28 +000079
Barry Warsaw908dc4b2002-06-29 05:56:15 +000080def _unquotevalue(value):
Barry Warsaw40ef0062006-03-18 15:41:53 +000081 # This is different than utils.collapse_rfc2231_value() because it doesn't
Barry Warsawbb113862004-10-03 03:16:19 +000082 # try to convert the value to a unicode. Message.get_param() and
83 # Message.get_params() are both currently defined to return the tuple in
84 # the face of RFC 2231 parameters.
Barry Warsaw5d840532004-05-09 03:44:55 +000085 if isinstance(value, tuple):
Barry Warsaw40ef0062006-03-18 15:41:53 +000086 return value[0], value[1], utils.unquote(value[2])
Barry Warsaw908dc4b2002-06-29 05:56:15 +000087 else:
Barry Warsaw40ef0062006-03-18 15:41:53 +000088 return utils.unquote(value)
Barry Warsaw908dc4b2002-06-29 05:56:15 +000089
90
Barry Warsaw48b0d362002-08-27 22:34:44 +000091
Barry Warsawba925802001-09-23 03:17:28 +000092class Message:
Barry Warsaw42d1d3e2002-09-30 18:17:35 +000093 """Basic message object.
Barry Warsawba925802001-09-23 03:17:28 +000094
95 A message object is defined as something that has a bunch of RFC 2822
Barry Warsaw42d1d3e2002-09-30 18:17:35 +000096 headers and a payload. It may optionally have an envelope header
97 (a.k.a. Unix-From or From_ header). If the message is a container (i.e. a
98 multipart or a message/rfc822), then the payload is a list of Message
99 objects, otherwise it is a string.
Barry Warsawba925802001-09-23 03:17:28 +0000100
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000101 Message objects implement part of the `mapping' interface, which assumes
R. David Murray13219a32010-12-06 18:45:46 +0000102 there is exactly one occurrence of the header per message. Some headers
Barry Warsawc4945492002-09-28 20:40:25 +0000103 do in fact appear multiple times (e.g. Received) and for those headers,
Barry Warsawba925802001-09-23 03:17:28 +0000104 you must use the explicit API to set or get all the headers. Not all of
105 the mapping methods are implemented.
Barry Warsawba925802001-09-23 03:17:28 +0000106 """
107 def __init__(self):
108 self._headers = []
109 self._unixfrom = None
110 self._payload = None
Barry Warsaw409a4c02002-04-10 21:01:31 +0000111 self._charset = None
Barry Warsawba925802001-09-23 03:17:28 +0000112 # Defaults for multipart messages
113 self.preamble = self.epilogue = None
Barry Warsawbb113862004-10-03 03:16:19 +0000114 self.defects = []
Barry Warsawa0c8b9d2002-07-09 02:46:12 +0000115 # Default content type
116 self._default_type = 'text/plain'
Barry Warsawba925802001-09-23 03:17:28 +0000117
118 def __str__(self):
119 """Return the entire formatted message as a string.
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000120 This includes the headers, body, and envelope header.
Barry Warsawba925802001-09-23 03:17:28 +0000121 """
Barry Warsawc4945492002-09-28 20:40:25 +0000122 return self.as_string(unixfrom=True)
Barry Warsawba925802001-09-23 03:17:28 +0000123
Barry Warsawc4945492002-09-28 20:40:25 +0000124 def as_string(self, unixfrom=False):
Barry Warsawba925802001-09-23 03:17:28 +0000125 """Return the entire formatted message as a string.
Barry Warsawc4945492002-09-28 20:40:25 +0000126 Optional `unixfrom' when True, means include the Unix From_ envelope
Barry Warsawba925802001-09-23 03:17:28 +0000127 header.
Barry Warsaw482c5f72003-04-18 23:04:35 +0000128
129 This is a convenience method and may not generate the message exactly
Barry Warsaw05bef932004-10-03 03:38:07 +0000130 as you intend because by default it mangles lines that begin with
131 "From ". For more flexibility, use the flatten() method of a
Barry Warsaw482c5f72003-04-18 23:04:35 +0000132 Generator instance.
Barry Warsawba925802001-09-23 03:17:28 +0000133 """
Amaury Forgeot d'Arc74b8d332009-07-11 14:33:51 +0000134 from email.generator import Generator
Barry Warsawba925802001-09-23 03:17:28 +0000135 fp = StringIO()
136 g = Generator(fp)
Barry Warsaw8ba76e82002-06-02 19:05:51 +0000137 g.flatten(self, unixfrom=unixfrom)
Barry Warsawba925802001-09-23 03:17:28 +0000138 return fp.getvalue()
139
140 def is_multipart(self):
Barry Warsawc4945492002-09-28 20:40:25 +0000141 """Return True if the message consists of multiple parts."""
Barry Warsawbb113862004-10-03 03:16:19 +0000142 return isinstance(self._payload, list)
Barry Warsawba925802001-09-23 03:17:28 +0000143
144 #
145 # Unix From_ line
146 #
147 def set_unixfrom(self, unixfrom):
148 self._unixfrom = unixfrom
149
150 def get_unixfrom(self):
151 return self._unixfrom
152
153 #
154 # Payload manipulation.
155 #
Barry Warsaw409a4c02002-04-10 21:01:31 +0000156 def attach(self, payload):
157 """Add the given payload to the current payload.
158
159 The current payload will always be a list of objects after this method
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000160 is called. If you want to set the payload to a scalar object, use
Barry Warsaw409a4c02002-04-10 21:01:31 +0000161 set_payload() instead.
162 """
163 if self._payload is None:
164 self._payload = [payload]
165 else:
166 self._payload.append(payload)
Barry Warsawba925802001-09-23 03:17:28 +0000167
Barry Warsawc4945492002-09-28 20:40:25 +0000168 def get_payload(self, i=None, decode=False):
Barry Warsawfbcde752002-09-11 14:11:35 +0000169 """Return a reference to the payload.
Barry Warsawba925802001-09-23 03:17:28 +0000170
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000171 The payload will either be a list object or a string. If you mutate
172 the list object, you modify the message's payload in place. Optional
173 i returns that index into the payload.
Barry Warsawba925802001-09-23 03:17:28 +0000174
Barry Warsaw08898492003-03-11 04:33:30 +0000175 Optional decode is a flag indicating whether the payload should be
176 decoded or not, according to the Content-Transfer-Encoding header
177 (default is False).
178
179 When True and the message is not a multipart, the payload will be
180 decoded if this header's value is `quoted-printable' or `base64'. If
181 some other encoding is used, or the header is missing, or if the
182 payload has bogus data (i.e. bogus base64 or uuencoded data), the
183 payload is returned as-is.
Barry Warsaw21191d32003-03-10 16:13:14 +0000184
185 If the message is a multipart and the decode flag is True, then None
186 is returned.
Barry Warsawba925802001-09-23 03:17:28 +0000187 """
188 if i is None:
189 payload = self._payload
Barry Warsaw5d840532004-05-09 03:44:55 +0000190 elif not isinstance(self._payload, list):
Barry Warsawbb113862004-10-03 03:16:19 +0000191 raise TypeError('Expected list, got %s' % type(self._payload))
Barry Warsawba925802001-09-23 03:17:28 +0000192 else:
193 payload = self._payload[i]
194 if decode:
195 if self.is_multipart():
196 return None
Barry Warsaw08898492003-03-11 04:33:30 +0000197 cte = self.get('content-transfer-encoding', '').lower()
198 if cte == 'quoted-printable':
Barry Warsaw40ef0062006-03-18 15:41:53 +0000199 return utils._qdecode(payload)
Barry Warsaw08898492003-03-11 04:33:30 +0000200 elif cte == 'base64':
Barry Warsaw21191d32003-03-10 16:13:14 +0000201 try:
Barry Warsaw40ef0062006-03-18 15:41:53 +0000202 return utils._bdecode(payload)
Barry Warsaw21191d32003-03-10 16:13:14 +0000203 except binascii.Error:
204 # Incorrect padding
205 return payload
Barry Warsaw08898492003-03-11 04:33:30 +0000206 elif cte in ('x-uuencode', 'uuencode', 'uue', 'x-uue'):
207 sfp = StringIO()
208 try:
Barry Warsaw40ef0062006-03-18 15:41:53 +0000209 uu.decode(StringIO(payload+'\n'), sfp, quiet=True)
Barry Warsaw08898492003-03-11 04:33:30 +0000210 payload = sfp.getvalue()
211 except uu.Error:
212 # Some decoding problem
213 return payload
Barry Warsawba925802001-09-23 03:17:28 +0000214 # Everything else, including encodings with 8bit or 7bit are returned
215 # unchanged.
216 return payload
217
Barry Warsaw409a4c02002-04-10 21:01:31 +0000218 def set_payload(self, payload, charset=None):
219 """Set the payload to the given value.
Barry Warsawba925802001-09-23 03:17:28 +0000220
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000221 Optional charset sets the message's default character set. See
222 set_charset() for details.
223 """
Barry Warsaw409a4c02002-04-10 21:01:31 +0000224 self._payload = payload
225 if charset is not None:
226 self.set_charset(charset)
227
228 def set_charset(self, charset):
229 """Set the charset of the payload to a given character set.
230
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000231 charset can be a Charset instance, a string naming a character set, or
232 None. If it is a string it will be converted to a Charset instance.
233 If charset is None, the charset parameter will be removed from the
234 Content-Type field. Anything else will generate a TypeError.
Barry Warsaw409a4c02002-04-10 21:01:31 +0000235
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000236 The message will be assumed to be of type text/* encoded with
Barry Warsaw409a4c02002-04-10 21:01:31 +0000237 charset.input_charset. It will be converted to charset.output_charset
238 and encoded properly, if needed, when generating the plain text
239 representation of the message. MIME headers (MIME-Version,
240 Content-Type, Content-Transfer-Encoding) will be added as needed.
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000241
Barry Warsaw409a4c02002-04-10 21:01:31 +0000242 """
243 if charset is None:
244 self.del_param('charset')
245 self._charset = None
246 return
Martin v. Löwisbdd0f392007-03-13 10:24:00 +0000247 if isinstance(charset, basestring):
Barry Warsaw40ef0062006-03-18 15:41:53 +0000248 charset = email.charset.Charset(charset)
249 if not isinstance(charset, email.charset.Charset):
Barry Warsawbb113862004-10-03 03:16:19 +0000250 raise TypeError(charset)
Barry Warsaw409a4c02002-04-10 21:01:31 +0000251 # BAW: should we accept strings that can serve as arguments to the
252 # Charset constructor?
253 self._charset = charset
Benjamin Peterson6e3dbbd2009-10-09 22:15:50 +0000254 if 'MIME-Version' not in self:
Barry Warsaw409a4c02002-04-10 21:01:31 +0000255 self.add_header('MIME-Version', '1.0')
Benjamin Peterson6e3dbbd2009-10-09 22:15:50 +0000256 if 'Content-Type' not in self:
Barry Warsaw409a4c02002-04-10 21:01:31 +0000257 self.add_header('Content-Type', 'text/plain',
258 charset=charset.get_output_charset())
259 else:
260 self.set_param('charset', charset.get_output_charset())
R. David Murray52dcd452010-06-02 22:03:15 +0000261 if isinstance(self._payload, unicode):
262 self._payload = self._payload.encode(charset.output_charset)
Brett Cannon1f571c62008-08-03 23:27:32 +0000263 if str(charset) != charset.get_output_charset():
Barry Warsawe58df822006-02-08 14:34:21 +0000264 self._payload = charset.body_encode(self._payload)
Benjamin Peterson6e3dbbd2009-10-09 22:15:50 +0000265 if 'Content-Transfer-Encoding' not in self:
Barry Warsaw409a4c02002-04-10 21:01:31 +0000266 cte = charset.get_body_encoding()
Barry Warsawbb113862004-10-03 03:16:19 +0000267 try:
Barry Warsaw409a4c02002-04-10 21:01:31 +0000268 cte(self)
Barry Warsawbb113862004-10-03 03:16:19 +0000269 except TypeError:
Barry Warsawe58df822006-02-08 14:34:21 +0000270 self._payload = charset.body_encode(self._payload)
Barry Warsaw409a4c02002-04-10 21:01:31 +0000271 self.add_header('Content-Transfer-Encoding', cte)
272
273 def get_charset(self):
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000274 """Return the Charset instance associated with the message's payload.
275 """
Barry Warsaw409a4c02002-04-10 21:01:31 +0000276 return self._charset
Tim Peters8ac14952002-05-23 15:15:30 +0000277
Barry Warsawba925802001-09-23 03:17:28 +0000278 #
279 # MAPPING INTERFACE (partial)
280 #
281 def __len__(self):
Barry Warsawbeb59452001-09-26 05:41:51 +0000282 """Return the total number of headers, including duplicates."""
Barry Warsawba925802001-09-23 03:17:28 +0000283 return len(self._headers)
284
285 def __getitem__(self, name):
286 """Get a header value.
287
288 Return None if the header is missing instead of raising an exception.
289
290 Note that if the header appeared multiple times, exactly which
R. David Murray13219a32010-12-06 18:45:46 +0000291 occurrence gets returned is undefined. Use get_all() to get all
Barry Warsawba925802001-09-23 03:17:28 +0000292 the values matching a header field name.
293 """
294 return self.get(name)
295
296 def __setitem__(self, name, val):
297 """Set the value of a header.
298
299 Note: this does not overwrite an existing header with the same field
300 name. Use __delitem__() first to delete any existing headers.
301 """
302 self._headers.append((name, val))
303
304 def __delitem__(self, name):
305 """Delete all occurrences of a header, if present.
306
307 Does not raise an exception if the header is missing.
308 """
309 name = name.lower()
310 newheaders = []
311 for k, v in self._headers:
Brett Cannon1f571c62008-08-03 23:27:32 +0000312 if k.lower() != name:
Barry Warsawba925802001-09-23 03:17:28 +0000313 newheaders.append((k, v))
314 self._headers = newheaders
315
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000316 def __contains__(self, name):
317 return name.lower() in [k.lower() for k, v in self._headers]
Barry Warsawba925802001-09-23 03:17:28 +0000318
319 def has_key(self, name):
320 """Return true if the message contains the header."""
Barry Warsawbb113862004-10-03 03:16:19 +0000321 missing = object()
Barry Warsawbeb59452001-09-26 05:41:51 +0000322 return self.get(name, missing) is not missing
Barry Warsawba925802001-09-23 03:17:28 +0000323
324 def keys(self):
325 """Return a list of all the message's header field names.
326
327 These will be sorted in the order they appeared in the original
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000328 message, or were added to the message, and may contain duplicates.
329 Any fields deleted and re-inserted are always appended to the header
330 list.
Barry Warsawba925802001-09-23 03:17:28 +0000331 """
332 return [k for k, v in self._headers]
333
334 def values(self):
335 """Return a list of all the message's header values.
336
337 These will be sorted in the order they appeared in the original
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000338 message, or were added to the message, and may contain duplicates.
339 Any fields deleted and re-inserted are always appended to the header
340 list.
Barry Warsawba925802001-09-23 03:17:28 +0000341 """
342 return [v for k, v in self._headers]
343
344 def items(self):
345 """Get all the message's header fields and values.
346
347 These will be sorted in the order they appeared in the original
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000348 message, or were added to the message, and may contain duplicates.
349 Any fields deleted and re-inserted are always appended to the header
350 list.
Barry Warsawba925802001-09-23 03:17:28 +0000351 """
352 return self._headers[:]
353
354 def get(self, name, failobj=None):
355 """Get a header value.
356
357 Like __getitem__() but return failobj instead of None when the field
358 is missing.
359 """
360 name = name.lower()
361 for k, v in self._headers:
362 if k.lower() == name:
363 return v
364 return failobj
365
366 #
367 # Additional useful stuff
368 #
369
370 def get_all(self, name, failobj=None):
371 """Return a list of all the values for the named field.
372
373 These will be sorted in the order they appeared in the original
374 message, and may contain duplicates. Any fields deleted and
Greg Ward6253c2d2001-11-24 15:49:53 +0000375 re-inserted are always appended to the header list.
Barry Warsaw9300a752001-10-09 15:48:29 +0000376
377 If no such fields exist, failobj is returned (defaults to None).
Barry Warsawba925802001-09-23 03:17:28 +0000378 """
379 values = []
380 name = name.lower()
381 for k, v in self._headers:
382 if k.lower() == name:
383 values.append(v)
Barry Warsaw9300a752001-10-09 15:48:29 +0000384 if not values:
385 return failobj
Barry Warsawba925802001-09-23 03:17:28 +0000386 return values
387
388 def add_header(self, _name, _value, **_params):
389 """Extended header setting.
390
391 name is the header field to add. keyword arguments can be used to set
392 additional parameters for the header field, with underscores converted
393 to dashes. Normally the parameter will be added as key="value" unless
R. David Murraya9aa34c2010-12-14 00:29:27 +0000394 value is None, in which case only the key will be added. If a
395 parameter value contains non-ASCII characters it must be specified as a
396 three-tuple of (charset, language, value), in which case it will be
397 encoded according to RFC2231 rules.
Barry Warsawba925802001-09-23 03:17:28 +0000398
399 Example:
400
401 msg.add_header('content-disposition', 'attachment', filename='bud.gif')
Barry Warsawba925802001-09-23 03:17:28 +0000402 """
403 parts = []
404 for k, v in _params.items():
405 if v is None:
406 parts.append(k.replace('_', '-'))
407 else:
Barry Warsaw409a4c02002-04-10 21:01:31 +0000408 parts.append(_formatparam(k.replace('_', '-'), v))
Barry Warsawba925802001-09-23 03:17:28 +0000409 if _value is not None:
410 parts.insert(0, _value)
411 self._headers.append((_name, SEMISPACE.join(parts)))
412
Barry Warsaw229727f2002-09-06 03:38:12 +0000413 def replace_header(self, _name, _value):
414 """Replace a header.
415
416 Replace the first matching header found in the message, retaining
417 header order and case. If no matching header was found, a KeyError is
418 raised.
419 """
420 _name = _name.lower()
421 for i, (k, v) in zip(range(len(self._headers)), self._headers):
422 if k.lower() == _name:
423 self._headers[i] = (k, _value)
424 break
425 else:
Barry Warsawbb113862004-10-03 03:16:19 +0000426 raise KeyError(_name)
Barry Warsaw229727f2002-09-06 03:38:12 +0000427
Barry Warsawc1068642002-07-19 22:24:55 +0000428 #
Barry Warsawc1068642002-07-19 22:24:55 +0000429 # Use these three methods instead of the three above.
430 #
431
432 def get_content_type(self):
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000433 """Return the message's content type.
Barry Warsawc1068642002-07-19 22:24:55 +0000434
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000435 The returned string is coerced to lower case of the form
436 `maintype/subtype'. If there was no Content-Type header in the
437 message, the default type as given by get_default_type() will be
438 returned. Since according to RFC 2045, messages always have a default
439 type this will always return a value.
Barry Warsawc1068642002-07-19 22:24:55 +0000440
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000441 RFC 2045 defines a message's default type to be text/plain unless it
442 appears inside a multipart/digest container, in which case it would be
443 message/rfc822.
Barry Warsawc1068642002-07-19 22:24:55 +0000444 """
Barry Warsawbb113862004-10-03 03:16:19 +0000445 missing = object()
Barry Warsawc1068642002-07-19 22:24:55 +0000446 value = self.get('content-type', missing)
447 if value is missing:
448 # This should have no parameters
449 return self.get_default_type()
Antoine Pitroub90a8be2008-08-15 21:03:21 +0000450 ctype = _splitparam(value)[0].lower()
Barry Warsawf36d8042002-08-20 14:50:09 +0000451 # RFC 2045, section 5.2 says if its invalid, use text/plain
Brett Cannon1f571c62008-08-03 23:27:32 +0000452 if ctype.count('/') != 1:
Barry Warsawf36d8042002-08-20 14:50:09 +0000453 return 'text/plain'
454 return ctype
Barry Warsawc1068642002-07-19 22:24:55 +0000455
456 def get_content_maintype(self):
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000457 """Return the message's main content type.
Barry Warsawc1068642002-07-19 22:24:55 +0000458
459 This is the `maintype' part of the string returned by
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000460 get_content_type().
Barry Warsawc1068642002-07-19 22:24:55 +0000461 """
462 ctype = self.get_content_type()
Barry Warsawc1068642002-07-19 22:24:55 +0000463 return ctype.split('/')[0]
464
465 def get_content_subtype(self):
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000466 """Returns the message's sub-content type.
Barry Warsawc1068642002-07-19 22:24:55 +0000467
468 This is the `subtype' part of the string returned by
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000469 get_content_type().
Barry Warsawc1068642002-07-19 22:24:55 +0000470 """
471 ctype = self.get_content_type()
Barry Warsawc1068642002-07-19 22:24:55 +0000472 return ctype.split('/')[1]
Barry Warsawba925802001-09-23 03:17:28 +0000473
Barry Warsawa0c8b9d2002-07-09 02:46:12 +0000474 def get_default_type(self):
475 """Return the `default' content type.
476
477 Most messages have a default content type of text/plain, except for
478 messages that are subparts of multipart/digest containers. Such
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000479 subparts have a default content type of message/rfc822.
Barry Warsawa0c8b9d2002-07-09 02:46:12 +0000480 """
481 return self._default_type
482
483 def set_default_type(self, ctype):
484 """Set the `default' content type.
485
Barry Warsawc1068642002-07-19 22:24:55 +0000486 ctype should be either "text/plain" or "message/rfc822", although this
487 is not enforced. The default content type is not stored in the
Barry Warsawc4945492002-09-28 20:40:25 +0000488 Content-Type header.
Barry Warsawa0c8b9d2002-07-09 02:46:12 +0000489 """
Barry Warsawa0c8b9d2002-07-09 02:46:12 +0000490 self._default_type = ctype
491
Barry Warsawbeb59452001-09-26 05:41:51 +0000492 def _get_params_preserve(self, failobj, header):
493 # Like get_params() but preserves the quoting of values. BAW:
494 # should this be part of the public interface?
Barry Warsawbb113862004-10-03 03:16:19 +0000495 missing = object()
Barry Warsawbeb59452001-09-26 05:41:51 +0000496 value = self.get(header, missing)
497 if value is missing:
498 return failobj
499 params = []
Barry Warsawa74e8682003-09-03 04:08:13 +0000500 for p in _parseparam(';' + value):
Barry Warsawbeb59452001-09-26 05:41:51 +0000501 try:
502 name, val = p.split('=', 1)
Barry Warsaw7aeac912002-07-18 23:09:09 +0000503 name = name.strip()
504 val = val.strip()
Barry Warsawbeb59452001-09-26 05:41:51 +0000505 except ValueError:
506 # Must have been a bare attribute
Barry Warsaw7aeac912002-07-18 23:09:09 +0000507 name = p.strip()
Barry Warsawbeb59452001-09-26 05:41:51 +0000508 val = ''
509 params.append((name, val))
Barry Warsaw40ef0062006-03-18 15:41:53 +0000510 params = utils.decode_params(params)
Barry Warsawbeb59452001-09-26 05:41:51 +0000511 return params
512
Barry Warsawc4945492002-09-28 20:40:25 +0000513 def get_params(self, failobj=None, header='content-type', unquote=True):
514 """Return the message's Content-Type parameters, as a list.
Barry Warsawba925802001-09-23 03:17:28 +0000515
Barry Warsawbeb59452001-09-26 05:41:51 +0000516 The elements of the returned list are 2-tuples of key/value pairs, as
517 split on the `=' sign. The left hand side of the `=' is the key,
518 while the right hand side is the value. If there is no `=' sign in
Barry Warsaw15aefa92002-09-26 17:19:34 +0000519 the parameter the value is the empty string. The value is as
520 described in the get_param() method.
Barry Warsawbeb59452001-09-26 05:41:51 +0000521
Barry Warsawc4945492002-09-28 20:40:25 +0000522 Optional failobj is the object to return if there is no Content-Type
Barry Warsawba925802001-09-23 03:17:28 +0000523 header. Optional header is the header to search instead of
Barry Warsawc4945492002-09-28 20:40:25 +0000524 Content-Type. If unquote is True, the value is unquoted.
Barry Warsawba925802001-09-23 03:17:28 +0000525 """
Barry Warsawbb113862004-10-03 03:16:19 +0000526 missing = object()
Barry Warsawbeb59452001-09-26 05:41:51 +0000527 params = self._get_params_preserve(missing, header)
528 if params is missing:
Barry Warsawba925802001-09-23 03:17:28 +0000529 return failobj
Barry Warsaw409a4c02002-04-10 21:01:31 +0000530 if unquote:
Barry Warsaw908dc4b2002-06-29 05:56:15 +0000531 return [(k, _unquotevalue(v)) for k, v in params]
Barry Warsaw409a4c02002-04-10 21:01:31 +0000532 else:
533 return params
Barry Warsawba925802001-09-23 03:17:28 +0000534
Barry Warsawc4945492002-09-28 20:40:25 +0000535 def get_param(self, param, failobj=None, header='content-type',
536 unquote=True):
537 """Return the parameter value if found in the Content-Type header.
Barry Warsawba925802001-09-23 03:17:28 +0000538
Barry Warsawc4945492002-09-28 20:40:25 +0000539 Optional failobj is the object to return if there is no Content-Type
Barry Warsaw15aefa92002-09-26 17:19:34 +0000540 header, or the Content-Type header has no such parameter. Optional
Barry Warsawc4945492002-09-28 20:40:25 +0000541 header is the header to search instead of Content-Type.
Barry Warsawbeb59452001-09-26 05:41:51 +0000542
Barry Warsaw15aefa92002-09-26 17:19:34 +0000543 Parameter keys are always compared case insensitively. The return
544 value can either be a string, or a 3-tuple if the parameter was RFC
545 2231 encoded. When it's a 3-tuple, the elements of the value are of
Barry Warsaw62083692003-08-19 03:53:02 +0000546 the form (CHARSET, LANGUAGE, VALUE). Note that both CHARSET and
547 LANGUAGE can be None, in which case you should consider VALUE to be
548 encoded in the us-ascii charset. You can usually ignore LANGUAGE.
549
550 Your application should be prepared to deal with 3-tuple return
551 values, and can convert the parameter to a Unicode string like so:
Barry Warsaw15aefa92002-09-26 17:19:34 +0000552
553 param = msg.get_param('foo')
554 if isinstance(param, tuple):
Barry Warsaw62083692003-08-19 03:53:02 +0000555 param = unicode(param[2], param[0] or 'us-ascii')
Barry Warsaw15aefa92002-09-26 17:19:34 +0000556
557 In any case, the parameter value (either the returned string, or the
558 VALUE item in the 3-tuple) is always unquoted, unless unquote is set
Barry Warsawc4945492002-09-28 20:40:25 +0000559 to False.
Barry Warsawba925802001-09-23 03:17:28 +0000560 """
Benjamin Peterson6e3dbbd2009-10-09 22:15:50 +0000561 if header not in self:
Barry Warsawba925802001-09-23 03:17:28 +0000562 return failobj
Barry Warsawbeb59452001-09-26 05:41:51 +0000563 for k, v in self._get_params_preserve(failobj, header):
564 if k.lower() == param.lower():
Barry Warsaw409a4c02002-04-10 21:01:31 +0000565 if unquote:
Barry Warsaw908dc4b2002-06-29 05:56:15 +0000566 return _unquotevalue(v)
Barry Warsaw409a4c02002-04-10 21:01:31 +0000567 else:
568 return v
Barry Warsawba925802001-09-23 03:17:28 +0000569 return failobj
570
Barry Warsawc4945492002-09-28 20:40:25 +0000571 def set_param(self, param, value, header='Content-Type', requote=True,
Barry Warsaw3c255352002-09-06 03:55:04 +0000572 charset=None, language=''):
Barry Warsawc4945492002-09-28 20:40:25 +0000573 """Set a parameter in the Content-Type header.
Barry Warsaw409a4c02002-04-10 21:01:31 +0000574
575 If the parameter already exists in the header, its value will be
576 replaced with the new value.
577
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000578 If header is Content-Type and has not yet been defined for this
Barry Warsaw409a4c02002-04-10 21:01:31 +0000579 message, it will be set to "text/plain" and the new parameter and
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000580 value will be appended as per RFC 2045.
Barry Warsaw409a4c02002-04-10 21:01:31 +0000581
Barry Warsawc4945492002-09-28 20:40:25 +0000582 An alternate header can specified in the header argument, and all
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000583 parameters will be quoted as necessary unless requote is False.
Barry Warsaw3c255352002-09-06 03:55:04 +0000584
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000585 If charset is specified, the parameter will be encoded according to RFC
586 2231. Optional language specifies the RFC 2231 language, defaulting
587 to the empty string. Both charset and language should be strings.
Barry Warsaw409a4c02002-04-10 21:01:31 +0000588 """
Barry Warsaw5d840532004-05-09 03:44:55 +0000589 if not isinstance(value, tuple) and charset:
Barry Warsaw3c255352002-09-06 03:55:04 +0000590 value = (charset, language, value)
591
Benjamin Peterson6e3dbbd2009-10-09 22:15:50 +0000592 if header not in self and header.lower() == 'content-type':
Barry Warsaw409a4c02002-04-10 21:01:31 +0000593 ctype = 'text/plain'
594 else:
595 ctype = self.get(header)
596 if not self.get_param(param, header=header):
597 if not ctype:
598 ctype = _formatparam(param, value, requote)
599 else:
600 ctype = SEMISPACE.join(
601 [ctype, _formatparam(param, value, requote)])
602 else:
603 ctype = ''
604 for old_param, old_value in self.get_params(header=header,
605 unquote=requote):
606 append_param = ''
607 if old_param.lower() == param.lower():
608 append_param = _formatparam(param, value, requote)
609 else:
610 append_param = _formatparam(old_param, old_value, requote)
611 if not ctype:
612 ctype = append_param
613 else:
614 ctype = SEMISPACE.join([ctype, append_param])
Brett Cannon1f571c62008-08-03 23:27:32 +0000615 if ctype != self.get(header):
Barry Warsaw409a4c02002-04-10 21:01:31 +0000616 del self[header]
617 self[header] = ctype
618
Barry Warsawc4945492002-09-28 20:40:25 +0000619 def del_param(self, param, header='content-type', requote=True):
Barry Warsaw409a4c02002-04-10 21:01:31 +0000620 """Remove the given parameter completely from the Content-Type header.
621
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000622 The header will be re-written in place without the parameter or its
623 value. All values will be quoted as necessary unless requote is
624 False. Optional header specifies an alternative to the Content-Type
625 header.
Barry Warsaw409a4c02002-04-10 21:01:31 +0000626 """
Benjamin Peterson6e3dbbd2009-10-09 22:15:50 +0000627 if header not in self:
Barry Warsaw409a4c02002-04-10 21:01:31 +0000628 return
629 new_ctype = ''
Barry Warsaw06fa0422004-08-16 15:47:34 +0000630 for p, v in self.get_params(header=header, unquote=requote):
Brett Cannon1f571c62008-08-03 23:27:32 +0000631 if p.lower() != param.lower():
Barry Warsaw409a4c02002-04-10 21:01:31 +0000632 if not new_ctype:
633 new_ctype = _formatparam(p, v, requote)
634 else:
635 new_ctype = SEMISPACE.join([new_ctype,
636 _formatparam(p, v, requote)])
Brett Cannon1f571c62008-08-03 23:27:32 +0000637 if new_ctype != self.get(header):
Barry Warsaw409a4c02002-04-10 21:01:31 +0000638 del self[header]
639 self[header] = new_ctype
640
Barry Warsawc4945492002-09-28 20:40:25 +0000641 def set_type(self, type, header='Content-Type', requote=True):
642 """Set the main type and subtype for the Content-Type header.
Barry Warsaw409a4c02002-04-10 21:01:31 +0000643
644 type must be a string in the form "maintype/subtype", otherwise a
645 ValueError is raised.
646
Barry Warsawc4945492002-09-28 20:40:25 +0000647 This method replaces the Content-Type header, keeping all the
648 parameters in place. If requote is False, this leaves the existing
Barry Warsaw409a4c02002-04-10 21:01:31 +0000649 header's quoting as is. Otherwise, the parameters will be quoted (the
650 default).
651
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000652 An alternative header can be specified in the header argument. When
653 the Content-Type header is set, we'll always also add a MIME-Version
Barry Warsaw409a4c02002-04-10 21:01:31 +0000654 header.
655 """
656 # BAW: should we be strict?
657 if not type.count('/') == 1:
658 raise ValueError
Barry Warsawc4945492002-09-28 20:40:25 +0000659 # Set the Content-Type, you get a MIME-Version
Barry Warsaw409a4c02002-04-10 21:01:31 +0000660 if header.lower() == 'content-type':
661 del self['mime-version']
662 self['MIME-Version'] = '1.0'
Benjamin Peterson6e3dbbd2009-10-09 22:15:50 +0000663 if header not in self:
Barry Warsaw409a4c02002-04-10 21:01:31 +0000664 self[header] = type
665 return
Barry Warsaw06fa0422004-08-16 15:47:34 +0000666 params = self.get_params(header=header, unquote=requote)
Barry Warsaw409a4c02002-04-10 21:01:31 +0000667 del self[header]
668 self[header] = type
669 # Skip the first param; it's the old type.
670 for p, v in params[1:]:
671 self.set_param(p, v, header, requote)
672
Barry Warsawba925802001-09-23 03:17:28 +0000673 def get_filename(self, failobj=None):
674 """Return the filename associated with the payload if present.
675
Barry Warsawc4945492002-09-28 20:40:25 +0000676 The filename is extracted from the Content-Disposition header's
Barry Warsawa0f28ef2006-01-17 04:49:07 +0000677 `filename' parameter, and it is unquoted. If that header is missing
678 the `filename' parameter, this method falls back to looking for the
679 `name' parameter.
Barry Warsawba925802001-09-23 03:17:28 +0000680 """
Barry Warsawbb113862004-10-03 03:16:19 +0000681 missing = object()
Barry Warsawba925802001-09-23 03:17:28 +0000682 filename = self.get_param('filename', missing, 'content-disposition')
683 if filename is missing:
R. David Murray0c8bee62009-10-09 21:50:54 +0000684 filename = self.get_param('name', missing, 'content-type')
Barry Warsawa0f28ef2006-01-17 04:49:07 +0000685 if filename is missing:
Barry Warsawba925802001-09-23 03:17:28 +0000686 return failobj
Barry Warsaw40ef0062006-03-18 15:41:53 +0000687 return utils.collapse_rfc2231_value(filename).strip()
Barry Warsawba925802001-09-23 03:17:28 +0000688
689 def get_boundary(self, failobj=None):
690 """Return the boundary associated with the payload if present.
691
Barry Warsawc4945492002-09-28 20:40:25 +0000692 The boundary is extracted from the Content-Type header's `boundary'
Barry Warsawba925802001-09-23 03:17:28 +0000693 parameter, and it is unquoted.
694 """
Barry Warsawbb113862004-10-03 03:16:19 +0000695 missing = object()
Barry Warsawba925802001-09-23 03:17:28 +0000696 boundary = self.get_param('boundary', missing)
697 if boundary is missing:
698 return failobj
Barry Warsaw93d9d5f2004-11-06 00:04:52 +0000699 # RFC 2046 says that boundaries may begin but not end in w/s
Barry Warsaw40ef0062006-03-18 15:41:53 +0000700 return utils.collapse_rfc2231_value(boundary).rstrip()
Barry Warsawba925802001-09-23 03:17:28 +0000701
702 def set_boundary(self, boundary):
Barry Warsawc4945492002-09-28 20:40:25 +0000703 """Set the boundary parameter in Content-Type to 'boundary'.
Barry Warsawba925802001-09-23 03:17:28 +0000704
Barry Warsawc4945492002-09-28 20:40:25 +0000705 This is subtly different than deleting the Content-Type header and
Barry Warsawba925802001-09-23 03:17:28 +0000706 adding a new one with a new boundary parameter via add_header(). The
707 main difference is that using the set_boundary() method preserves the
Barry Warsawc4945492002-09-28 20:40:25 +0000708 order of the Content-Type header in the original message.
Barry Warsawba925802001-09-23 03:17:28 +0000709
Barry Warsawc4945492002-09-28 20:40:25 +0000710 HeaderParseError is raised if the message has no Content-Type header.
Barry Warsawba925802001-09-23 03:17:28 +0000711 """
Barry Warsawbb113862004-10-03 03:16:19 +0000712 missing = object()
Barry Warsawbeb59452001-09-26 05:41:51 +0000713 params = self._get_params_preserve(missing, 'content-type')
714 if params is missing:
Barry Warsawc4945492002-09-28 20:40:25 +0000715 # There was no Content-Type header, and we don't know what type
Barry Warsawba925802001-09-23 03:17:28 +0000716 # to set it to, so raise an exception.
Barry Warsaw40ef0062006-03-18 15:41:53 +0000717 raise errors.HeaderParseError('No Content-Type header found')
Barry Warsawba925802001-09-23 03:17:28 +0000718 newparams = []
Barry Warsawc4945492002-09-28 20:40:25 +0000719 foundp = False
Barry Warsawbeb59452001-09-26 05:41:51 +0000720 for pk, pv in params:
721 if pk.lower() == 'boundary':
722 newparams.append(('boundary', '"%s"' % boundary))
Barry Warsawc4945492002-09-28 20:40:25 +0000723 foundp = True
Barry Warsawba925802001-09-23 03:17:28 +0000724 else:
Barry Warsawbeb59452001-09-26 05:41:51 +0000725 newparams.append((pk, pv))
Barry Warsawba925802001-09-23 03:17:28 +0000726 if not foundp:
Barry Warsawc4945492002-09-28 20:40:25 +0000727 # The original Content-Type header had no boundary attribute.
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000728 # Tack one on the end. BAW: should we raise an exception
Barry Warsawba925802001-09-23 03:17:28 +0000729 # instead???
Barry Warsawbeb59452001-09-26 05:41:51 +0000730 newparams.append(('boundary', '"%s"' % boundary))
Barry Warsawc4945492002-09-28 20:40:25 +0000731 # Replace the existing Content-Type header with the new value
Barry Warsawba925802001-09-23 03:17:28 +0000732 newheaders = []
733 for h, v in self._headers:
734 if h.lower() == 'content-type':
Barry Warsawbeb59452001-09-26 05:41:51 +0000735 parts = []
736 for k, v in newparams:
737 if v == '':
738 parts.append(k)
739 else:
740 parts.append('%s=%s' % (k, v))
741 newheaders.append((h, SEMISPACE.join(parts)))
742
Barry Warsawba925802001-09-23 03:17:28 +0000743 else:
744 newheaders.append((h, v))
745 self._headers = newheaders
746
Barry Warsaw15aefa92002-09-26 17:19:34 +0000747 def get_content_charset(self, failobj=None):
748 """Return the charset parameter of the Content-Type header.
749
Barry Warsawee07cb12002-10-10 15:13:26 +0000750 The returned string is always coerced to lower case. If there is no
751 Content-Type header, or if that header has no charset parameter,
752 failobj is returned.
Barry Warsaw15aefa92002-09-26 17:19:34 +0000753 """
Barry Warsawbb113862004-10-03 03:16:19 +0000754 missing = object()
Barry Warsaw15aefa92002-09-26 17:19:34 +0000755 charset = self.get_param('charset', missing)
756 if charset is missing:
757 return failobj
Barry Warsaw5d840532004-05-09 03:44:55 +0000758 if isinstance(charset, tuple):
Barry Warsaw15aefa92002-09-26 17:19:34 +0000759 # RFC 2231 encoded, so decode it, and it better end up as ascii.
Barry Warsaw62083692003-08-19 03:53:02 +0000760 pcharset = charset[0] or 'us-ascii'
Barry Warsawd92ae782006-07-26 05:54:46 +0000761 try:
762 # LookupError will be raised if the charset isn't known to
763 # Python. UnicodeError will be raised if the encoded text
764 # contains a character not in the charset.
765 charset = unicode(charset[2], pcharset).encode('us-ascii')
766 except (LookupError, UnicodeError):
767 charset = charset[2]
768 # charset character must be in us-ascii range
769 try:
Martin v. Löwisbdd0f392007-03-13 10:24:00 +0000770 if isinstance(charset, str):
771 charset = unicode(charset, 'us-ascii')
772 charset = charset.encode('us-ascii')
Barry Warsawd92ae782006-07-26 05:54:46 +0000773 except UnicodeError:
774 return failobj
Barry Warsawee07cb12002-10-10 15:13:26 +0000775 # RFC 2046, $4.1.2 says charsets are not case sensitive
776 return charset.lower()
Barry Warsaw15aefa92002-09-26 17:19:34 +0000777
Barry Warsawba925802001-09-23 03:17:28 +0000778 def get_charsets(self, failobj=None):
779 """Return a list containing the charset(s) used in this message.
Tim Peters527e64f2001-10-04 05:36:56 +0000780
Barry Warsawc4945492002-09-28 20:40:25 +0000781 The returned list of items describes the Content-Type headers'
Barry Warsawba925802001-09-23 03:17:28 +0000782 charset parameter for this message and all the subparts in its
783 payload.
784
785 Each item will either be a string (the value of the charset parameter
Barry Warsawc4945492002-09-28 20:40:25 +0000786 in the Content-Type header of that part) or the value of the
Barry Warsawba925802001-09-23 03:17:28 +0000787 'failobj' parameter (defaults to None), if the part does not have a
788 main MIME type of "text", or the charset is not defined.
789
790 The list will contain one string for each part of the message, plus
791 one for the container message (i.e. self), so that a non-multipart
792 message will still return a list of length 1.
793 """
Barry Warsaw15aefa92002-09-26 17:19:34 +0000794 return [part.get_content_charset(failobj) for part in self.walk()]
Barry Warsaw5d840532004-05-09 03:44:55 +0000795
796 # I.e. def walk(self): ...
Amaury Forgeot d'Arc74b8d332009-07-11 14:33:51 +0000797 from email.iterators import walk