blob: 23cedf6143a71b5ec4c94c6baa9fd9207f77ca31 [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
Barry Warsaw908dc4b2002-06-29 05:56:15 +000041 This will quote the value if needed or if quote is true.
Barry Warsaw409a4c02002-04-10 21:01:31 +000042 """
43 if value is not None and len(value) > 0:
Barry Warsaw5d840532004-05-09 03:44:55 +000044 # A tuple is used for RFC 2231 encoded parameter values where items
Barry Warsaw908dc4b2002-06-29 05:56:15 +000045 # are (charset, language, value). charset is a string, not a Charset
46 # instance.
Barry Warsaw5d840532004-05-09 03:44:55 +000047 if isinstance(value, tuple):
Barry Warsaw3c255352002-09-06 03:55:04 +000048 # Encode as per RFC 2231
49 param += '*'
Barry Warsaw40ef0062006-03-18 15:41:53 +000050 value = utils.encode_rfc2231(value[2], value[0], value[1])
Barry Warsaw409a4c02002-04-10 21:01:31 +000051 # BAW: Please check this. I think that if quote is set it should
52 # force quoting even if not necessary.
53 if quote or tspecials.search(value):
Barry Warsaw40ef0062006-03-18 15:41:53 +000054 return '%s="%s"' % (param, utils.quote(value))
Barry Warsaw409a4c02002-04-10 21:01:31 +000055 else:
56 return '%s=%s' % (param, value)
57 else:
58 return param
Barry Warsawbeb59452001-09-26 05:41:51 +000059
Barry Warsawa74e8682003-09-03 04:08:13 +000060def _parseparam(s):
61 plist = []
62 while s[:1] == ';':
63 s = s[1:]
64 end = s.find(';')
65 while end > 0 and s.count('"', 0, end) % 2:
66 end = s.find(';', end + 1)
67 if end < 0:
68 end = len(s)
69 f = s[:end]
70 if '=' in f:
71 i = f.index('=')
72 f = f[:i].strip().lower() + '=' + f[i+1:].strip()
73 plist.append(f.strip())
74 s = s[end:]
75 return plist
76
Barry Warsawba925802001-09-23 03:17:28 +000077
Barry Warsaw908dc4b2002-06-29 05:56:15 +000078def _unquotevalue(value):
Barry Warsaw40ef0062006-03-18 15:41:53 +000079 # This is different than utils.collapse_rfc2231_value() because it doesn't
Barry Warsawbb113862004-10-03 03:16:19 +000080 # try to convert the value to a unicode. Message.get_param() and
81 # Message.get_params() are both currently defined to return the tuple in
82 # the face of RFC 2231 parameters.
Barry Warsaw5d840532004-05-09 03:44:55 +000083 if isinstance(value, tuple):
Barry Warsaw40ef0062006-03-18 15:41:53 +000084 return value[0], value[1], utils.unquote(value[2])
Barry Warsaw908dc4b2002-06-29 05:56:15 +000085 else:
Barry Warsaw40ef0062006-03-18 15:41:53 +000086 return utils.unquote(value)
Barry Warsaw908dc4b2002-06-29 05:56:15 +000087
88
Barry Warsaw48b0d362002-08-27 22:34:44 +000089
Barry Warsawba925802001-09-23 03:17:28 +000090class Message:
Barry Warsaw42d1d3e2002-09-30 18:17:35 +000091 """Basic message object.
Barry Warsawba925802001-09-23 03:17:28 +000092
93 A message object is defined as something that has a bunch of RFC 2822
Barry Warsaw42d1d3e2002-09-30 18:17:35 +000094 headers and a payload. It may optionally have an envelope header
95 (a.k.a. Unix-From or From_ header). If the message is a container (i.e. a
96 multipart or a message/rfc822), then the payload is a list of Message
97 objects, otherwise it is a string.
Barry Warsawba925802001-09-23 03:17:28 +000098
Barry Warsaw42d1d3e2002-09-30 18:17:35 +000099 Message objects implement part of the `mapping' interface, which assumes
Barry Warsawba925802001-09-23 03:17:28 +0000100 there is exactly one occurrance of the header per message. Some headers
Barry Warsawc4945492002-09-28 20:40:25 +0000101 do in fact appear multiple times (e.g. Received) and for those headers,
Barry Warsawba925802001-09-23 03:17:28 +0000102 you must use the explicit API to set or get all the headers. Not all of
103 the mapping methods are implemented.
Barry Warsawba925802001-09-23 03:17:28 +0000104 """
105 def __init__(self):
106 self._headers = []
107 self._unixfrom = None
108 self._payload = None
Barry Warsaw409a4c02002-04-10 21:01:31 +0000109 self._charset = None
Barry Warsawba925802001-09-23 03:17:28 +0000110 # Defaults for multipart messages
111 self.preamble = self.epilogue = None
Barry Warsawbb113862004-10-03 03:16:19 +0000112 self.defects = []
Barry Warsawa0c8b9d2002-07-09 02:46:12 +0000113 # Default content type
114 self._default_type = 'text/plain'
Barry Warsawba925802001-09-23 03:17:28 +0000115
116 def __str__(self):
117 """Return the entire formatted message as a string.
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000118 This includes the headers, body, and envelope header.
Barry Warsawba925802001-09-23 03:17:28 +0000119 """
Barry Warsawc4945492002-09-28 20:40:25 +0000120 return self.as_string(unixfrom=True)
Barry Warsawba925802001-09-23 03:17:28 +0000121
Barry Warsawc4945492002-09-28 20:40:25 +0000122 def as_string(self, unixfrom=False):
Barry Warsawba925802001-09-23 03:17:28 +0000123 """Return the entire formatted message as a string.
Barry Warsawc4945492002-09-28 20:40:25 +0000124 Optional `unixfrom' when True, means include the Unix From_ envelope
Barry Warsawba925802001-09-23 03:17:28 +0000125 header.
Barry Warsaw482c5f72003-04-18 23:04:35 +0000126
127 This is a convenience method and may not generate the message exactly
Barry Warsaw05bef932004-10-03 03:38:07 +0000128 as you intend because by default it mangles lines that begin with
129 "From ". For more flexibility, use the flatten() method of a
Barry Warsaw482c5f72003-04-18 23:04:35 +0000130 Generator instance.
Barry Warsawba925802001-09-23 03:17:28 +0000131 """
Barry Warsaw8ba76e82002-06-02 19:05:51 +0000132 from email.Generator import Generator
Barry Warsawba925802001-09-23 03:17:28 +0000133 fp = StringIO()
134 g = Generator(fp)
Barry Warsaw8ba76e82002-06-02 19:05:51 +0000135 g.flatten(self, unixfrom=unixfrom)
Barry Warsawba925802001-09-23 03:17:28 +0000136 return fp.getvalue()
137
138 def is_multipart(self):
Barry Warsawc4945492002-09-28 20:40:25 +0000139 """Return True if the message consists of multiple parts."""
Barry Warsawbb113862004-10-03 03:16:19 +0000140 return isinstance(self._payload, list)
Barry Warsawba925802001-09-23 03:17:28 +0000141
142 #
143 # Unix From_ line
144 #
145 def set_unixfrom(self, unixfrom):
146 self._unixfrom = unixfrom
147
148 def get_unixfrom(self):
149 return self._unixfrom
150
151 #
152 # Payload manipulation.
153 #
Barry Warsaw409a4c02002-04-10 21:01:31 +0000154 def attach(self, payload):
155 """Add the given payload to the current payload.
156
157 The current payload will always be a list of objects after this method
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000158 is called. If you want to set the payload to a scalar object, use
Barry Warsaw409a4c02002-04-10 21:01:31 +0000159 set_payload() instead.
160 """
161 if self._payload is None:
162 self._payload = [payload]
163 else:
164 self._payload.append(payload)
Barry Warsawba925802001-09-23 03:17:28 +0000165
Barry Warsawc4945492002-09-28 20:40:25 +0000166 def get_payload(self, i=None, decode=False):
Barry Warsawfbcde752002-09-11 14:11:35 +0000167 """Return a reference to the payload.
Barry Warsawba925802001-09-23 03:17:28 +0000168
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000169 The payload will either be a list object or a string. If you mutate
170 the list object, you modify the message's payload in place. Optional
171 i returns that index into the payload.
Barry Warsawba925802001-09-23 03:17:28 +0000172
Barry Warsaw08898492003-03-11 04:33:30 +0000173 Optional decode is a flag indicating whether the payload should be
174 decoded or not, according to the Content-Transfer-Encoding header
175 (default is False).
176
177 When True and the message is not a multipart, the payload will be
178 decoded if this header's value is `quoted-printable' or `base64'. If
179 some other encoding is used, or the header is missing, or if the
180 payload has bogus data (i.e. bogus base64 or uuencoded data), the
181 payload is returned as-is.
Barry Warsaw21191d32003-03-10 16:13:14 +0000182
183 If the message is a multipart and the decode flag is True, then None
184 is returned.
Barry Warsawba925802001-09-23 03:17:28 +0000185 """
186 if i is None:
187 payload = self._payload
Barry Warsaw5d840532004-05-09 03:44:55 +0000188 elif not isinstance(self._payload, list):
Barry Warsawbb113862004-10-03 03:16:19 +0000189 raise TypeError('Expected list, got %s' % type(self._payload))
Barry Warsawba925802001-09-23 03:17:28 +0000190 else:
191 payload = self._payload[i]
192 if decode:
193 if self.is_multipart():
194 return None
Barry Warsaw08898492003-03-11 04:33:30 +0000195 cte = self.get('content-transfer-encoding', '').lower()
196 if cte == 'quoted-printable':
Barry Warsaw40ef0062006-03-18 15:41:53 +0000197 return utils._qdecode(payload)
Barry Warsaw08898492003-03-11 04:33:30 +0000198 elif cte == 'base64':
Barry Warsaw21191d32003-03-10 16:13:14 +0000199 try:
Barry Warsaw40ef0062006-03-18 15:41:53 +0000200 return utils._bdecode(payload)
Barry Warsaw21191d32003-03-10 16:13:14 +0000201 except binascii.Error:
202 # Incorrect padding
203 return payload
Barry Warsaw08898492003-03-11 04:33:30 +0000204 elif cte in ('x-uuencode', 'uuencode', 'uue', 'x-uue'):
205 sfp = StringIO()
206 try:
Barry Warsaw40ef0062006-03-18 15:41:53 +0000207 uu.decode(StringIO(payload+'\n'), sfp, quiet=True)
Barry Warsaw08898492003-03-11 04:33:30 +0000208 payload = sfp.getvalue()
209 except uu.Error:
210 # Some decoding problem
211 return payload
Barry Warsawba925802001-09-23 03:17:28 +0000212 # Everything else, including encodings with 8bit or 7bit are returned
213 # unchanged.
214 return payload
215
Barry Warsaw409a4c02002-04-10 21:01:31 +0000216 def set_payload(self, payload, charset=None):
217 """Set the payload to the given value.
Barry Warsawba925802001-09-23 03:17:28 +0000218
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000219 Optional charset sets the message's default character set. See
220 set_charset() for details.
221 """
Barry Warsaw409a4c02002-04-10 21:01:31 +0000222 self._payload = payload
223 if charset is not None:
224 self.set_charset(charset)
225
226 def set_charset(self, charset):
227 """Set the charset of the payload to a given character set.
228
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000229 charset can be a Charset instance, a string naming a character set, or
230 None. If it is a string it will be converted to a Charset instance.
231 If charset is None, the charset parameter will be removed from the
232 Content-Type field. Anything else will generate a TypeError.
Barry Warsaw409a4c02002-04-10 21:01:31 +0000233
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000234 The message will be assumed to be of type text/* encoded with
Barry Warsaw409a4c02002-04-10 21:01:31 +0000235 charset.input_charset. It will be converted to charset.output_charset
236 and encoded properly, if needed, when generating the plain text
237 representation of the message. MIME headers (MIME-Version,
238 Content-Type, Content-Transfer-Encoding) will be added as needed.
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000239
Barry Warsaw409a4c02002-04-10 21:01:31 +0000240 """
241 if charset is None:
242 self.del_param('charset')
243 self._charset = None
244 return
Martin v. Löwisbdd0f392007-03-13 10:24:00 +0000245 if isinstance(charset, basestring):
Barry Warsaw40ef0062006-03-18 15:41:53 +0000246 charset = email.charset.Charset(charset)
247 if not isinstance(charset, email.charset.Charset):
Barry Warsawbb113862004-10-03 03:16:19 +0000248 raise TypeError(charset)
Barry Warsaw409a4c02002-04-10 21:01:31 +0000249 # BAW: should we accept strings that can serve as arguments to the
250 # Charset constructor?
251 self._charset = charset
252 if not self.has_key('MIME-Version'):
253 self.add_header('MIME-Version', '1.0')
254 if not self.has_key('Content-Type'):
255 self.add_header('Content-Type', 'text/plain',
256 charset=charset.get_output_charset())
257 else:
258 self.set_param('charset', charset.get_output_charset())
Brett Cannon1f571c62008-08-03 23:27:32 +0000259 if str(charset) != charset.get_output_charset():
Barry Warsawe58df822006-02-08 14:34:21 +0000260 self._payload = charset.body_encode(self._payload)
Barry Warsaw409a4c02002-04-10 21:01:31 +0000261 if not self.has_key('Content-Transfer-Encoding'):
262 cte = charset.get_body_encoding()
Barry Warsawbb113862004-10-03 03:16:19 +0000263 try:
Barry Warsaw409a4c02002-04-10 21:01:31 +0000264 cte(self)
Barry Warsawbb113862004-10-03 03:16:19 +0000265 except TypeError:
Barry Warsawe58df822006-02-08 14:34:21 +0000266 self._payload = charset.body_encode(self._payload)
Barry Warsaw409a4c02002-04-10 21:01:31 +0000267 self.add_header('Content-Transfer-Encoding', cte)
268
269 def get_charset(self):
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000270 """Return the Charset instance associated with the message's payload.
271 """
Barry Warsaw409a4c02002-04-10 21:01:31 +0000272 return self._charset
Tim Peters8ac14952002-05-23 15:15:30 +0000273
Barry Warsawba925802001-09-23 03:17:28 +0000274 #
275 # MAPPING INTERFACE (partial)
276 #
277 def __len__(self):
Barry Warsawbeb59452001-09-26 05:41:51 +0000278 """Return the total number of headers, including duplicates."""
Barry Warsawba925802001-09-23 03:17:28 +0000279 return len(self._headers)
280
281 def __getitem__(self, name):
282 """Get a header value.
283
284 Return None if the header is missing instead of raising an exception.
285
286 Note that if the header appeared multiple times, exactly which
Barry Warsawbb113862004-10-03 03:16:19 +0000287 occurrance gets returned is undefined. Use get_all() to get all
Barry Warsawba925802001-09-23 03:17:28 +0000288 the values matching a header field name.
289 """
290 return self.get(name)
291
292 def __setitem__(self, name, val):
293 """Set the value of a header.
294
295 Note: this does not overwrite an existing header with the same field
296 name. Use __delitem__() first to delete any existing headers.
297 """
298 self._headers.append((name, val))
299
300 def __delitem__(self, name):
301 """Delete all occurrences of a header, if present.
302
303 Does not raise an exception if the header is missing.
304 """
305 name = name.lower()
306 newheaders = []
307 for k, v in self._headers:
Brett Cannon1f571c62008-08-03 23:27:32 +0000308 if k.lower() != name:
Barry Warsawba925802001-09-23 03:17:28 +0000309 newheaders.append((k, v))
310 self._headers = newheaders
311
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000312 def __contains__(self, name):
313 return name.lower() in [k.lower() for k, v in self._headers]
Barry Warsawba925802001-09-23 03:17:28 +0000314
315 def has_key(self, name):
316 """Return true if the message contains the header."""
Barry Warsawbb113862004-10-03 03:16:19 +0000317 missing = object()
Barry Warsawbeb59452001-09-26 05:41:51 +0000318 return self.get(name, missing) is not missing
Barry Warsawba925802001-09-23 03:17:28 +0000319
320 def keys(self):
321 """Return a list of all the message's header field names.
322
323 These will be sorted in the order they appeared in the original
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000324 message, or were added to the message, and may contain duplicates.
325 Any fields deleted and re-inserted are always appended to the header
326 list.
Barry Warsawba925802001-09-23 03:17:28 +0000327 """
328 return [k for k, v in self._headers]
329
330 def values(self):
331 """Return a list of all the message's header values.
332
333 These will be sorted in the order they appeared in the original
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000334 message, or were added to the message, and may contain duplicates.
335 Any fields deleted and re-inserted are always appended to the header
336 list.
Barry Warsawba925802001-09-23 03:17:28 +0000337 """
338 return [v for k, v in self._headers]
339
340 def items(self):
341 """Get all the message's header fields and values.
342
343 These will be sorted in the order they appeared in the original
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000344 message, or were added to the message, and may contain duplicates.
345 Any fields deleted and re-inserted are always appended to the header
346 list.
Barry Warsawba925802001-09-23 03:17:28 +0000347 """
348 return self._headers[:]
349
350 def get(self, name, failobj=None):
351 """Get a header value.
352
353 Like __getitem__() but return failobj instead of None when the field
354 is missing.
355 """
356 name = name.lower()
357 for k, v in self._headers:
358 if k.lower() == name:
359 return v
360 return failobj
361
362 #
363 # Additional useful stuff
364 #
365
366 def get_all(self, name, failobj=None):
367 """Return a list of all the values for the named field.
368
369 These will be sorted in the order they appeared in the original
370 message, and may contain duplicates. Any fields deleted and
Greg Ward6253c2d2001-11-24 15:49:53 +0000371 re-inserted are always appended to the header list.
Barry Warsaw9300a752001-10-09 15:48:29 +0000372
373 If no such fields exist, failobj is returned (defaults to None).
Barry Warsawba925802001-09-23 03:17:28 +0000374 """
375 values = []
376 name = name.lower()
377 for k, v in self._headers:
378 if k.lower() == name:
379 values.append(v)
Barry Warsaw9300a752001-10-09 15:48:29 +0000380 if not values:
381 return failobj
Barry Warsawba925802001-09-23 03:17:28 +0000382 return values
383
384 def add_header(self, _name, _value, **_params):
385 """Extended header setting.
386
387 name is the header field to add. keyword arguments can be used to set
388 additional parameters for the header field, with underscores converted
389 to dashes. Normally the parameter will be added as key="value" unless
390 value is None, in which case only the key will be added.
391
392 Example:
393
394 msg.add_header('content-disposition', 'attachment', filename='bud.gif')
Barry Warsawba925802001-09-23 03:17:28 +0000395 """
396 parts = []
397 for k, v in _params.items():
398 if v is None:
399 parts.append(k.replace('_', '-'))
400 else:
Barry Warsaw409a4c02002-04-10 21:01:31 +0000401 parts.append(_formatparam(k.replace('_', '-'), v))
Barry Warsawba925802001-09-23 03:17:28 +0000402 if _value is not None:
403 parts.insert(0, _value)
404 self._headers.append((_name, SEMISPACE.join(parts)))
405
Barry Warsaw229727f2002-09-06 03:38:12 +0000406 def replace_header(self, _name, _value):
407 """Replace a header.
408
409 Replace the first matching header found in the message, retaining
410 header order and case. If no matching header was found, a KeyError is
411 raised.
412 """
413 _name = _name.lower()
414 for i, (k, v) in zip(range(len(self._headers)), self._headers):
415 if k.lower() == _name:
416 self._headers[i] = (k, _value)
417 break
418 else:
Barry Warsawbb113862004-10-03 03:16:19 +0000419 raise KeyError(_name)
Barry Warsaw229727f2002-09-06 03:38:12 +0000420
Barry Warsawc1068642002-07-19 22:24:55 +0000421 #
Barry Warsawc1068642002-07-19 22:24:55 +0000422 # Use these three methods instead of the three above.
423 #
424
425 def get_content_type(self):
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000426 """Return the message's content type.
Barry Warsawc1068642002-07-19 22:24:55 +0000427
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000428 The returned string is coerced to lower case of the form
429 `maintype/subtype'. If there was no Content-Type header in the
430 message, the default type as given by get_default_type() will be
431 returned. Since according to RFC 2045, messages always have a default
432 type this will always return a value.
Barry Warsawc1068642002-07-19 22:24:55 +0000433
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000434 RFC 2045 defines a message's default type to be text/plain unless it
435 appears inside a multipart/digest container, in which case it would be
436 message/rfc822.
Barry Warsawc1068642002-07-19 22:24:55 +0000437 """
Barry Warsawbb113862004-10-03 03:16:19 +0000438 missing = object()
Barry Warsawc1068642002-07-19 22:24:55 +0000439 value = self.get('content-type', missing)
440 if value is missing:
441 # This should have no parameters
442 return self.get_default_type()
Antoine Pitroub90a8be2008-08-15 21:03:21 +0000443 ctype = _splitparam(value)[0].lower()
Barry Warsawf36d8042002-08-20 14:50:09 +0000444 # RFC 2045, section 5.2 says if its invalid, use text/plain
Brett Cannon1f571c62008-08-03 23:27:32 +0000445 if ctype.count('/') != 1:
Barry Warsawf36d8042002-08-20 14:50:09 +0000446 return 'text/plain'
447 return ctype
Barry Warsawc1068642002-07-19 22:24:55 +0000448
449 def get_content_maintype(self):
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000450 """Return the message's main content type.
Barry Warsawc1068642002-07-19 22:24:55 +0000451
452 This is the `maintype' part of the string returned by
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000453 get_content_type().
Barry Warsawc1068642002-07-19 22:24:55 +0000454 """
455 ctype = self.get_content_type()
Barry Warsawc1068642002-07-19 22:24:55 +0000456 return ctype.split('/')[0]
457
458 def get_content_subtype(self):
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000459 """Returns the message's sub-content type.
Barry Warsawc1068642002-07-19 22:24:55 +0000460
461 This is the `subtype' part of the string returned by
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000462 get_content_type().
Barry Warsawc1068642002-07-19 22:24:55 +0000463 """
464 ctype = self.get_content_type()
Barry Warsawc1068642002-07-19 22:24:55 +0000465 return ctype.split('/')[1]
Barry Warsawba925802001-09-23 03:17:28 +0000466
Barry Warsawa0c8b9d2002-07-09 02:46:12 +0000467 def get_default_type(self):
468 """Return the `default' content type.
469
470 Most messages have a default content type of text/plain, except for
471 messages that are subparts of multipart/digest containers. Such
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000472 subparts have a default content type of message/rfc822.
Barry Warsawa0c8b9d2002-07-09 02:46:12 +0000473 """
474 return self._default_type
475
476 def set_default_type(self, ctype):
477 """Set the `default' content type.
478
Barry Warsawc1068642002-07-19 22:24:55 +0000479 ctype should be either "text/plain" or "message/rfc822", although this
480 is not enforced. The default content type is not stored in the
Barry Warsawc4945492002-09-28 20:40:25 +0000481 Content-Type header.
Barry Warsawa0c8b9d2002-07-09 02:46:12 +0000482 """
Barry Warsawa0c8b9d2002-07-09 02:46:12 +0000483 self._default_type = ctype
484
Barry Warsawbeb59452001-09-26 05:41:51 +0000485 def _get_params_preserve(self, failobj, header):
486 # Like get_params() but preserves the quoting of values. BAW:
487 # should this be part of the public interface?
Barry Warsawbb113862004-10-03 03:16:19 +0000488 missing = object()
Barry Warsawbeb59452001-09-26 05:41:51 +0000489 value = self.get(header, missing)
490 if value is missing:
491 return failobj
492 params = []
Barry Warsawa74e8682003-09-03 04:08:13 +0000493 for p in _parseparam(';' + value):
Barry Warsawbeb59452001-09-26 05:41:51 +0000494 try:
495 name, val = p.split('=', 1)
Barry Warsaw7aeac912002-07-18 23:09:09 +0000496 name = name.strip()
497 val = val.strip()
Barry Warsawbeb59452001-09-26 05:41:51 +0000498 except ValueError:
499 # Must have been a bare attribute
Barry Warsaw7aeac912002-07-18 23:09:09 +0000500 name = p.strip()
Barry Warsawbeb59452001-09-26 05:41:51 +0000501 val = ''
502 params.append((name, val))
Barry Warsaw40ef0062006-03-18 15:41:53 +0000503 params = utils.decode_params(params)
Barry Warsawbeb59452001-09-26 05:41:51 +0000504 return params
505
Barry Warsawc4945492002-09-28 20:40:25 +0000506 def get_params(self, failobj=None, header='content-type', unquote=True):
507 """Return the message's Content-Type parameters, as a list.
Barry Warsawba925802001-09-23 03:17:28 +0000508
Barry Warsawbeb59452001-09-26 05:41:51 +0000509 The elements of the returned list are 2-tuples of key/value pairs, as
510 split on the `=' sign. The left hand side of the `=' is the key,
511 while the right hand side is the value. If there is no `=' sign in
Barry Warsaw15aefa92002-09-26 17:19:34 +0000512 the parameter the value is the empty string. The value is as
513 described in the get_param() method.
Barry Warsawbeb59452001-09-26 05:41:51 +0000514
Barry Warsawc4945492002-09-28 20:40:25 +0000515 Optional failobj is the object to return if there is no Content-Type
Barry Warsawba925802001-09-23 03:17:28 +0000516 header. Optional header is the header to search instead of
Barry Warsawc4945492002-09-28 20:40:25 +0000517 Content-Type. If unquote is True, the value is unquoted.
Barry Warsawba925802001-09-23 03:17:28 +0000518 """
Barry Warsawbb113862004-10-03 03:16:19 +0000519 missing = object()
Barry Warsawbeb59452001-09-26 05:41:51 +0000520 params = self._get_params_preserve(missing, header)
521 if params is missing:
Barry Warsawba925802001-09-23 03:17:28 +0000522 return failobj
Barry Warsaw409a4c02002-04-10 21:01:31 +0000523 if unquote:
Barry Warsaw908dc4b2002-06-29 05:56:15 +0000524 return [(k, _unquotevalue(v)) for k, v in params]
Barry Warsaw409a4c02002-04-10 21:01:31 +0000525 else:
526 return params
Barry Warsawba925802001-09-23 03:17:28 +0000527
Barry Warsawc4945492002-09-28 20:40:25 +0000528 def get_param(self, param, failobj=None, header='content-type',
529 unquote=True):
530 """Return the parameter value if found in the Content-Type header.
Barry Warsawba925802001-09-23 03:17:28 +0000531
Barry Warsawc4945492002-09-28 20:40:25 +0000532 Optional failobj is the object to return if there is no Content-Type
Barry Warsaw15aefa92002-09-26 17:19:34 +0000533 header, or the Content-Type header has no such parameter. Optional
Barry Warsawc4945492002-09-28 20:40:25 +0000534 header is the header to search instead of Content-Type.
Barry Warsawbeb59452001-09-26 05:41:51 +0000535
Barry Warsaw15aefa92002-09-26 17:19:34 +0000536 Parameter keys are always compared case insensitively. The return
537 value can either be a string, or a 3-tuple if the parameter was RFC
538 2231 encoded. When it's a 3-tuple, the elements of the value are of
Barry Warsaw62083692003-08-19 03:53:02 +0000539 the form (CHARSET, LANGUAGE, VALUE). Note that both CHARSET and
540 LANGUAGE can be None, in which case you should consider VALUE to be
541 encoded in the us-ascii charset. You can usually ignore LANGUAGE.
542
543 Your application should be prepared to deal with 3-tuple return
544 values, and can convert the parameter to a Unicode string like so:
Barry Warsaw15aefa92002-09-26 17:19:34 +0000545
546 param = msg.get_param('foo')
547 if isinstance(param, tuple):
Barry Warsaw62083692003-08-19 03:53:02 +0000548 param = unicode(param[2], param[0] or 'us-ascii')
Barry Warsaw15aefa92002-09-26 17:19:34 +0000549
550 In any case, the parameter value (either the returned string, or the
551 VALUE item in the 3-tuple) is always unquoted, unless unquote is set
Barry Warsawc4945492002-09-28 20:40:25 +0000552 to False.
Barry Warsawba925802001-09-23 03:17:28 +0000553 """
Barry Warsawbeb59452001-09-26 05:41:51 +0000554 if not self.has_key(header):
Barry Warsawba925802001-09-23 03:17:28 +0000555 return failobj
Barry Warsawbeb59452001-09-26 05:41:51 +0000556 for k, v in self._get_params_preserve(failobj, header):
557 if k.lower() == param.lower():
Barry Warsaw409a4c02002-04-10 21:01:31 +0000558 if unquote:
Barry Warsaw908dc4b2002-06-29 05:56:15 +0000559 return _unquotevalue(v)
Barry Warsaw409a4c02002-04-10 21:01:31 +0000560 else:
561 return v
Barry Warsawba925802001-09-23 03:17:28 +0000562 return failobj
563
Barry Warsawc4945492002-09-28 20:40:25 +0000564 def set_param(self, param, value, header='Content-Type', requote=True,
Barry Warsaw3c255352002-09-06 03:55:04 +0000565 charset=None, language=''):
Barry Warsawc4945492002-09-28 20:40:25 +0000566 """Set a parameter in the Content-Type header.
Barry Warsaw409a4c02002-04-10 21:01:31 +0000567
568 If the parameter already exists in the header, its value will be
569 replaced with the new value.
570
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000571 If header is Content-Type and has not yet been defined for this
Barry Warsaw409a4c02002-04-10 21:01:31 +0000572 message, it will be set to "text/plain" and the new parameter and
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000573 value will be appended as per RFC 2045.
Barry Warsaw409a4c02002-04-10 21:01:31 +0000574
Barry Warsawc4945492002-09-28 20:40:25 +0000575 An alternate header can specified in the header argument, and all
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000576 parameters will be quoted as necessary unless requote is False.
Barry Warsaw3c255352002-09-06 03:55:04 +0000577
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000578 If charset is specified, the parameter will be encoded according to RFC
579 2231. Optional language specifies the RFC 2231 language, defaulting
580 to the empty string. Both charset and language should be strings.
Barry Warsaw409a4c02002-04-10 21:01:31 +0000581 """
Barry Warsaw5d840532004-05-09 03:44:55 +0000582 if not isinstance(value, tuple) and charset:
Barry Warsaw3c255352002-09-06 03:55:04 +0000583 value = (charset, language, value)
584
Barry Warsaw409a4c02002-04-10 21:01:31 +0000585 if not self.has_key(header) and header.lower() == 'content-type':
586 ctype = 'text/plain'
587 else:
588 ctype = self.get(header)
589 if not self.get_param(param, header=header):
590 if not ctype:
591 ctype = _formatparam(param, value, requote)
592 else:
593 ctype = SEMISPACE.join(
594 [ctype, _formatparam(param, value, requote)])
595 else:
596 ctype = ''
597 for old_param, old_value in self.get_params(header=header,
598 unquote=requote):
599 append_param = ''
600 if old_param.lower() == param.lower():
601 append_param = _formatparam(param, value, requote)
602 else:
603 append_param = _formatparam(old_param, old_value, requote)
604 if not ctype:
605 ctype = append_param
606 else:
607 ctype = SEMISPACE.join([ctype, append_param])
Brett Cannon1f571c62008-08-03 23:27:32 +0000608 if ctype != self.get(header):
Barry Warsaw409a4c02002-04-10 21:01:31 +0000609 del self[header]
610 self[header] = ctype
611
Barry Warsawc4945492002-09-28 20:40:25 +0000612 def del_param(self, param, header='content-type', requote=True):
Barry Warsaw409a4c02002-04-10 21:01:31 +0000613 """Remove the given parameter completely from the Content-Type header.
614
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000615 The header will be re-written in place without the parameter or its
616 value. All values will be quoted as necessary unless requote is
617 False. Optional header specifies an alternative to the Content-Type
618 header.
Barry Warsaw409a4c02002-04-10 21:01:31 +0000619 """
620 if not self.has_key(header):
621 return
622 new_ctype = ''
Barry Warsaw06fa0422004-08-16 15:47:34 +0000623 for p, v in self.get_params(header=header, unquote=requote):
Brett Cannon1f571c62008-08-03 23:27:32 +0000624 if p.lower() != param.lower():
Barry Warsaw409a4c02002-04-10 21:01:31 +0000625 if not new_ctype:
626 new_ctype = _formatparam(p, v, requote)
627 else:
628 new_ctype = SEMISPACE.join([new_ctype,
629 _formatparam(p, v, requote)])
Brett Cannon1f571c62008-08-03 23:27:32 +0000630 if new_ctype != self.get(header):
Barry Warsaw409a4c02002-04-10 21:01:31 +0000631 del self[header]
632 self[header] = new_ctype
633
Barry Warsawc4945492002-09-28 20:40:25 +0000634 def set_type(self, type, header='Content-Type', requote=True):
635 """Set the main type and subtype for the Content-Type header.
Barry Warsaw409a4c02002-04-10 21:01:31 +0000636
637 type must be a string in the form "maintype/subtype", otherwise a
638 ValueError is raised.
639
Barry Warsawc4945492002-09-28 20:40:25 +0000640 This method replaces the Content-Type header, keeping all the
641 parameters in place. If requote is False, this leaves the existing
Barry Warsaw409a4c02002-04-10 21:01:31 +0000642 header's quoting as is. Otherwise, the parameters will be quoted (the
643 default).
644
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000645 An alternative header can be specified in the header argument. When
646 the Content-Type header is set, we'll always also add a MIME-Version
Barry Warsaw409a4c02002-04-10 21:01:31 +0000647 header.
648 """
649 # BAW: should we be strict?
650 if not type.count('/') == 1:
651 raise ValueError
Barry Warsawc4945492002-09-28 20:40:25 +0000652 # Set the Content-Type, you get a MIME-Version
Barry Warsaw409a4c02002-04-10 21:01:31 +0000653 if header.lower() == 'content-type':
654 del self['mime-version']
655 self['MIME-Version'] = '1.0'
656 if not self.has_key(header):
657 self[header] = type
658 return
Barry Warsaw06fa0422004-08-16 15:47:34 +0000659 params = self.get_params(header=header, unquote=requote)
Barry Warsaw409a4c02002-04-10 21:01:31 +0000660 del self[header]
661 self[header] = type
662 # Skip the first param; it's the old type.
663 for p, v in params[1:]:
664 self.set_param(p, v, header, requote)
665
Barry Warsawba925802001-09-23 03:17:28 +0000666 def get_filename(self, failobj=None):
667 """Return the filename associated with the payload if present.
668
Barry Warsawc4945492002-09-28 20:40:25 +0000669 The filename is extracted from the Content-Disposition header's
Barry Warsawa0f28ef2006-01-17 04:49:07 +0000670 `filename' parameter, and it is unquoted. If that header is missing
671 the `filename' parameter, this method falls back to looking for the
672 `name' parameter.
Barry Warsawba925802001-09-23 03:17:28 +0000673 """
Barry Warsawbb113862004-10-03 03:16:19 +0000674 missing = object()
Barry Warsawba925802001-09-23 03:17:28 +0000675 filename = self.get_param('filename', missing, 'content-disposition')
676 if filename is missing:
Barry Warsawa0f28ef2006-01-17 04:49:07 +0000677 filename = self.get_param('name', missing, 'content-disposition')
678 if filename is missing:
Barry Warsawba925802001-09-23 03:17:28 +0000679 return failobj
Barry Warsaw40ef0062006-03-18 15:41:53 +0000680 return utils.collapse_rfc2231_value(filename).strip()
Barry Warsawba925802001-09-23 03:17:28 +0000681
682 def get_boundary(self, failobj=None):
683 """Return the boundary associated with the payload if present.
684
Barry Warsawc4945492002-09-28 20:40:25 +0000685 The boundary is extracted from the Content-Type header's `boundary'
Barry Warsawba925802001-09-23 03:17:28 +0000686 parameter, and it is unquoted.
687 """
Barry Warsawbb113862004-10-03 03:16:19 +0000688 missing = object()
Barry Warsawba925802001-09-23 03:17:28 +0000689 boundary = self.get_param('boundary', missing)
690 if boundary is missing:
691 return failobj
Barry Warsaw93d9d5f2004-11-06 00:04:52 +0000692 # RFC 2046 says that boundaries may begin but not end in w/s
Barry Warsaw40ef0062006-03-18 15:41:53 +0000693 return utils.collapse_rfc2231_value(boundary).rstrip()
Barry Warsawba925802001-09-23 03:17:28 +0000694
695 def set_boundary(self, boundary):
Barry Warsawc4945492002-09-28 20:40:25 +0000696 """Set the boundary parameter in Content-Type to 'boundary'.
Barry Warsawba925802001-09-23 03:17:28 +0000697
Barry Warsawc4945492002-09-28 20:40:25 +0000698 This is subtly different than deleting the Content-Type header and
Barry Warsawba925802001-09-23 03:17:28 +0000699 adding a new one with a new boundary parameter via add_header(). The
700 main difference is that using the set_boundary() method preserves the
Barry Warsawc4945492002-09-28 20:40:25 +0000701 order of the Content-Type header in the original message.
Barry Warsawba925802001-09-23 03:17:28 +0000702
Barry Warsawc4945492002-09-28 20:40:25 +0000703 HeaderParseError is raised if the message has no Content-Type header.
Barry Warsawba925802001-09-23 03:17:28 +0000704 """
Barry Warsawbb113862004-10-03 03:16:19 +0000705 missing = object()
Barry Warsawbeb59452001-09-26 05:41:51 +0000706 params = self._get_params_preserve(missing, 'content-type')
707 if params is missing:
Barry Warsawc4945492002-09-28 20:40:25 +0000708 # There was no Content-Type header, and we don't know what type
Barry Warsawba925802001-09-23 03:17:28 +0000709 # to set it to, so raise an exception.
Barry Warsaw40ef0062006-03-18 15:41:53 +0000710 raise errors.HeaderParseError('No Content-Type header found')
Barry Warsawba925802001-09-23 03:17:28 +0000711 newparams = []
Barry Warsawc4945492002-09-28 20:40:25 +0000712 foundp = False
Barry Warsawbeb59452001-09-26 05:41:51 +0000713 for pk, pv in params:
714 if pk.lower() == 'boundary':
715 newparams.append(('boundary', '"%s"' % boundary))
Barry Warsawc4945492002-09-28 20:40:25 +0000716 foundp = True
Barry Warsawba925802001-09-23 03:17:28 +0000717 else:
Barry Warsawbeb59452001-09-26 05:41:51 +0000718 newparams.append((pk, pv))
Barry Warsawba925802001-09-23 03:17:28 +0000719 if not foundp:
Barry Warsawc4945492002-09-28 20:40:25 +0000720 # The original Content-Type header had no boundary attribute.
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000721 # Tack one on the end. BAW: should we raise an exception
Barry Warsawba925802001-09-23 03:17:28 +0000722 # instead???
Barry Warsawbeb59452001-09-26 05:41:51 +0000723 newparams.append(('boundary', '"%s"' % boundary))
Barry Warsawc4945492002-09-28 20:40:25 +0000724 # Replace the existing Content-Type header with the new value
Barry Warsawba925802001-09-23 03:17:28 +0000725 newheaders = []
726 for h, v in self._headers:
727 if h.lower() == 'content-type':
Barry Warsawbeb59452001-09-26 05:41:51 +0000728 parts = []
729 for k, v in newparams:
730 if v == '':
731 parts.append(k)
732 else:
733 parts.append('%s=%s' % (k, v))
734 newheaders.append((h, SEMISPACE.join(parts)))
735
Barry Warsawba925802001-09-23 03:17:28 +0000736 else:
737 newheaders.append((h, v))
738 self._headers = newheaders
739
Barry Warsaw15aefa92002-09-26 17:19:34 +0000740 def get_content_charset(self, failobj=None):
741 """Return the charset parameter of the Content-Type header.
742
Barry Warsawee07cb12002-10-10 15:13:26 +0000743 The returned string is always coerced to lower case. If there is no
744 Content-Type header, or if that header has no charset parameter,
745 failobj is returned.
Barry Warsaw15aefa92002-09-26 17:19:34 +0000746 """
Barry Warsawbb113862004-10-03 03:16:19 +0000747 missing = object()
Barry Warsaw15aefa92002-09-26 17:19:34 +0000748 charset = self.get_param('charset', missing)
749 if charset is missing:
750 return failobj
Barry Warsaw5d840532004-05-09 03:44:55 +0000751 if isinstance(charset, tuple):
Barry Warsaw15aefa92002-09-26 17:19:34 +0000752 # RFC 2231 encoded, so decode it, and it better end up as ascii.
Barry Warsaw62083692003-08-19 03:53:02 +0000753 pcharset = charset[0] or 'us-ascii'
Barry Warsawd92ae782006-07-26 05:54:46 +0000754 try:
755 # LookupError will be raised if the charset isn't known to
756 # Python. UnicodeError will be raised if the encoded text
757 # contains a character not in the charset.
758 charset = unicode(charset[2], pcharset).encode('us-ascii')
759 except (LookupError, UnicodeError):
760 charset = charset[2]
761 # charset character must be in us-ascii range
762 try:
Martin v. Löwisbdd0f392007-03-13 10:24:00 +0000763 if isinstance(charset, str):
764 charset = unicode(charset, 'us-ascii')
765 charset = charset.encode('us-ascii')
Barry Warsawd92ae782006-07-26 05:54:46 +0000766 except UnicodeError:
767 return failobj
Barry Warsawee07cb12002-10-10 15:13:26 +0000768 # RFC 2046, $4.1.2 says charsets are not case sensitive
769 return charset.lower()
Barry Warsaw15aefa92002-09-26 17:19:34 +0000770
Barry Warsawba925802001-09-23 03:17:28 +0000771 def get_charsets(self, failobj=None):
772 """Return a list containing the charset(s) used in this message.
Tim Peters527e64f2001-10-04 05:36:56 +0000773
Barry Warsawc4945492002-09-28 20:40:25 +0000774 The returned list of items describes the Content-Type headers'
Barry Warsawba925802001-09-23 03:17:28 +0000775 charset parameter for this message and all the subparts in its
776 payload.
777
778 Each item will either be a string (the value of the charset parameter
Barry Warsawc4945492002-09-28 20:40:25 +0000779 in the Content-Type header of that part) or the value of the
Barry Warsawba925802001-09-23 03:17:28 +0000780 'failobj' parameter (defaults to None), if the part does not have a
781 main MIME type of "text", or the charset is not defined.
782
783 The list will contain one string for each part of the message, plus
784 one for the container message (i.e. self), so that a non-multipart
785 message will still return a list of length 1.
786 """
Barry Warsaw15aefa92002-09-26 17:19:34 +0000787 return [part.get_content_charset(failobj) for part in self.walk()]
Barry Warsaw5d840532004-05-09 03:44:55 +0000788
789 # I.e. def walk(self): ...
790 from email.Iterators import walk