blob: 8bc82a6b11219652d4dcb32c228913374f4cd990 [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 Warsaw409a4c02002-04-10 21:01:31 +00008import warnings
Barry Warsawba925802001-09-23 03:17:28 +00009from cStringIO import StringIO
Barry Warsaw908dc4b2002-06-29 05:56:15 +000010from types import ListType, TupleType, StringType
Barry Warsawba925802001-09-23 03:17:28 +000011
Barry Warsawba925802001-09-23 03:17:28 +000012# Intrapackage imports
Barry Warsaw8ba76e82002-06-02 19:05:51 +000013from email import Errors
14from email import Utils
15from email import Charset
Barry Warsawba925802001-09-23 03:17:28 +000016
Barry Warsawbeb59452001-09-26 05:41:51 +000017SEMISPACE = '; '
Barry Warsaw409a4c02002-04-10 21:01:31 +000018
19# Regular expression used to split header parameters. BAW: this may be too
20# simple. It isn't strictly RFC 2045 (section 5.1) compliant, but it catches
21# most headers found in the wild. We may eventually need a full fledged
22# parser eventually.
Barry Warsaw2539cf52001-10-25 22:43:46 +000023paramre = re.compile(r'\s*;\s*')
Barry Warsaw409a4c02002-04-10 21:01:31 +000024# Regular expression that matches `special' characters in parameters, the
25# existance of which force quoting of the parameter value.
26tspecials = re.compile(r'[ \(\)<>@,;:\\"/\[\]\?=]')
27
28
29
Barry Warsaw908dc4b2002-06-29 05:56:15 +000030# Helper functions
Barry Warsaw409a4c02002-04-10 21:01:31 +000031def _formatparam(param, value=None, quote=1):
32 """Convenience function to format and return a key=value pair.
33
Barry Warsaw908dc4b2002-06-29 05:56:15 +000034 This will quote the value if needed or if quote is true.
Barry Warsaw409a4c02002-04-10 21:01:31 +000035 """
36 if value is not None and len(value) > 0:
Barry Warsaw908dc4b2002-06-29 05:56:15 +000037 # TupleType is used for RFC 2231 encoded parameter values where items
38 # are (charset, language, value). charset is a string, not a Charset
39 # instance.
40 if isinstance(value, TupleType):
Barry Warsaw3c255352002-09-06 03:55:04 +000041 # Encode as per RFC 2231
42 param += '*'
43 value = Utils.encode_rfc2231(value[2], value[0], value[1])
Barry Warsaw409a4c02002-04-10 21:01:31 +000044 # BAW: Please check this. I think that if quote is set it should
45 # force quoting even if not necessary.
46 if quote or tspecials.search(value):
47 return '%s="%s"' % (param, Utils.quote(value))
48 else:
49 return '%s=%s' % (param, value)
50 else:
51 return param
Barry Warsawbeb59452001-09-26 05:41:51 +000052
Barry Warsawba925802001-09-23 03:17:28 +000053
Barry Warsaw908dc4b2002-06-29 05:56:15 +000054def _unquotevalue(value):
55 if isinstance(value, TupleType):
Barry Warsaw15aefa92002-09-26 17:19:34 +000056 return value[0], value[1], Utils.unquote(value[2])
Barry Warsaw908dc4b2002-06-29 05:56:15 +000057 else:
Tim Peters280488b2002-08-23 18:19:30 +000058 return Utils.unquote(value)
Barry Warsaw908dc4b2002-06-29 05:56:15 +000059
60
Barry Warsaw48b0d362002-08-27 22:34:44 +000061
Barry Warsawba925802001-09-23 03:17:28 +000062class Message:
63 """Basic message object for use inside the object tree.
64
65 A message object is defined as something that has a bunch of RFC 2822
66 headers and a payload. If the body of the message is a multipart, then
67 the payload is a list of Messages, otherwise it is a string.
68
69 These objects implement part of the `mapping' interface, which assumes
70 there is exactly one occurrance of the header per message. Some headers
71 do in fact appear multiple times (e.g. Received:) and for those headers,
72 you must use the explicit API to set or get all the headers. Not all of
73 the mapping methods are implemented.
74
75 """
76 def __init__(self):
77 self._headers = []
78 self._unixfrom = None
79 self._payload = None
Barry Warsaw409a4c02002-04-10 21:01:31 +000080 self._charset = None
Barry Warsawba925802001-09-23 03:17:28 +000081 # Defaults for multipart messages
82 self.preamble = self.epilogue = None
Barry Warsawa0c8b9d2002-07-09 02:46:12 +000083 # Default content type
84 self._default_type = 'text/plain'
Barry Warsawba925802001-09-23 03:17:28 +000085
86 def __str__(self):
87 """Return the entire formatted message as a string.
88 This includes the headers, body, and `unixfrom' line.
89 """
90 return self.as_string(unixfrom=1)
91
92 def as_string(self, unixfrom=0):
93 """Return the entire formatted message as a string.
94 Optional `unixfrom' when true, means include the Unix From_ envelope
95 header.
96 """
Barry Warsaw8ba76e82002-06-02 19:05:51 +000097 from email.Generator import Generator
Barry Warsawba925802001-09-23 03:17:28 +000098 fp = StringIO()
99 g = Generator(fp)
Barry Warsaw8ba76e82002-06-02 19:05:51 +0000100 g.flatten(self, unixfrom=unixfrom)
Barry Warsawba925802001-09-23 03:17:28 +0000101 return fp.getvalue()
102
103 def is_multipart(self):
104 """Return true if the message consists of multiple parts."""
105 if type(self._payload) is ListType:
106 return 1
107 return 0
108
109 #
110 # Unix From_ line
111 #
112 def set_unixfrom(self, unixfrom):
113 self._unixfrom = unixfrom
114
115 def get_unixfrom(self):
116 return self._unixfrom
117
118 #
119 # Payload manipulation.
120 #
121 def add_payload(self, payload):
122 """Add the given payload to the current payload.
123
124 If the current payload is empty, then the current payload will be made
125 a scalar, set to the given value.
126 """
Barry Warsaw409a4c02002-04-10 21:01:31 +0000127 warnings.warn('add_payload() is deprecated, use attach() instead.',
128 DeprecationWarning, 2)
Barry Warsawba925802001-09-23 03:17:28 +0000129 if self._payload is None:
130 self._payload = payload
131 elif type(self._payload) is ListType:
132 self._payload.append(payload)
133 elif self.get_main_type() not in (None, 'multipart'):
134 raise Errors.MultipartConversionError(
135 'Message main Content-Type: must be "multipart" or missing')
136 else:
137 self._payload = [self._payload, payload]
138
Barry Warsaw409a4c02002-04-10 21:01:31 +0000139 def attach(self, payload):
140 """Add the given payload to the current payload.
141
142 The current payload will always be a list of objects after this method
143 is called. If you want to set the payload to a scalar object
144 (e.g. because you're attaching a message/rfc822 subpart), use
145 set_payload() instead.
146 """
147 if self._payload is None:
148 self._payload = [payload]
149 else:
150 self._payload.append(payload)
Barry Warsawba925802001-09-23 03:17:28 +0000151
152 def get_payload(self, i=None, decode=0):
Barry Warsawfbcde752002-09-11 14:11:35 +0000153 """Return a reference to the payload.
Barry Warsawba925802001-09-23 03:17:28 +0000154
Barry Warsawfbcde752002-09-11 14:11:35 +0000155 The payload is typically either a list object or a string. If you
156 mutate the list object, you modify the message's payload in place.
Barry Warsawba925802001-09-23 03:17:28 +0000157 Optional i returns that index into the payload.
158
159 Optional decode is a flag indicating whether the payload should be
160 decoded or not, according to the Content-Transfer-Encoding: header.
161 When true and the message is not a multipart, the payload will be
162 decoded if this header's value is `quoted-printable' or `base64'. If
163 some other encoding is used, or the header is missing, the payload is
164 returned as-is (undecoded). If the message is a multipart and the
165 decode flag is true, then None is returned.
166 """
167 if i is None:
168 payload = self._payload
169 elif type(self._payload) is not ListType:
170 raise TypeError, i
171 else:
172 payload = self._payload[i]
173 if decode:
174 if self.is_multipart():
175 return None
176 cte = self.get('content-transfer-encoding', '')
177 if cte.lower() == 'quoted-printable':
178 return Utils._qdecode(payload)
179 elif cte.lower() == 'base64':
180 return Utils._bdecode(payload)
181 # Everything else, including encodings with 8bit or 7bit are returned
182 # unchanged.
183 return payload
184
Barry Warsaw409a4c02002-04-10 21:01:31 +0000185 def set_payload(self, payload, charset=None):
186 """Set the payload to the given value.
Barry Warsawba925802001-09-23 03:17:28 +0000187
Barry Warsaw409a4c02002-04-10 21:01:31 +0000188 Optionally set the charset, which must be a Charset instance."""
189 self._payload = payload
190 if charset is not None:
191 self.set_charset(charset)
192
193 def set_charset(self, charset):
194 """Set the charset of the payload to a given character set.
195
196 charset can be a string or a Charset object. If it is a string, it
197 will be converted to a Charset object by calling Charset's
198 constructor. If charset is None, the charset parameter will be
199 removed from the Content-Type: field. Anything else will generate a
200 TypeError.
201
202 The message will be assumed to be a text message encoded with
203 charset.input_charset. It will be converted to charset.output_charset
204 and encoded properly, if needed, when generating the plain text
205 representation of the message. MIME headers (MIME-Version,
206 Content-Type, Content-Transfer-Encoding) will be added as needed.
207 """
208 if charset is None:
209 self.del_param('charset')
210 self._charset = None
211 return
212 if isinstance(charset, StringType):
213 charset = Charset.Charset(charset)
214 if not isinstance(charset, Charset.Charset):
215 raise TypeError, charset
216 # BAW: should we accept strings that can serve as arguments to the
217 # Charset constructor?
218 self._charset = charset
219 if not self.has_key('MIME-Version'):
220 self.add_header('MIME-Version', '1.0')
221 if not self.has_key('Content-Type'):
222 self.add_header('Content-Type', 'text/plain',
223 charset=charset.get_output_charset())
224 else:
225 self.set_param('charset', charset.get_output_charset())
226 if not self.has_key('Content-Transfer-Encoding'):
227 cte = charset.get_body_encoding()
228 if callable(cte):
229 cte(self)
230 else:
231 self.add_header('Content-Transfer-Encoding', cte)
232
233 def get_charset(self):
234 """Return the Charset object associated with the message's payload."""
235 return self._charset
Tim Peters8ac14952002-05-23 15:15:30 +0000236
Barry Warsawba925802001-09-23 03:17:28 +0000237 #
238 # MAPPING INTERFACE (partial)
239 #
240 def __len__(self):
Barry Warsawbeb59452001-09-26 05:41:51 +0000241 """Return the total number of headers, including duplicates."""
Barry Warsawba925802001-09-23 03:17:28 +0000242 return len(self._headers)
243
244 def __getitem__(self, name):
245 """Get a header value.
246
247 Return None if the header is missing instead of raising an exception.
248
249 Note that if the header appeared multiple times, exactly which
250 occurrance gets returned is undefined. Use getall() to get all
251 the values matching a header field name.
252 """
253 return self.get(name)
254
255 def __setitem__(self, name, val):
256 """Set the value of a header.
257
258 Note: this does not overwrite an existing header with the same field
259 name. Use __delitem__() first to delete any existing headers.
260 """
261 self._headers.append((name, val))
262
263 def __delitem__(self, name):
264 """Delete all occurrences of a header, if present.
265
266 Does not raise an exception if the header is missing.
267 """
268 name = name.lower()
269 newheaders = []
270 for k, v in self._headers:
271 if k.lower() <> name:
272 newheaders.append((k, v))
273 self._headers = newheaders
274
275 def __contains__(self, key):
276 return key.lower() in [k.lower() for k, v in self._headers]
277
278 def has_key(self, name):
279 """Return true if the message contains the header."""
Barry Warsawbeb59452001-09-26 05:41:51 +0000280 missing = []
281 return self.get(name, missing) is not missing
Barry Warsawba925802001-09-23 03:17:28 +0000282
283 def keys(self):
284 """Return a list of all the message's header field names.
285
286 These will be sorted in the order they appeared in the original
287 message, and may contain duplicates. Any fields deleted and
288 re-inserted are always appended to the header list.
289 """
290 return [k for k, v in self._headers]
291
292 def values(self):
293 """Return a list of all the message's header values.
294
295 These will be sorted in the order they appeared in the original
296 message, and may contain duplicates. Any fields deleted and
Barry Warsawbf7c52c2001-11-24 16:56:56 +0000297 re-inserted are always appended to the header list.
Barry Warsawba925802001-09-23 03:17:28 +0000298 """
299 return [v for k, v in self._headers]
300
301 def items(self):
302 """Get all the message's header fields and values.
303
304 These will be sorted in the order they appeared in the original
305 message, and may contain duplicates. Any fields deleted and
Barry Warsawbf7c52c2001-11-24 16:56:56 +0000306 re-inserted are always appended to the header list.
Barry Warsawba925802001-09-23 03:17:28 +0000307 """
308 return self._headers[:]
309
310 def get(self, name, failobj=None):
311 """Get a header value.
312
313 Like __getitem__() but return failobj instead of None when the field
314 is missing.
315 """
316 name = name.lower()
317 for k, v in self._headers:
318 if k.lower() == name:
319 return v
320 return failobj
321
322 #
323 # Additional useful stuff
324 #
325
326 def get_all(self, name, failobj=None):
327 """Return a list of all the values for the named field.
328
329 These will be sorted in the order they appeared in the original
330 message, and may contain duplicates. Any fields deleted and
Greg Ward6253c2d2001-11-24 15:49:53 +0000331 re-inserted are always appended to the header list.
Barry Warsaw9300a752001-10-09 15:48:29 +0000332
333 If no such fields exist, failobj is returned (defaults to None).
Barry Warsawba925802001-09-23 03:17:28 +0000334 """
335 values = []
336 name = name.lower()
337 for k, v in self._headers:
338 if k.lower() == name:
339 values.append(v)
Barry Warsaw9300a752001-10-09 15:48:29 +0000340 if not values:
341 return failobj
Barry Warsawba925802001-09-23 03:17:28 +0000342 return values
343
344 def add_header(self, _name, _value, **_params):
345 """Extended header setting.
346
347 name is the header field to add. keyword arguments can be used to set
348 additional parameters for the header field, with underscores converted
349 to dashes. Normally the parameter will be added as key="value" unless
350 value is None, in which case only the key will be added.
351
352 Example:
353
354 msg.add_header('content-disposition', 'attachment', filename='bud.gif')
Barry Warsawba925802001-09-23 03:17:28 +0000355 """
356 parts = []
357 for k, v in _params.items():
358 if v is None:
359 parts.append(k.replace('_', '-'))
360 else:
Barry Warsaw409a4c02002-04-10 21:01:31 +0000361 parts.append(_formatparam(k.replace('_', '-'), v))
Barry Warsawba925802001-09-23 03:17:28 +0000362 if _value is not None:
363 parts.insert(0, _value)
364 self._headers.append((_name, SEMISPACE.join(parts)))
365
Barry Warsaw229727f2002-09-06 03:38:12 +0000366 def replace_header(self, _name, _value):
367 """Replace a header.
368
369 Replace the first matching header found in the message, retaining
370 header order and case. If no matching header was found, a KeyError is
371 raised.
372 """
373 _name = _name.lower()
374 for i, (k, v) in zip(range(len(self._headers)), self._headers):
375 if k.lower() == _name:
376 self._headers[i] = (k, _value)
377 break
378 else:
379 raise KeyError, _name
380
Barry Warsawc1068642002-07-19 22:24:55 +0000381 #
382 # These methods are silently deprecated in favor of get_content_type() and
383 # friends (see below). They will be noisily deprecated in email 3.0.
384 #
385
Barry Warsawba925802001-09-23 03:17:28 +0000386 def get_type(self, failobj=None):
387 """Returns the message's content type.
388
389 The returned string is coerced to lowercase and returned as a single
390 string of the form `maintype/subtype'. If there was no Content-Type:
391 header in the message, failobj is returned (defaults to None).
392 """
393 missing = []
394 value = self.get('content-type', missing)
395 if value is missing:
396 return failobj
Barry Warsaw7aeac912002-07-18 23:09:09 +0000397 return paramre.split(value)[0].lower().strip()
Barry Warsawba925802001-09-23 03:17:28 +0000398
399 def get_main_type(self, failobj=None):
400 """Return the message's main content type if present."""
401 missing = []
402 ctype = self.get_type(missing)
403 if ctype is missing:
404 return failobj
Barry Warsawc1068642002-07-19 22:24:55 +0000405 if ctype.count('/') <> 1:
406 return failobj
407 return ctype.split('/')[0]
Barry Warsawba925802001-09-23 03:17:28 +0000408
409 def get_subtype(self, failobj=None):
410 """Return the message's content subtype if present."""
411 missing = []
412 ctype = self.get_type(missing)
413 if ctype is missing:
414 return failobj
Barry Warsawc1068642002-07-19 22:24:55 +0000415 if ctype.count('/') <> 1:
416 return failobj
417 return ctype.split('/')[1]
418
419 #
420 # Use these three methods instead of the three above.
421 #
422
423 def get_content_type(self):
424 """Returns the message's content type.
425
426 The returned string is coerced to lowercase and returned as a ingle
427 string of the form `maintype/subtype'. If there was no Content-Type:
428 header in the message, the default type as give by get_default_type()
429 will be returned. Since messages always have a default type this will
430 always return a value.
431
432 The current state of RFC standards define a message's default type to
433 be text/plain unless it appears inside a multipart/digest container,
434 in which case it would be message/rfc822.
435 """
436 missing = []
437 value = self.get('content-type', missing)
438 if value is missing:
439 # This should have no parameters
440 return self.get_default_type()
Barry Warsawf36d8042002-08-20 14:50:09 +0000441 ctype = paramre.split(value)[0].lower().strip()
442 # RFC 2045, section 5.2 says if its invalid, use text/plain
443 if ctype.count('/') <> 1:
444 return 'text/plain'
445 return ctype
Barry Warsawc1068642002-07-19 22:24:55 +0000446
447 def get_content_maintype(self):
448 """Returns the message's main content type.
449
450 This is the `maintype' part of the string returned by
451 get_content_type(). If no slash is found in the full content type, a
452 ValueError is raised.
453 """
454 ctype = self.get_content_type()
Barry Warsawc1068642002-07-19 22:24:55 +0000455 return ctype.split('/')[0]
456
457 def get_content_subtype(self):
458 """Returns the message's sub content type.
459
460 This is the `subtype' part of the string returned by
461 get_content_type(). If no slash is found in the full content type, a
462 ValueError is raised.
463 """
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
472 subparts then have a default content type of message/rfc822.
473 """
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
481 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?
488 missing = []
489 value = self.get(header, missing)
490 if value is missing:
491 return failobj
492 params = []
493 for p in paramre.split(value):
494 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 Warsaw908dc4b2002-06-29 05:56:15 +0000503 params = Utils.decode_params(params)
Barry Warsawbeb59452001-09-26 05:41:51 +0000504 return params
505
Barry Warsaw409a4c02002-04-10 21:01:31 +0000506 def get_params(self, failobj=None, header='content-type', unquote=1):
Barry Warsawba925802001-09-23 03:17:28 +0000507 """Return the message's Content-Type: parameters, as a list.
508
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 Warsawba925802001-09-23 03:17:28 +0000515 Optional failobj is the object to return if there is no Content-Type:
516 header. Optional header is the header to search instead of
Barry Warsaw409a4c02002-04-10 21:01:31 +0000517 Content-Type:.
Barry Warsawba925802001-09-23 03:17:28 +0000518 """
519 missing = []
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 Warsaw409a4c02002-04-10 21:01:31 +0000528 def get_param(self, param, failobj=None, header='content-type', unquote=1):
Barry Warsawba925802001-09-23 03:17:28 +0000529 """Return the parameter value if found in the Content-Type: header.
530
531 Optional failobj is the object to return if there is no Content-Type:
Barry Warsaw15aefa92002-09-26 17:19:34 +0000532 header, or the Content-Type header has no such parameter. Optional
533 header is the header to search instead of Content-Type:
Barry Warsawbeb59452001-09-26 05:41:51 +0000534
Barry Warsaw15aefa92002-09-26 17:19:34 +0000535 Parameter keys are always compared case insensitively. The return
536 value can either be a string, or a 3-tuple if the parameter was RFC
537 2231 encoded. When it's a 3-tuple, the elements of the value are of
538 the form (CHARSET, LANGUAGE, VALUE), where LANGUAGE may be the empty
539 string. Your application should be prepared to deal with these, and
540 can convert the parameter to a Unicode string like so:
541
542 param = msg.get_param('foo')
543 if isinstance(param, tuple):
544 param = unicode(param[2], param[0])
545
546 In any case, the parameter value (either the returned string, or the
547 VALUE item in the 3-tuple) is always unquoted, unless unquote is set
548 to a false value.
Barry Warsawba925802001-09-23 03:17:28 +0000549 """
Barry Warsawbeb59452001-09-26 05:41:51 +0000550 if not self.has_key(header):
Barry Warsawba925802001-09-23 03:17:28 +0000551 return failobj
Barry Warsawbeb59452001-09-26 05:41:51 +0000552 for k, v in self._get_params_preserve(failobj, header):
553 if k.lower() == param.lower():
Barry Warsaw409a4c02002-04-10 21:01:31 +0000554 if unquote:
Barry Warsaw908dc4b2002-06-29 05:56:15 +0000555 return _unquotevalue(v)
Barry Warsaw409a4c02002-04-10 21:01:31 +0000556 else:
557 return v
Barry Warsawba925802001-09-23 03:17:28 +0000558 return failobj
559
Barry Warsaw3c255352002-09-06 03:55:04 +0000560 def set_param(self, param, value, header='Content-Type', requote=1,
561 charset=None, language=''):
Barry Warsaw409a4c02002-04-10 21:01:31 +0000562 """Set a parameter in the Content-Type: header.
563
564 If the parameter already exists in the header, its value will be
565 replaced with the new value.
566
567 If header is Content-Type: and has not yet been defined in this
568 message, it will be set to "text/plain" and the new parameter and
569 value will be appended, as per RFC 2045.
570
571 An alternate header can specified in the header argument, and
572 all parameters will be quoted as appropriate unless requote is
573 set to a false value.
Barry Warsaw3c255352002-09-06 03:55:04 +0000574
575 If charset is specified the parameter will be encoded according to RFC
576 2231. In this case language is optional.
Barry Warsaw409a4c02002-04-10 21:01:31 +0000577 """
Barry Warsaw3c255352002-09-06 03:55:04 +0000578 if not isinstance(value, TupleType) and charset:
579 value = (charset, language, value)
580
Barry Warsaw409a4c02002-04-10 21:01:31 +0000581 if not self.has_key(header) and header.lower() == 'content-type':
582 ctype = 'text/plain'
583 else:
584 ctype = self.get(header)
585 if not self.get_param(param, header=header):
586 if not ctype:
587 ctype = _formatparam(param, value, requote)
588 else:
589 ctype = SEMISPACE.join(
590 [ctype, _formatparam(param, value, requote)])
591 else:
592 ctype = ''
593 for old_param, old_value in self.get_params(header=header,
594 unquote=requote):
595 append_param = ''
596 if old_param.lower() == param.lower():
597 append_param = _formatparam(param, value, requote)
598 else:
599 append_param = _formatparam(old_param, old_value, requote)
600 if not ctype:
601 ctype = append_param
602 else:
603 ctype = SEMISPACE.join([ctype, append_param])
604 if ctype <> self.get(header):
605 del self[header]
606 self[header] = ctype
607
608 def del_param(self, param, header='content-type', requote=1):
609 """Remove the given parameter completely from the Content-Type header.
610
611 The header will be re-written in place without param or its value.
612 All values will be quoted as appropriate unless requote is set to a
613 false value.
614 """
615 if not self.has_key(header):
616 return
617 new_ctype = ''
618 for p, v in self.get_params(header, unquote=requote):
619 if p.lower() <> param.lower():
620 if not new_ctype:
621 new_ctype = _formatparam(p, v, requote)
622 else:
623 new_ctype = SEMISPACE.join([new_ctype,
624 _formatparam(p, v, requote)])
625 if new_ctype <> self.get(header):
626 del self[header]
627 self[header] = new_ctype
628
629 def set_type(self, type, header='Content-Type', requote=1):
630 """Set the main type and subtype for the Content-Type: header.
631
632 type must be a string in the form "maintype/subtype", otherwise a
633 ValueError is raised.
634
635 This method replaces the Content-Type: header, keeping all the
636 parameters in place. If requote is false, this leaves the existing
637 header's quoting as is. Otherwise, the parameters will be quoted (the
638 default).
639
640 An alternate header can be specified in the header argument. When the
641 Content-Type: header is set, we'll always also add a MIME-Version:
642 header.
643 """
644 # BAW: should we be strict?
645 if not type.count('/') == 1:
646 raise ValueError
647 # Set the Content-Type: you get a MIME-Version:
648 if header.lower() == 'content-type':
649 del self['mime-version']
650 self['MIME-Version'] = '1.0'
651 if not self.has_key(header):
652 self[header] = type
653 return
654 params = self.get_params(header, unquote=requote)
655 del self[header]
656 self[header] = type
657 # Skip the first param; it's the old type.
658 for p, v in params[1:]:
659 self.set_param(p, v, header, requote)
660
Barry Warsawba925802001-09-23 03:17:28 +0000661 def get_filename(self, failobj=None):
662 """Return the filename associated with the payload if present.
663
664 The filename is extracted from the Content-Disposition: header's
665 `filename' parameter, and it is unquoted.
666 """
667 missing = []
668 filename = self.get_param('filename', missing, 'content-disposition')
669 if filename is missing:
670 return failobj
Barry Warsaw908dc4b2002-06-29 05:56:15 +0000671 if isinstance(filename, TupleType):
672 # It's an RFC 2231 encoded parameter
673 newvalue = _unquotevalue(filename)
674 return unicode(newvalue[2], newvalue[0])
675 else:
676 newvalue = _unquotevalue(filename.strip())
677 return newvalue
Barry Warsawba925802001-09-23 03:17:28 +0000678
679 def get_boundary(self, failobj=None):
680 """Return the boundary associated with the payload if present.
681
682 The boundary is extracted from the Content-Type: header's `boundary'
683 parameter, and it is unquoted.
684 """
685 missing = []
686 boundary = self.get_param('boundary', missing)
687 if boundary is missing:
688 return failobj
Barry Warsaw15aefa92002-09-26 17:19:34 +0000689 if isinstance(boundary, TupleType):
690 # RFC 2231 encoded, so decode. It better end up as ascii
691 return unicode(boundary[2], boundary[0]).encode('us-ascii')
Barry Warsaw908dc4b2002-06-29 05:56:15 +0000692 return _unquotevalue(boundary.strip())
Barry Warsawba925802001-09-23 03:17:28 +0000693
694 def set_boundary(self, boundary):
695 """Set the boundary parameter in Content-Type: to 'boundary'.
696
697 This is subtly different than deleting the Content-Type: header and
698 adding a new one with a new boundary parameter via add_header(). The
699 main difference is that using the set_boundary() method preserves the
700 order of the Content-Type: header in the original message.
701
702 HeaderParseError is raised if the message has no Content-Type: header.
703 """
Barry Warsawbeb59452001-09-26 05:41:51 +0000704 missing = []
705 params = self._get_params_preserve(missing, 'content-type')
706 if params is missing:
Barry Warsawba925802001-09-23 03:17:28 +0000707 # There was no Content-Type: header, and we don't know what type
708 # to set it to, so raise an exception.
709 raise Errors.HeaderParseError, 'No Content-Type: header found'
710 newparams = []
711 foundp = 0
Barry Warsawbeb59452001-09-26 05:41:51 +0000712 for pk, pv in params:
713 if pk.lower() == 'boundary':
714 newparams.append(('boundary', '"%s"' % boundary))
Barry Warsawba925802001-09-23 03:17:28 +0000715 foundp = 1
716 else:
Barry Warsawbeb59452001-09-26 05:41:51 +0000717 newparams.append((pk, pv))
Barry Warsawba925802001-09-23 03:17:28 +0000718 if not foundp:
719 # The original Content-Type: header had no boundary attribute.
720 # Tack one one the end. BAW: should we raise an exception
721 # instead???
Barry Warsawbeb59452001-09-26 05:41:51 +0000722 newparams.append(('boundary', '"%s"' % boundary))
Barry Warsawba925802001-09-23 03:17:28 +0000723 # Replace the existing Content-Type: header with the new value
724 newheaders = []
725 for h, v in self._headers:
726 if h.lower() == 'content-type':
Barry Warsawbeb59452001-09-26 05:41:51 +0000727 parts = []
728 for k, v in newparams:
729 if v == '':
730 parts.append(k)
731 else:
732 parts.append('%s=%s' % (k, v))
733 newheaders.append((h, SEMISPACE.join(parts)))
734
Barry Warsawba925802001-09-23 03:17:28 +0000735 else:
736 newheaders.append((h, v))
737 self._headers = newheaders
738
Barry Warsaw8c1aac22002-05-19 23:44:19 +0000739 try:
740 from email._compat22 import walk
741 except SyntaxError:
742 # Must be using Python 2.1
743 from email._compat21 import walk
Barry Warsawba925802001-09-23 03:17:28 +0000744
Barry Warsaw15aefa92002-09-26 17:19:34 +0000745 def get_content_charset(self, failobj=None):
746 """Return the charset parameter of the Content-Type header.
747
748 If there is no Content-Type header, or if that header has no charset
749 parameter, failobj is returned.
750 """
751 missing = []
752 charset = self.get_param('charset', missing)
753 if charset is missing:
754 return failobj
755 if isinstance(charset, TupleType):
756 # RFC 2231 encoded, so decode it, and it better end up as ascii.
757 return unicode(charset[2], charset[0]).encode('us-ascii')
758 return charset
759
Barry Warsawba925802001-09-23 03:17:28 +0000760 def get_charsets(self, failobj=None):
761 """Return a list containing the charset(s) used in this message.
Tim Peters527e64f2001-10-04 05:36:56 +0000762
Barry Warsawba925802001-09-23 03:17:28 +0000763 The returned list of items describes the Content-Type: headers'
764 charset parameter for this message and all the subparts in its
765 payload.
766
767 Each item will either be a string (the value of the charset parameter
768 in the Content-Type: header of that part) or the value of the
769 'failobj' parameter (defaults to None), if the part does not have a
770 main MIME type of "text", or the charset is not defined.
771
772 The list will contain one string for each part of the message, plus
773 one for the container message (i.e. self), so that a non-multipart
774 message will still return a list of length 1.
775 """
Barry Warsaw15aefa92002-09-26 17:19:34 +0000776 return [part.get_content_charset(failobj) for part in self.walk()]