blob: 66f8640eb1f7459434f59de7051da0deb9a94b0f [file] [log] [blame]
Barry Warsaw409a4c02002-04-10 21:01:31 +00001# Copyright (C) 2001,2002 Python Software Foundation
Barry Warsawba925802001-09-23 03:17:28 +00002# Author: barry@zope.com (Barry Warsaw)
3
4"""Basic message object for the email package object model.
5"""
6
Barry Warsawba925802001-09-23 03:17:28 +00007import re
Barry Warsaw08898492003-03-11 04:33:30 +00008import uu
Barry Warsaw21191d32003-03-10 16:13:14 +00009import binascii
Barry Warsaw409a4c02002-04-10 21:01:31 +000010import warnings
Barry Warsawba925802001-09-23 03:17:28 +000011from cStringIO import StringIO
Barry Warsaw908dc4b2002-06-29 05:56:15 +000012from types import ListType, TupleType, StringType
Barry Warsawba925802001-09-23 03:17:28 +000013
Barry Warsawba925802001-09-23 03:17:28 +000014# Intrapackage imports
Barry Warsaw8ba76e82002-06-02 19:05:51 +000015from email import Utils
Barry Warsaw21191d32003-03-10 16:13:14 +000016from email import Errors
Barry Warsaw8ba76e82002-06-02 19:05:51 +000017from email import Charset
Barry Warsawba925802001-09-23 03:17:28 +000018
Barry Warsawbeb59452001-09-26 05:41:51 +000019SEMISPACE = '; '
Barry Warsaw409a4c02002-04-10 21:01:31 +000020
Barry Warsawc4945492002-09-28 20:40:25 +000021try:
22 True, False
23except NameError:
24 True = 1
25 False = 0
26
Barry Warsaw409a4c02002-04-10 21:01:31 +000027# Regular expression used to split header parameters. BAW: this may be too
28# simple. It isn't strictly RFC 2045 (section 5.1) compliant, but it catches
29# most headers found in the wild. We may eventually need a full fledged
30# parser eventually.
Barry Warsaw2539cf52001-10-25 22:43:46 +000031paramre = re.compile(r'\s*;\s*')
Barry Warsaw409a4c02002-04-10 21:01:31 +000032# Regular expression that matches `special' characters in parameters, the
33# existance of which force quoting of the parameter value.
34tspecials = re.compile(r'[ \(\)<>@,;:\\"/\[\]\?=]')
35
36
37
Barry Warsaw908dc4b2002-06-29 05:56:15 +000038# Helper functions
Barry Warsawc4945492002-09-28 20:40:25 +000039def _formatparam(param, value=None, quote=True):
Barry Warsaw409a4c02002-04-10 21:01:31 +000040 """Convenience function to format and return a key=value pair.
41
Barry Warsaw908dc4b2002-06-29 05:56:15 +000042 This will quote the value if needed or if quote is true.
Barry Warsaw409a4c02002-04-10 21:01:31 +000043 """
44 if value is not None and len(value) > 0:
Barry Warsaw908dc4b2002-06-29 05:56:15 +000045 # TupleType is used for RFC 2231 encoded parameter values where items
46 # are (charset, language, value). charset is a string, not a Charset
47 # instance.
48 if isinstance(value, TupleType):
Barry Warsaw3c255352002-09-06 03:55:04 +000049 # Encode as per RFC 2231
50 param += '*'
51 value = Utils.encode_rfc2231(value[2], value[0], value[1])
Barry Warsaw409a4c02002-04-10 21:01:31 +000052 # BAW: Please check this. I think that if quote is set it should
53 # force quoting even if not necessary.
54 if quote or tspecials.search(value):
55 return '%s="%s"' % (param, Utils.quote(value))
56 else:
57 return '%s=%s' % (param, value)
58 else:
59 return param
Barry Warsawbeb59452001-09-26 05:41:51 +000060
Barry Warsawba925802001-09-23 03:17:28 +000061
Barry Warsaw908dc4b2002-06-29 05:56:15 +000062def _unquotevalue(value):
63 if isinstance(value, TupleType):
Barry Warsaw15aefa92002-09-26 17:19:34 +000064 return value[0], value[1], Utils.unquote(value[2])
Barry Warsaw908dc4b2002-06-29 05:56:15 +000065 else:
Tim Peters280488b2002-08-23 18:19:30 +000066 return Utils.unquote(value)
Barry Warsaw908dc4b2002-06-29 05:56:15 +000067
68
Barry Warsaw48b0d362002-08-27 22:34:44 +000069
Barry Warsawba925802001-09-23 03:17:28 +000070class Message:
Barry Warsaw42d1d3e2002-09-30 18:17:35 +000071 """Basic message object.
Barry Warsawba925802001-09-23 03:17:28 +000072
73 A message object is defined as something that has a bunch of RFC 2822
Barry Warsaw42d1d3e2002-09-30 18:17:35 +000074 headers and a payload. It may optionally have an envelope header
75 (a.k.a. Unix-From or From_ header). If the message is a container (i.e. a
76 multipart or a message/rfc822), then the payload is a list of Message
77 objects, otherwise it is a string.
Barry Warsawba925802001-09-23 03:17:28 +000078
Barry Warsaw42d1d3e2002-09-30 18:17:35 +000079 Message objects implement part of the `mapping' interface, which assumes
Barry Warsawba925802001-09-23 03:17:28 +000080 there is exactly one occurrance of the header per message. Some headers
Barry Warsawc4945492002-09-28 20:40:25 +000081 do in fact appear multiple times (e.g. Received) and for those headers,
Barry Warsawba925802001-09-23 03:17:28 +000082 you must use the explicit API to set or get all the headers. Not all of
83 the mapping methods are implemented.
Barry Warsawba925802001-09-23 03:17:28 +000084 """
85 def __init__(self):
86 self._headers = []
87 self._unixfrom = None
88 self._payload = None
Barry Warsaw409a4c02002-04-10 21:01:31 +000089 self._charset = None
Barry Warsawba925802001-09-23 03:17:28 +000090 # Defaults for multipart messages
91 self.preamble = self.epilogue = None
Barry Warsawa0c8b9d2002-07-09 02:46:12 +000092 # Default content type
93 self._default_type = 'text/plain'
Barry Warsawba925802001-09-23 03:17:28 +000094
95 def __str__(self):
96 """Return the entire formatted message as a string.
Barry Warsaw42d1d3e2002-09-30 18:17:35 +000097 This includes the headers, body, and envelope header.
Barry Warsawba925802001-09-23 03:17:28 +000098 """
Barry Warsawc4945492002-09-28 20:40:25 +000099 return self.as_string(unixfrom=True)
Barry Warsawba925802001-09-23 03:17:28 +0000100
Barry Warsawc4945492002-09-28 20:40:25 +0000101 def as_string(self, unixfrom=False):
Barry Warsawba925802001-09-23 03:17:28 +0000102 """Return the entire formatted message as a string.
Barry Warsawc4945492002-09-28 20:40:25 +0000103 Optional `unixfrom' when True, means include the Unix From_ envelope
Barry Warsawba925802001-09-23 03:17:28 +0000104 header.
105 """
Barry Warsaw8ba76e82002-06-02 19:05:51 +0000106 from email.Generator import Generator
Barry Warsawba925802001-09-23 03:17:28 +0000107 fp = StringIO()
108 g = Generator(fp)
Barry Warsaw8ba76e82002-06-02 19:05:51 +0000109 g.flatten(self, unixfrom=unixfrom)
Barry Warsawba925802001-09-23 03:17:28 +0000110 return fp.getvalue()
111
112 def is_multipart(self):
Barry Warsawc4945492002-09-28 20:40:25 +0000113 """Return True if the message consists of multiple parts."""
Barry Warsaw4ece7782002-09-28 20:41:39 +0000114 if isinstance(self._payload, ListType):
Barry Warsawc4945492002-09-28 20:40:25 +0000115 return True
116 return False
Barry Warsawba925802001-09-23 03:17:28 +0000117
118 #
119 # Unix From_ line
120 #
121 def set_unixfrom(self, unixfrom):
122 self._unixfrom = unixfrom
123
124 def get_unixfrom(self):
125 return self._unixfrom
126
127 #
128 # Payload manipulation.
129 #
130 def add_payload(self, payload):
131 """Add the given payload to the current payload.
132
133 If the current payload is empty, then the current payload will be made
134 a scalar, set to the given value.
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000135
136 Note: This method is deprecated. Use .attach() instead.
Barry Warsawba925802001-09-23 03:17:28 +0000137 """
Barry Warsaw409a4c02002-04-10 21:01:31 +0000138 warnings.warn('add_payload() is deprecated, use attach() instead.',
139 DeprecationWarning, 2)
Barry Warsawba925802001-09-23 03:17:28 +0000140 if self._payload is None:
141 self._payload = payload
Barry Warsawc4945492002-09-28 20:40:25 +0000142 elif isinstance(self._payload, ListType):
Barry Warsawba925802001-09-23 03:17:28 +0000143 self._payload.append(payload)
144 elif self.get_main_type() not in (None, 'multipart'):
145 raise Errors.MultipartConversionError(
Barry Warsawc4945492002-09-28 20:40:25 +0000146 'Message main content type must be "multipart" or missing')
Barry Warsawba925802001-09-23 03:17:28 +0000147 else:
148 self._payload = [self._payload, payload]
149
Barry Warsaw409a4c02002-04-10 21:01:31 +0000150 def attach(self, payload):
151 """Add the given payload to the current payload.
152
153 The current payload will always be a list of objects after this method
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000154 is called. If you want to set the payload to a scalar object, use
Barry Warsaw409a4c02002-04-10 21:01:31 +0000155 set_payload() instead.
156 """
157 if self._payload is None:
158 self._payload = [payload]
159 else:
160 self._payload.append(payload)
Barry Warsawba925802001-09-23 03:17:28 +0000161
Barry Warsawc4945492002-09-28 20:40:25 +0000162 def get_payload(self, i=None, decode=False):
Barry Warsawfbcde752002-09-11 14:11:35 +0000163 """Return a reference to the payload.
Barry Warsawba925802001-09-23 03:17:28 +0000164
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000165 The payload will either be a list object or a string. If you mutate
166 the list object, you modify the message's payload in place. Optional
167 i returns that index into the payload.
Barry Warsawba925802001-09-23 03:17:28 +0000168
Barry Warsaw08898492003-03-11 04:33:30 +0000169 Optional decode is a flag indicating whether the payload should be
170 decoded or not, according to the Content-Transfer-Encoding header
171 (default is False).
172
173 When True and the message is not a multipart, the payload will be
174 decoded if this header's value is `quoted-printable' or `base64'. If
175 some other encoding is used, or the header is missing, or if the
176 payload has bogus data (i.e. bogus base64 or uuencoded data), the
177 payload is returned as-is.
Barry Warsaw21191d32003-03-10 16:13:14 +0000178
179 If the message is a multipart and the decode flag is True, then None
180 is returned.
Barry Warsawba925802001-09-23 03:17:28 +0000181 """
182 if i is None:
183 payload = self._payload
Barry Warsawc4945492002-09-28 20:40:25 +0000184 elif not isinstance(self._payload, ListType):
Barry Warsawba925802001-09-23 03:17:28 +0000185 raise TypeError, i
186 else:
187 payload = self._payload[i]
188 if decode:
189 if self.is_multipart():
190 return None
Barry Warsaw08898492003-03-11 04:33:30 +0000191 cte = self.get('content-transfer-encoding', '').lower()
192 if cte == 'quoted-printable':
Barry Warsawba925802001-09-23 03:17:28 +0000193 return Utils._qdecode(payload)
Barry Warsaw08898492003-03-11 04:33:30 +0000194 elif cte == 'base64':
Barry Warsaw21191d32003-03-10 16:13:14 +0000195 try:
196 return Utils._bdecode(payload)
197 except binascii.Error:
198 # Incorrect padding
199 return payload
Barry Warsaw08898492003-03-11 04:33:30 +0000200 elif cte in ('x-uuencode', 'uuencode', 'uue', 'x-uue'):
201 sfp = StringIO()
202 try:
203 uu.decode(StringIO(payload+'\n'), sfp)
204 payload = sfp.getvalue()
205 except uu.Error:
206 # Some decoding problem
207 return payload
Barry Warsawba925802001-09-23 03:17:28 +0000208 # Everything else, including encodings with 8bit or 7bit are returned
209 # unchanged.
210 return payload
211
Barry Warsaw409a4c02002-04-10 21:01:31 +0000212 def set_payload(self, payload, charset=None):
213 """Set the payload to the given value.
Barry Warsawba925802001-09-23 03:17:28 +0000214
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000215 Optional charset sets the message's default character set. See
216 set_charset() for details.
217 """
Barry Warsaw409a4c02002-04-10 21:01:31 +0000218 self._payload = payload
219 if charset is not None:
220 self.set_charset(charset)
221
222 def set_charset(self, charset):
223 """Set the charset of the payload to a given character set.
224
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000225 charset can be a Charset instance, a string naming a character set, or
226 None. If it is a string it will be converted to a Charset instance.
227 If charset is None, the charset parameter will be removed from the
228 Content-Type field. Anything else will generate a TypeError.
Barry Warsaw409a4c02002-04-10 21:01:31 +0000229
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000230 The message will be assumed to be of type text/* encoded with
Barry Warsaw409a4c02002-04-10 21:01:31 +0000231 charset.input_charset. It will be converted to charset.output_charset
232 and encoded properly, if needed, when generating the plain text
233 representation of the message. MIME headers (MIME-Version,
234 Content-Type, Content-Transfer-Encoding) will be added as needed.
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000235
Barry Warsaw409a4c02002-04-10 21:01:31 +0000236 """
237 if charset is None:
238 self.del_param('charset')
239 self._charset = None
240 return
241 if isinstance(charset, StringType):
242 charset = Charset.Charset(charset)
243 if not isinstance(charset, Charset.Charset):
244 raise TypeError, charset
245 # BAW: should we accept strings that can serve as arguments to the
246 # Charset constructor?
247 self._charset = charset
248 if not self.has_key('MIME-Version'):
249 self.add_header('MIME-Version', '1.0')
250 if not self.has_key('Content-Type'):
251 self.add_header('Content-Type', 'text/plain',
252 charset=charset.get_output_charset())
253 else:
254 self.set_param('charset', charset.get_output_charset())
255 if not self.has_key('Content-Transfer-Encoding'):
256 cte = charset.get_body_encoding()
257 if callable(cte):
258 cte(self)
259 else:
260 self.add_header('Content-Transfer-Encoding', cte)
261
262 def get_charset(self):
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000263 """Return the Charset instance associated with the message's payload.
264 """
Barry Warsaw409a4c02002-04-10 21:01:31 +0000265 return self._charset
Tim Peters8ac14952002-05-23 15:15:30 +0000266
Barry Warsawba925802001-09-23 03:17:28 +0000267 #
268 # MAPPING INTERFACE (partial)
269 #
270 def __len__(self):
Barry Warsawbeb59452001-09-26 05:41:51 +0000271 """Return the total number of headers, including duplicates."""
Barry Warsawba925802001-09-23 03:17:28 +0000272 return len(self._headers)
273
274 def __getitem__(self, name):
275 """Get a header value.
276
277 Return None if the header is missing instead of raising an exception.
278
279 Note that if the header appeared multiple times, exactly which
280 occurrance gets returned is undefined. Use getall() to get all
281 the values matching a header field name.
282 """
283 return self.get(name)
284
285 def __setitem__(self, name, val):
286 """Set the value of a header.
287
288 Note: this does not overwrite an existing header with the same field
289 name. Use __delitem__() first to delete any existing headers.
290 """
291 self._headers.append((name, val))
292
293 def __delitem__(self, name):
294 """Delete all occurrences of a header, if present.
295
296 Does not raise an exception if the header is missing.
297 """
298 name = name.lower()
299 newheaders = []
300 for k, v in self._headers:
301 if k.lower() <> name:
302 newheaders.append((k, v))
303 self._headers = newheaders
304
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000305 def __contains__(self, name):
306 return name.lower() in [k.lower() for k, v in self._headers]
Barry Warsawba925802001-09-23 03:17:28 +0000307
308 def has_key(self, name):
309 """Return true if the message contains the header."""
Barry Warsawbeb59452001-09-26 05:41:51 +0000310 missing = []
311 return self.get(name, missing) is not missing
Barry Warsawba925802001-09-23 03:17:28 +0000312
313 def keys(self):
314 """Return a list of all the message's header field names.
315
316 These will be sorted in the order they appeared in the original
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000317 message, or were added to the message, and may contain duplicates.
318 Any fields deleted and re-inserted are always appended to the header
319 list.
Barry Warsawba925802001-09-23 03:17:28 +0000320 """
321 return [k for k, v in self._headers]
322
323 def values(self):
324 """Return a list of all the message's header values.
325
326 These will be sorted in the order they appeared in the original
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000327 message, or were added to the message, and may contain duplicates.
328 Any fields deleted and re-inserted are always appended to the header
329 list.
Barry Warsawba925802001-09-23 03:17:28 +0000330 """
331 return [v for k, v in self._headers]
332
333 def items(self):
334 """Get all the message's header fields and values.
335
336 These will be sorted in the order they appeared in the original
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000337 message, or were added to the message, and may contain duplicates.
338 Any fields deleted and re-inserted are always appended to the header
339 list.
Barry Warsawba925802001-09-23 03:17:28 +0000340 """
341 return self._headers[:]
342
343 def get(self, name, failobj=None):
344 """Get a header value.
345
346 Like __getitem__() but return failobj instead of None when the field
347 is missing.
348 """
349 name = name.lower()
350 for k, v in self._headers:
351 if k.lower() == name:
352 return v
353 return failobj
354
355 #
356 # Additional useful stuff
357 #
358
359 def get_all(self, name, failobj=None):
360 """Return a list of all the values for the named field.
361
362 These will be sorted in the order they appeared in the original
363 message, and may contain duplicates. Any fields deleted and
Greg Ward6253c2d2001-11-24 15:49:53 +0000364 re-inserted are always appended to the header list.
Barry Warsaw9300a752001-10-09 15:48:29 +0000365
366 If no such fields exist, failobj is returned (defaults to None).
Barry Warsawba925802001-09-23 03:17:28 +0000367 """
368 values = []
369 name = name.lower()
370 for k, v in self._headers:
371 if k.lower() == name:
372 values.append(v)
Barry Warsaw9300a752001-10-09 15:48:29 +0000373 if not values:
374 return failobj
Barry Warsawba925802001-09-23 03:17:28 +0000375 return values
376
377 def add_header(self, _name, _value, **_params):
378 """Extended header setting.
379
380 name is the header field to add. keyword arguments can be used to set
381 additional parameters for the header field, with underscores converted
382 to dashes. Normally the parameter will be added as key="value" unless
383 value is None, in which case only the key will be added.
384
385 Example:
386
387 msg.add_header('content-disposition', 'attachment', filename='bud.gif')
Barry Warsawba925802001-09-23 03:17:28 +0000388 """
389 parts = []
390 for k, v in _params.items():
391 if v is None:
392 parts.append(k.replace('_', '-'))
393 else:
Barry Warsaw409a4c02002-04-10 21:01:31 +0000394 parts.append(_formatparam(k.replace('_', '-'), v))
Barry Warsawba925802001-09-23 03:17:28 +0000395 if _value is not None:
396 parts.insert(0, _value)
397 self._headers.append((_name, SEMISPACE.join(parts)))
398
Barry Warsaw229727f2002-09-06 03:38:12 +0000399 def replace_header(self, _name, _value):
400 """Replace a header.
401
402 Replace the first matching header found in the message, retaining
403 header order and case. If no matching header was found, a KeyError is
404 raised.
405 """
406 _name = _name.lower()
407 for i, (k, v) in zip(range(len(self._headers)), self._headers):
408 if k.lower() == _name:
409 self._headers[i] = (k, _value)
410 break
411 else:
412 raise KeyError, _name
413
Barry Warsawc1068642002-07-19 22:24:55 +0000414 #
415 # These methods are silently deprecated in favor of get_content_type() and
416 # friends (see below). They will be noisily deprecated in email 3.0.
417 #
418
Barry Warsawba925802001-09-23 03:17:28 +0000419 def get_type(self, failobj=None):
420 """Returns the message's content type.
421
422 The returned string is coerced to lowercase and returned as a single
Barry Warsawc4945492002-09-28 20:40:25 +0000423 string of the form `maintype/subtype'. If there was no Content-Type
Barry Warsawba925802001-09-23 03:17:28 +0000424 header in the message, failobj is returned (defaults to None).
425 """
426 missing = []
427 value = self.get('content-type', missing)
428 if value is missing:
429 return failobj
Barry Warsaw7aeac912002-07-18 23:09:09 +0000430 return paramre.split(value)[0].lower().strip()
Barry Warsawba925802001-09-23 03:17:28 +0000431
432 def get_main_type(self, failobj=None):
433 """Return the message's main content type if present."""
434 missing = []
435 ctype = self.get_type(missing)
436 if ctype is missing:
437 return failobj
Barry Warsawc1068642002-07-19 22:24:55 +0000438 if ctype.count('/') <> 1:
439 return failobj
440 return ctype.split('/')[0]
Barry Warsawba925802001-09-23 03:17:28 +0000441
442 def get_subtype(self, failobj=None):
443 """Return the message's content subtype if present."""
444 missing = []
445 ctype = self.get_type(missing)
446 if ctype is missing:
447 return failobj
Barry Warsawc1068642002-07-19 22:24:55 +0000448 if ctype.count('/') <> 1:
449 return failobj
450 return ctype.split('/')[1]
451
452 #
453 # Use these three methods instead of the three above.
454 #
455
456 def get_content_type(self):
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000457 """Return the message's content type.
Barry Warsawc1068642002-07-19 22:24:55 +0000458
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000459 The returned string is coerced to lower case of the form
460 `maintype/subtype'. If there was no Content-Type header in the
461 message, the default type as given by get_default_type() will be
462 returned. Since according to RFC 2045, messages always have a default
463 type this will always return a value.
Barry Warsawc1068642002-07-19 22:24:55 +0000464
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000465 RFC 2045 defines a message's default type to be text/plain unless it
466 appears inside a multipart/digest container, in which case it would be
467 message/rfc822.
Barry Warsawc1068642002-07-19 22:24:55 +0000468 """
469 missing = []
470 value = self.get('content-type', missing)
471 if value is missing:
472 # This should have no parameters
473 return self.get_default_type()
Barry Warsawf36d8042002-08-20 14:50:09 +0000474 ctype = paramre.split(value)[0].lower().strip()
475 # RFC 2045, section 5.2 says if its invalid, use text/plain
476 if ctype.count('/') <> 1:
477 return 'text/plain'
478 return ctype
Barry Warsawc1068642002-07-19 22:24:55 +0000479
480 def get_content_maintype(self):
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000481 """Return the message's main content type.
Barry Warsawc1068642002-07-19 22:24:55 +0000482
483 This is the `maintype' part of the string returned by
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000484 get_content_type().
Barry Warsawc1068642002-07-19 22:24:55 +0000485 """
486 ctype = self.get_content_type()
Barry Warsawc1068642002-07-19 22:24:55 +0000487 return ctype.split('/')[0]
488
489 def get_content_subtype(self):
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000490 """Returns the message's sub-content type.
Barry Warsawc1068642002-07-19 22:24:55 +0000491
492 This is the `subtype' part of the string returned by
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000493 get_content_type().
Barry Warsawc1068642002-07-19 22:24:55 +0000494 """
495 ctype = self.get_content_type()
Barry Warsawc1068642002-07-19 22:24:55 +0000496 return ctype.split('/')[1]
Barry Warsawba925802001-09-23 03:17:28 +0000497
Barry Warsawa0c8b9d2002-07-09 02:46:12 +0000498 def get_default_type(self):
499 """Return the `default' content type.
500
501 Most messages have a default content type of text/plain, except for
502 messages that are subparts of multipart/digest containers. Such
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000503 subparts have a default content type of message/rfc822.
Barry Warsawa0c8b9d2002-07-09 02:46:12 +0000504 """
505 return self._default_type
506
507 def set_default_type(self, ctype):
508 """Set the `default' content type.
509
Barry Warsawc1068642002-07-19 22:24:55 +0000510 ctype should be either "text/plain" or "message/rfc822", although this
511 is not enforced. The default content type is not stored in the
Barry Warsawc4945492002-09-28 20:40:25 +0000512 Content-Type header.
Barry Warsawa0c8b9d2002-07-09 02:46:12 +0000513 """
Barry Warsawa0c8b9d2002-07-09 02:46:12 +0000514 self._default_type = ctype
515
Barry Warsawbeb59452001-09-26 05:41:51 +0000516 def _get_params_preserve(self, failobj, header):
517 # Like get_params() but preserves the quoting of values. BAW:
518 # should this be part of the public interface?
519 missing = []
520 value = self.get(header, missing)
521 if value is missing:
522 return failobj
523 params = []
524 for p in paramre.split(value):
525 try:
526 name, val = p.split('=', 1)
Barry Warsaw7aeac912002-07-18 23:09:09 +0000527 name = name.strip()
528 val = val.strip()
Barry Warsawbeb59452001-09-26 05:41:51 +0000529 except ValueError:
530 # Must have been a bare attribute
Barry Warsaw7aeac912002-07-18 23:09:09 +0000531 name = p.strip()
Barry Warsawbeb59452001-09-26 05:41:51 +0000532 val = ''
533 params.append((name, val))
Barry Warsaw908dc4b2002-06-29 05:56:15 +0000534 params = Utils.decode_params(params)
Barry Warsawbeb59452001-09-26 05:41:51 +0000535 return params
536
Barry Warsawc4945492002-09-28 20:40:25 +0000537 def get_params(self, failobj=None, header='content-type', unquote=True):
538 """Return the message's Content-Type parameters, as a list.
Barry Warsawba925802001-09-23 03:17:28 +0000539
Barry Warsawbeb59452001-09-26 05:41:51 +0000540 The elements of the returned list are 2-tuples of key/value pairs, as
541 split on the `=' sign. The left hand side of the `=' is the key,
542 while the right hand side is the value. If there is no `=' sign in
Barry Warsaw15aefa92002-09-26 17:19:34 +0000543 the parameter the value is the empty string. The value is as
544 described in the get_param() method.
Barry Warsawbeb59452001-09-26 05:41:51 +0000545
Barry Warsawc4945492002-09-28 20:40:25 +0000546 Optional failobj is the object to return if there is no Content-Type
Barry Warsawba925802001-09-23 03:17:28 +0000547 header. Optional header is the header to search instead of
Barry Warsawc4945492002-09-28 20:40:25 +0000548 Content-Type. If unquote is True, the value is unquoted.
Barry Warsawba925802001-09-23 03:17:28 +0000549 """
550 missing = []
Barry Warsawbeb59452001-09-26 05:41:51 +0000551 params = self._get_params_preserve(missing, header)
552 if params is missing:
Barry Warsawba925802001-09-23 03:17:28 +0000553 return failobj
Barry Warsaw409a4c02002-04-10 21:01:31 +0000554 if unquote:
Barry Warsaw908dc4b2002-06-29 05:56:15 +0000555 return [(k, _unquotevalue(v)) for k, v in params]
Barry Warsaw409a4c02002-04-10 21:01:31 +0000556 else:
557 return params
Barry Warsawba925802001-09-23 03:17:28 +0000558
Barry Warsawc4945492002-09-28 20:40:25 +0000559 def get_param(self, param, failobj=None, header='content-type',
560 unquote=True):
561 """Return the parameter value if found in the Content-Type header.
Barry Warsawba925802001-09-23 03:17:28 +0000562
Barry Warsawc4945492002-09-28 20:40:25 +0000563 Optional failobj is the object to return if there is no Content-Type
Barry Warsaw15aefa92002-09-26 17:19:34 +0000564 header, or the Content-Type header has no such parameter. Optional
Barry Warsawc4945492002-09-28 20:40:25 +0000565 header is the header to search instead of Content-Type.
Barry Warsawbeb59452001-09-26 05:41:51 +0000566
Barry Warsaw15aefa92002-09-26 17:19:34 +0000567 Parameter keys are always compared case insensitively. The return
568 value can either be a string, or a 3-tuple if the parameter was RFC
569 2231 encoded. When it's a 3-tuple, the elements of the value are of
570 the form (CHARSET, LANGUAGE, VALUE), where LANGUAGE may be the empty
571 string. Your application should be prepared to deal with these, and
572 can convert the parameter to a Unicode string like so:
573
574 param = msg.get_param('foo')
575 if isinstance(param, tuple):
576 param = unicode(param[2], param[0])
577
578 In any case, the parameter value (either the returned string, or the
579 VALUE item in the 3-tuple) is always unquoted, unless unquote is set
Barry Warsawc4945492002-09-28 20:40:25 +0000580 to False.
Barry Warsawba925802001-09-23 03:17:28 +0000581 """
Barry Warsawbeb59452001-09-26 05:41:51 +0000582 if not self.has_key(header):
Barry Warsawba925802001-09-23 03:17:28 +0000583 return failobj
Barry Warsawbeb59452001-09-26 05:41:51 +0000584 for k, v in self._get_params_preserve(failobj, header):
585 if k.lower() == param.lower():
Barry Warsaw409a4c02002-04-10 21:01:31 +0000586 if unquote:
Barry Warsaw908dc4b2002-06-29 05:56:15 +0000587 return _unquotevalue(v)
Barry Warsaw409a4c02002-04-10 21:01:31 +0000588 else:
589 return v
Barry Warsawba925802001-09-23 03:17:28 +0000590 return failobj
591
Barry Warsawc4945492002-09-28 20:40:25 +0000592 def set_param(self, param, value, header='Content-Type', requote=True,
Barry Warsaw3c255352002-09-06 03:55:04 +0000593 charset=None, language=''):
Barry Warsawc4945492002-09-28 20:40:25 +0000594 """Set a parameter in the Content-Type header.
Barry Warsaw409a4c02002-04-10 21:01:31 +0000595
596 If the parameter already exists in the header, its value will be
597 replaced with the new value.
598
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000599 If header is Content-Type and has not yet been defined for this
Barry Warsaw409a4c02002-04-10 21:01:31 +0000600 message, it will be set to "text/plain" and the new parameter and
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000601 value will be appended as per RFC 2045.
Barry Warsaw409a4c02002-04-10 21:01:31 +0000602
Barry Warsawc4945492002-09-28 20:40:25 +0000603 An alternate header can specified in the header argument, and all
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000604 parameters will be quoted as necessary unless requote is False.
Barry Warsaw3c255352002-09-06 03:55:04 +0000605
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000606 If charset is specified, the parameter will be encoded according to RFC
607 2231. Optional language specifies the RFC 2231 language, defaulting
608 to the empty string. Both charset and language should be strings.
Barry Warsaw409a4c02002-04-10 21:01:31 +0000609 """
Barry Warsaw3c255352002-09-06 03:55:04 +0000610 if not isinstance(value, TupleType) and charset:
611 value = (charset, language, value)
612
Barry Warsaw409a4c02002-04-10 21:01:31 +0000613 if not self.has_key(header) and header.lower() == 'content-type':
614 ctype = 'text/plain'
615 else:
616 ctype = self.get(header)
617 if not self.get_param(param, header=header):
618 if not ctype:
619 ctype = _formatparam(param, value, requote)
620 else:
621 ctype = SEMISPACE.join(
622 [ctype, _formatparam(param, value, requote)])
623 else:
624 ctype = ''
625 for old_param, old_value in self.get_params(header=header,
626 unquote=requote):
627 append_param = ''
628 if old_param.lower() == param.lower():
629 append_param = _formatparam(param, value, requote)
630 else:
631 append_param = _formatparam(old_param, old_value, requote)
632 if not ctype:
633 ctype = append_param
634 else:
635 ctype = SEMISPACE.join([ctype, append_param])
636 if ctype <> self.get(header):
637 del self[header]
638 self[header] = ctype
639
Barry Warsawc4945492002-09-28 20:40:25 +0000640 def del_param(self, param, header='content-type', requote=True):
Barry Warsaw409a4c02002-04-10 21:01:31 +0000641 """Remove the given parameter completely from the Content-Type header.
642
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000643 The header will be re-written in place without the parameter or its
644 value. All values will be quoted as necessary unless requote is
645 False. Optional header specifies an alternative to the Content-Type
646 header.
Barry Warsaw409a4c02002-04-10 21:01:31 +0000647 """
648 if not self.has_key(header):
649 return
650 new_ctype = ''
651 for p, v in self.get_params(header, unquote=requote):
652 if p.lower() <> param.lower():
653 if not new_ctype:
654 new_ctype = _formatparam(p, v, requote)
655 else:
656 new_ctype = SEMISPACE.join([new_ctype,
657 _formatparam(p, v, requote)])
658 if new_ctype <> self.get(header):
659 del self[header]
660 self[header] = new_ctype
661
Barry Warsawc4945492002-09-28 20:40:25 +0000662 def set_type(self, type, header='Content-Type', requote=True):
663 """Set the main type and subtype for the Content-Type header.
Barry Warsaw409a4c02002-04-10 21:01:31 +0000664
665 type must be a string in the form "maintype/subtype", otherwise a
666 ValueError is raised.
667
Barry Warsawc4945492002-09-28 20:40:25 +0000668 This method replaces the Content-Type header, keeping all the
669 parameters in place. If requote is False, this leaves the existing
Barry Warsaw409a4c02002-04-10 21:01:31 +0000670 header's quoting as is. Otherwise, the parameters will be quoted (the
671 default).
672
Barry Warsaw42d1d3e2002-09-30 18:17:35 +0000673 An alternative header can be specified in the header argument. When
674 the Content-Type header is set, we'll always also add a MIME-Version
Barry Warsaw409a4c02002-04-10 21:01:31 +0000675 header.
676 """
677 # BAW: should we be strict?
678 if not type.count('/') == 1:
679 raise ValueError
Barry Warsawc4945492002-09-28 20:40:25 +0000680 # Set the Content-Type, you get a MIME-Version
Barry Warsaw409a4c02002-04-10 21:01:31 +0000681 if header.lower() == 'content-type':
682 del self['mime-version']
683 self['MIME-Version'] = '1.0'
684 if not self.has_key(header):
685 self[header] = type
686 return
687 params = self.get_params(header, unquote=requote)
688 del self[header]
689 self[header] = type
690 # Skip the first param; it's the old type.
691 for p, v in params[1:]:
692 self.set_param(p, v, header, requote)
693
Barry Warsawba925802001-09-23 03:17:28 +0000694 def get_filename(self, failobj=None):
695 """Return the filename associated with the payload if present.
696
Barry Warsawc4945492002-09-28 20:40:25 +0000697 The filename is extracted from the Content-Disposition header's
Barry Warsawba925802001-09-23 03:17:28 +0000698 `filename' parameter, and it is unquoted.
699 """
700 missing = []
701 filename = self.get_param('filename', missing, 'content-disposition')
702 if filename is missing:
703 return failobj
Barry Warsaw908dc4b2002-06-29 05:56:15 +0000704 if isinstance(filename, TupleType):
705 # It's an RFC 2231 encoded parameter
706 newvalue = _unquotevalue(filename)
707 return unicode(newvalue[2], newvalue[0])
708 else:
709 newvalue = _unquotevalue(filename.strip())
710 return newvalue
Barry Warsawba925802001-09-23 03:17:28 +0000711
712 def get_boundary(self, failobj=None):
713 """Return the boundary associated with the payload if present.
714
Barry Warsawc4945492002-09-28 20:40:25 +0000715 The boundary is extracted from the Content-Type header's `boundary'
Barry Warsawba925802001-09-23 03:17:28 +0000716 parameter, and it is unquoted.
717 """
718 missing = []
719 boundary = self.get_param('boundary', missing)
720 if boundary is missing:
721 return failobj
Barry Warsaw15aefa92002-09-26 17:19:34 +0000722 if isinstance(boundary, TupleType):
723 # RFC 2231 encoded, so decode. It better end up as ascii
724 return unicode(boundary[2], boundary[0]).encode('us-ascii')
Barry Warsaw908dc4b2002-06-29 05:56:15 +0000725 return _unquotevalue(boundary.strip())
Barry Warsawba925802001-09-23 03:17:28 +0000726
727 def set_boundary(self, boundary):
Barry Warsawc4945492002-09-28 20:40:25 +0000728 """Set the boundary parameter in Content-Type to 'boundary'.
Barry Warsawba925802001-09-23 03:17:28 +0000729
Barry Warsawc4945492002-09-28 20:40:25 +0000730 This is subtly different than deleting the Content-Type header and
Barry Warsawba925802001-09-23 03:17:28 +0000731 adding a new one with a new boundary parameter via add_header(). The
732 main difference is that using the set_boundary() method preserves the
Barry Warsawc4945492002-09-28 20:40:25 +0000733 order of the Content-Type header in the original message.
Barry Warsawba925802001-09-23 03:17:28 +0000734
Barry Warsawc4945492002-09-28 20:40:25 +0000735 HeaderParseError is raised if the message has no Content-Type header.
Barry Warsawba925802001-09-23 03:17:28 +0000736 """
Barry Warsawbeb59452001-09-26 05:41:51 +0000737 missing = []
738 params = self._get_params_preserve(missing, 'content-type')
739 if params is missing:
Barry Warsawc4945492002-09-28 20:40:25 +0000740 # There was no Content-Type header, and we don't know what type
Barry Warsawba925802001-09-23 03:17:28 +0000741 # to set it to, so raise an exception.
Barry Warsawc4945492002-09-28 20:40:25 +0000742 raise Errors.HeaderParseError, 'No Content-Type header found'
Barry Warsawba925802001-09-23 03:17:28 +0000743 newparams = []
Barry Warsawc4945492002-09-28 20:40:25 +0000744 foundp = False
Barry Warsawbeb59452001-09-26 05:41:51 +0000745 for pk, pv in params:
746 if pk.lower() == 'boundary':
747 newparams.append(('boundary', '"%s"' % boundary))
Barry Warsawc4945492002-09-28 20:40:25 +0000748 foundp = True
Barry Warsawba925802001-09-23 03:17:28 +0000749 else:
Barry Warsawbeb59452001-09-26 05:41:51 +0000750 newparams.append((pk, pv))
Barry Warsawba925802001-09-23 03:17:28 +0000751 if not foundp:
Barry Warsawc4945492002-09-28 20:40:25 +0000752 # The original Content-Type header had no boundary attribute.
Barry Warsawba925802001-09-23 03:17:28 +0000753 # Tack one one the end. BAW: should we raise an exception
754 # instead???
Barry Warsawbeb59452001-09-26 05:41:51 +0000755 newparams.append(('boundary', '"%s"' % boundary))
Barry Warsawc4945492002-09-28 20:40:25 +0000756 # Replace the existing Content-Type header with the new value
Barry Warsawba925802001-09-23 03:17:28 +0000757 newheaders = []
758 for h, v in self._headers:
759 if h.lower() == 'content-type':
Barry Warsawbeb59452001-09-26 05:41:51 +0000760 parts = []
761 for k, v in newparams:
762 if v == '':
763 parts.append(k)
764 else:
765 parts.append('%s=%s' % (k, v))
766 newheaders.append((h, SEMISPACE.join(parts)))
767
Barry Warsawba925802001-09-23 03:17:28 +0000768 else:
769 newheaders.append((h, v))
770 self._headers = newheaders
771
Barry Warsaw8c1aac22002-05-19 23:44:19 +0000772 try:
773 from email._compat22 import walk
774 except SyntaxError:
775 # Must be using Python 2.1
776 from email._compat21 import walk
Barry Warsawba925802001-09-23 03:17:28 +0000777
Barry Warsaw15aefa92002-09-26 17:19:34 +0000778 def get_content_charset(self, failobj=None):
779 """Return the charset parameter of the Content-Type header.
780
Barry Warsawee07cb12002-10-10 15:13:26 +0000781 The returned string is always coerced to lower case. If there is no
782 Content-Type header, or if that header has no charset parameter,
783 failobj is returned.
Barry Warsaw15aefa92002-09-26 17:19:34 +0000784 """
785 missing = []
786 charset = self.get_param('charset', missing)
787 if charset is missing:
788 return failobj
789 if isinstance(charset, TupleType):
790 # RFC 2231 encoded, so decode it, and it better end up as ascii.
Barry Warsawee07cb12002-10-10 15:13:26 +0000791 charset = unicode(charset[2], charset[0]).encode('us-ascii')
792 # RFC 2046, $4.1.2 says charsets are not case sensitive
793 return charset.lower()
Barry Warsaw15aefa92002-09-26 17:19:34 +0000794
Barry Warsawba925802001-09-23 03:17:28 +0000795 def get_charsets(self, failobj=None):
796 """Return a list containing the charset(s) used in this message.
Tim Peters527e64f2001-10-04 05:36:56 +0000797
Barry Warsawc4945492002-09-28 20:40:25 +0000798 The returned list of items describes the Content-Type headers'
Barry Warsawba925802001-09-23 03:17:28 +0000799 charset parameter for this message and all the subparts in its
800 payload.
801
802 Each item will either be a string (the value of the charset parameter
Barry Warsawc4945492002-09-28 20:40:25 +0000803 in the Content-Type header of that part) or the value of the
Barry Warsawba925802001-09-23 03:17:28 +0000804 'failobj' parameter (defaults to None), if the part does not have a
805 main MIME type of "text", or the charset is not defined.
806
807 The list will contain one string for each part of the message, plus
808 one for the container message (i.e. self), so that a non-multipart
809 message will still return a list of length 1.
810 """
Barry Warsaw15aefa92002-09-26 17:19:34 +0000811 return [part.get_content_charset(failobj) for part in self.walk()]