blob: 326d0b82f2910ba86edc7c4dba0db8727f152732 [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):
Tim Peters280488b2002-08-23 18:19:30 +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):
153 """Return the current payload exactly as is.
154
155 Optional i returns that index into the payload.
156
157 Optional decode is a flag indicating whether the payload should be
158 decoded or not, according to the Content-Transfer-Encoding: header.
159 When true and the message is not a multipart, the payload will be
160 decoded if this header's value is `quoted-printable' or `base64'. If
161 some other encoding is used, or the header is missing, the payload is
162 returned as-is (undecoded). If the message is a multipart and the
163 decode flag is true, then None is returned.
164 """
165 if i is None:
166 payload = self._payload
167 elif type(self._payload) is not ListType:
168 raise TypeError, i
169 else:
170 payload = self._payload[i]
171 if decode:
172 if self.is_multipart():
173 return None
174 cte = self.get('content-transfer-encoding', '')
175 if cte.lower() == 'quoted-printable':
176 return Utils._qdecode(payload)
177 elif cte.lower() == 'base64':
178 return Utils._bdecode(payload)
179 # Everything else, including encodings with 8bit or 7bit are returned
180 # unchanged.
181 return payload
182
183
Barry Warsaw409a4c02002-04-10 21:01:31 +0000184 def set_payload(self, payload, charset=None):
185 """Set the payload to the given value.
Barry Warsawba925802001-09-23 03:17:28 +0000186
Barry Warsaw409a4c02002-04-10 21:01:31 +0000187 Optionally set the charset, which must be a Charset instance."""
188 self._payload = payload
189 if charset is not None:
190 self.set_charset(charset)
191
192 def set_charset(self, charset):
193 """Set the charset of the payload to a given character set.
194
195 charset can be a string or a Charset object. If it is a string, it
196 will be converted to a Charset object by calling Charset's
197 constructor. If charset is None, the charset parameter will be
198 removed from the Content-Type: field. Anything else will generate a
199 TypeError.
200
201 The message will be assumed to be a text message encoded with
202 charset.input_charset. It will be converted to charset.output_charset
203 and encoded properly, if needed, when generating the plain text
204 representation of the message. MIME headers (MIME-Version,
205 Content-Type, Content-Transfer-Encoding) will be added as needed.
206 """
207 if charset is None:
208 self.del_param('charset')
209 self._charset = None
210 return
211 if isinstance(charset, StringType):
212 charset = Charset.Charset(charset)
213 if not isinstance(charset, Charset.Charset):
214 raise TypeError, charset
215 # BAW: should we accept strings that can serve as arguments to the
216 # Charset constructor?
217 self._charset = charset
218 if not self.has_key('MIME-Version'):
219 self.add_header('MIME-Version', '1.0')
220 if not self.has_key('Content-Type'):
221 self.add_header('Content-Type', 'text/plain',
222 charset=charset.get_output_charset())
223 else:
224 self.set_param('charset', charset.get_output_charset())
225 if not self.has_key('Content-Transfer-Encoding'):
226 cte = charset.get_body_encoding()
227 if callable(cte):
228 cte(self)
229 else:
230 self.add_header('Content-Transfer-Encoding', cte)
231
232 def get_charset(self):
233 """Return the Charset object associated with the message's payload."""
234 return self._charset
Tim Peters8ac14952002-05-23 15:15:30 +0000235
Barry Warsawba925802001-09-23 03:17:28 +0000236 #
237 # MAPPING INTERFACE (partial)
238 #
239 def __len__(self):
Barry Warsawbeb59452001-09-26 05:41:51 +0000240 """Return the total number of headers, including duplicates."""
Barry Warsawba925802001-09-23 03:17:28 +0000241 return len(self._headers)
242
243 def __getitem__(self, name):
244 """Get a header value.
245
246 Return None if the header is missing instead of raising an exception.
247
248 Note that if the header appeared multiple times, exactly which
249 occurrance gets returned is undefined. Use getall() to get all
250 the values matching a header field name.
251 """
252 return self.get(name)
253
254 def __setitem__(self, name, val):
255 """Set the value of a header.
256
257 Note: this does not overwrite an existing header with the same field
258 name. Use __delitem__() first to delete any existing headers.
259 """
260 self._headers.append((name, val))
261
262 def __delitem__(self, name):
263 """Delete all occurrences of a header, if present.
264
265 Does not raise an exception if the header is missing.
266 """
267 name = name.lower()
268 newheaders = []
269 for k, v in self._headers:
270 if k.lower() <> name:
271 newheaders.append((k, v))
272 self._headers = newheaders
273
274 def __contains__(self, key):
275 return key.lower() in [k.lower() for k, v in self._headers]
276
277 def has_key(self, name):
278 """Return true if the message contains the header."""
Barry Warsawbeb59452001-09-26 05:41:51 +0000279 missing = []
280 return self.get(name, missing) is not missing
Barry Warsawba925802001-09-23 03:17:28 +0000281
282 def keys(self):
283 """Return a list of all the message's header field names.
284
285 These will be sorted in the order they appeared in the original
286 message, and may contain duplicates. Any fields deleted and
287 re-inserted are always appended to the header list.
288 """
289 return [k for k, v in self._headers]
290
291 def values(self):
292 """Return a list of all the message's header values.
293
294 These will be sorted in the order they appeared in the original
295 message, and may contain duplicates. Any fields deleted and
Barry Warsawbf7c52c2001-11-24 16:56:56 +0000296 re-inserted are always appended to the header list.
Barry Warsawba925802001-09-23 03:17:28 +0000297 """
298 return [v for k, v in self._headers]
299
300 def items(self):
301 """Get all the message's header fields and values.
302
303 These will be sorted in the order they appeared in the original
304 message, and may contain duplicates. Any fields deleted and
Barry Warsawbf7c52c2001-11-24 16:56:56 +0000305 re-inserted are always appended to the header list.
Barry Warsawba925802001-09-23 03:17:28 +0000306 """
307 return self._headers[:]
308
309 def get(self, name, failobj=None):
310 """Get a header value.
311
312 Like __getitem__() but return failobj instead of None when the field
313 is missing.
314 """
315 name = name.lower()
316 for k, v in self._headers:
317 if k.lower() == name:
318 return v
319 return failobj
320
321 #
322 # Additional useful stuff
323 #
324
325 def get_all(self, name, failobj=None):
326 """Return a list of all the values for the named field.
327
328 These will be sorted in the order they appeared in the original
329 message, and may contain duplicates. Any fields deleted and
Greg Ward6253c2d2001-11-24 15:49:53 +0000330 re-inserted are always appended to the header list.
Barry Warsaw9300a752001-10-09 15:48:29 +0000331
332 If no such fields exist, failobj is returned (defaults to None).
Barry Warsawba925802001-09-23 03:17:28 +0000333 """
334 values = []
335 name = name.lower()
336 for k, v in self._headers:
337 if k.lower() == name:
338 values.append(v)
Barry Warsaw9300a752001-10-09 15:48:29 +0000339 if not values:
340 return failobj
Barry Warsawba925802001-09-23 03:17:28 +0000341 return values
342
343 def add_header(self, _name, _value, **_params):
344 """Extended header setting.
345
346 name is the header field to add. keyword arguments can be used to set
347 additional parameters for the header field, with underscores converted
348 to dashes. Normally the parameter will be added as key="value" unless
349 value is None, in which case only the key will be added.
350
351 Example:
352
353 msg.add_header('content-disposition', 'attachment', filename='bud.gif')
Barry Warsawba925802001-09-23 03:17:28 +0000354 """
355 parts = []
356 for k, v in _params.items():
357 if v is None:
358 parts.append(k.replace('_', '-'))
359 else:
Barry Warsaw409a4c02002-04-10 21:01:31 +0000360 parts.append(_formatparam(k.replace('_', '-'), v))
Barry Warsawba925802001-09-23 03:17:28 +0000361 if _value is not None:
362 parts.insert(0, _value)
363 self._headers.append((_name, SEMISPACE.join(parts)))
364
Barry Warsaw229727f2002-09-06 03:38:12 +0000365 def replace_header(self, _name, _value):
366 """Replace a header.
367
368 Replace the first matching header found in the message, retaining
369 header order and case. If no matching header was found, a KeyError is
370 raised.
371 """
372 _name = _name.lower()
373 for i, (k, v) in zip(range(len(self._headers)), self._headers):
374 if k.lower() == _name:
375 self._headers[i] = (k, _value)
376 break
377 else:
378 raise KeyError, _name
379
Barry Warsawc1068642002-07-19 22:24:55 +0000380 #
381 # These methods are silently deprecated in favor of get_content_type() and
382 # friends (see below). They will be noisily deprecated in email 3.0.
383 #
384
Barry Warsawba925802001-09-23 03:17:28 +0000385 def get_type(self, failobj=None):
386 """Returns the message's content type.
387
388 The returned string is coerced to lowercase and returned as a single
389 string of the form `maintype/subtype'. If there was no Content-Type:
390 header in the message, failobj is returned (defaults to None).
391 """
392 missing = []
393 value = self.get('content-type', missing)
394 if value is missing:
395 return failobj
Barry Warsaw7aeac912002-07-18 23:09:09 +0000396 return paramre.split(value)[0].lower().strip()
Barry Warsawba925802001-09-23 03:17:28 +0000397
398 def get_main_type(self, failobj=None):
399 """Return the message's main content type if present."""
400 missing = []
401 ctype = self.get_type(missing)
402 if ctype is missing:
403 return failobj
Barry Warsawc1068642002-07-19 22:24:55 +0000404 if ctype.count('/') <> 1:
405 return failobj
406 return ctype.split('/')[0]
Barry Warsawba925802001-09-23 03:17:28 +0000407
408 def get_subtype(self, failobj=None):
409 """Return the message's content subtype if present."""
410 missing = []
411 ctype = self.get_type(missing)
412 if ctype is missing:
413 return failobj
Barry Warsawc1068642002-07-19 22:24:55 +0000414 if ctype.count('/') <> 1:
415 return failobj
416 return ctype.split('/')[1]
417
418 #
419 # Use these three methods instead of the three above.
420 #
421
422 def get_content_type(self):
423 """Returns the message's content type.
424
425 The returned string is coerced to lowercase and returned as a ingle
426 string of the form `maintype/subtype'. If there was no Content-Type:
427 header in the message, the default type as give by get_default_type()
428 will be returned. Since messages always have a default type this will
429 always return a value.
430
431 The current state of RFC standards define a message's default type to
432 be text/plain unless it appears inside a multipart/digest container,
433 in which case it would be message/rfc822.
434 """
435 missing = []
436 value = self.get('content-type', missing)
437 if value is missing:
438 # This should have no parameters
439 return self.get_default_type()
Barry Warsawf36d8042002-08-20 14:50:09 +0000440 ctype = paramre.split(value)[0].lower().strip()
441 # RFC 2045, section 5.2 says if its invalid, use text/plain
442 if ctype.count('/') <> 1:
443 return 'text/plain'
444 return ctype
Barry Warsawc1068642002-07-19 22:24:55 +0000445
446 def get_content_maintype(self):
447 """Returns the message's main content type.
448
449 This is the `maintype' part of the string returned by
450 get_content_type(). If no slash is found in the full content type, a
451 ValueError is raised.
452 """
453 ctype = self.get_content_type()
Barry Warsawc1068642002-07-19 22:24:55 +0000454 return ctype.split('/')[0]
455
456 def get_content_subtype(self):
457 """Returns the message's sub content type.
458
459 This is the `subtype' part of the string returned by
460 get_content_type(). If no slash is found in the full content type, a
461 ValueError is raised.
462 """
463 ctype = self.get_content_type()
Barry Warsawc1068642002-07-19 22:24:55 +0000464 return ctype.split('/')[1]
Barry Warsawba925802001-09-23 03:17:28 +0000465
Barry Warsawa0c8b9d2002-07-09 02:46:12 +0000466 def get_default_type(self):
467 """Return the `default' content type.
468
469 Most messages have a default content type of text/plain, except for
470 messages that are subparts of multipart/digest containers. Such
471 subparts then have a default content type of message/rfc822.
472 """
473 return self._default_type
474
475 def set_default_type(self, ctype):
476 """Set the `default' content type.
477
Barry Warsawc1068642002-07-19 22:24:55 +0000478 ctype should be either "text/plain" or "message/rfc822", although this
479 is not enforced. The default content type is not stored in the
480 Content-Type: header.
Barry Warsawa0c8b9d2002-07-09 02:46:12 +0000481 """
Barry Warsawa0c8b9d2002-07-09 02:46:12 +0000482 self._default_type = ctype
483
Barry Warsawbeb59452001-09-26 05:41:51 +0000484 def _get_params_preserve(self, failobj, header):
485 # Like get_params() but preserves the quoting of values. BAW:
486 # should this be part of the public interface?
487 missing = []
488 value = self.get(header, missing)
489 if value is missing:
490 return failobj
491 params = []
492 for p in paramre.split(value):
493 try:
494 name, val = p.split('=', 1)
Barry Warsaw7aeac912002-07-18 23:09:09 +0000495 name = name.strip()
496 val = val.strip()
Barry Warsawbeb59452001-09-26 05:41:51 +0000497 except ValueError:
498 # Must have been a bare attribute
Barry Warsaw7aeac912002-07-18 23:09:09 +0000499 name = p.strip()
Barry Warsawbeb59452001-09-26 05:41:51 +0000500 val = ''
501 params.append((name, val))
Barry Warsaw908dc4b2002-06-29 05:56:15 +0000502 params = Utils.decode_params(params)
Barry Warsawbeb59452001-09-26 05:41:51 +0000503 return params
504
Barry Warsaw409a4c02002-04-10 21:01:31 +0000505 def get_params(self, failobj=None, header='content-type', unquote=1):
Barry Warsawba925802001-09-23 03:17:28 +0000506 """Return the message's Content-Type: parameters, as a list.
507
Barry Warsawbeb59452001-09-26 05:41:51 +0000508 The elements of the returned list are 2-tuples of key/value pairs, as
509 split on the `=' sign. The left hand side of the `=' is the key,
510 while the right hand side is the value. If there is no `=' sign in
511 the parameter the value is the empty string. The value is always
Barry Warsaw409a4c02002-04-10 21:01:31 +0000512 unquoted, unless unquote is set to a false value.
Barry Warsawbeb59452001-09-26 05:41:51 +0000513
Barry Warsawba925802001-09-23 03:17:28 +0000514 Optional failobj is the object to return if there is no Content-Type:
515 header. Optional header is the header to search instead of
Barry Warsaw409a4c02002-04-10 21:01:31 +0000516 Content-Type:.
Barry Warsawba925802001-09-23 03:17:28 +0000517 """
518 missing = []
Barry Warsawbeb59452001-09-26 05:41:51 +0000519 params = self._get_params_preserve(missing, header)
520 if params is missing:
Barry Warsawba925802001-09-23 03:17:28 +0000521 return failobj
Barry Warsaw409a4c02002-04-10 21:01:31 +0000522 if unquote:
Barry Warsaw908dc4b2002-06-29 05:56:15 +0000523 return [(k, _unquotevalue(v)) for k, v in params]
Barry Warsaw409a4c02002-04-10 21:01:31 +0000524 else:
525 return params
Barry Warsawba925802001-09-23 03:17:28 +0000526
Barry Warsaw409a4c02002-04-10 21:01:31 +0000527 def get_param(self, param, failobj=None, header='content-type', unquote=1):
Barry Warsawba925802001-09-23 03:17:28 +0000528 """Return the parameter value if found in the Content-Type: header.
529
530 Optional failobj is the object to return if there is no Content-Type:
531 header. Optional header is the header to search instead of
532 Content-Type:
Barry Warsawbeb59452001-09-26 05:41:51 +0000533
534 Parameter keys are always compared case insensitively. Values are
Barry Warsaw409a4c02002-04-10 21:01:31 +0000535 always unquoted, unless unquote is set to a false value.
Barry Warsawba925802001-09-23 03:17:28 +0000536 """
Barry Warsawbeb59452001-09-26 05:41:51 +0000537 if not self.has_key(header):
Barry Warsawba925802001-09-23 03:17:28 +0000538 return failobj
Barry Warsawbeb59452001-09-26 05:41:51 +0000539 for k, v in self._get_params_preserve(failobj, header):
540 if k.lower() == param.lower():
Barry Warsaw409a4c02002-04-10 21:01:31 +0000541 if unquote:
Barry Warsaw908dc4b2002-06-29 05:56:15 +0000542 return _unquotevalue(v)
Barry Warsaw409a4c02002-04-10 21:01:31 +0000543 else:
544 return v
Barry Warsawba925802001-09-23 03:17:28 +0000545 return failobj
546
Barry Warsaw3c255352002-09-06 03:55:04 +0000547 def set_param(self, param, value, header='Content-Type', requote=1,
548 charset=None, language=''):
Barry Warsaw409a4c02002-04-10 21:01:31 +0000549 """Set a parameter in the Content-Type: header.
550
551 If the parameter already exists in the header, its value will be
552 replaced with the new value.
553
554 If header is Content-Type: and has not yet been defined in this
555 message, it will be set to "text/plain" and the new parameter and
556 value will be appended, as per RFC 2045.
557
558 An alternate header can specified in the header argument, and
559 all parameters will be quoted as appropriate unless requote is
560 set to a false value.
Barry Warsaw3c255352002-09-06 03:55:04 +0000561
562 If charset is specified the parameter will be encoded according to RFC
563 2231. In this case language is optional.
Barry Warsaw409a4c02002-04-10 21:01:31 +0000564 """
Barry Warsaw3c255352002-09-06 03:55:04 +0000565 if not isinstance(value, TupleType) and charset:
566 value = (charset, language, value)
567
Barry Warsaw409a4c02002-04-10 21:01:31 +0000568 if not self.has_key(header) and header.lower() == 'content-type':
569 ctype = 'text/plain'
570 else:
571 ctype = self.get(header)
572 if not self.get_param(param, header=header):
573 if not ctype:
574 ctype = _formatparam(param, value, requote)
575 else:
576 ctype = SEMISPACE.join(
577 [ctype, _formatparam(param, value, requote)])
578 else:
579 ctype = ''
580 for old_param, old_value in self.get_params(header=header,
581 unquote=requote):
582 append_param = ''
583 if old_param.lower() == param.lower():
584 append_param = _formatparam(param, value, requote)
585 else:
586 append_param = _formatparam(old_param, old_value, requote)
587 if not ctype:
588 ctype = append_param
589 else:
590 ctype = SEMISPACE.join([ctype, append_param])
591 if ctype <> self.get(header):
592 del self[header]
593 self[header] = ctype
594
595 def del_param(self, param, header='content-type', requote=1):
596 """Remove the given parameter completely from the Content-Type header.
597
598 The header will be re-written in place without param or its value.
599 All values will be quoted as appropriate unless requote is set to a
600 false value.
601 """
602 if not self.has_key(header):
603 return
604 new_ctype = ''
605 for p, v in self.get_params(header, unquote=requote):
606 if p.lower() <> param.lower():
607 if not new_ctype:
608 new_ctype = _formatparam(p, v, requote)
609 else:
610 new_ctype = SEMISPACE.join([new_ctype,
611 _formatparam(p, v, requote)])
612 if new_ctype <> self.get(header):
613 del self[header]
614 self[header] = new_ctype
615
616 def set_type(self, type, header='Content-Type', requote=1):
617 """Set the main type and subtype for the Content-Type: header.
618
619 type must be a string in the form "maintype/subtype", otherwise a
620 ValueError is raised.
621
622 This method replaces the Content-Type: header, keeping all the
623 parameters in place. If requote is false, this leaves the existing
624 header's quoting as is. Otherwise, the parameters will be quoted (the
625 default).
626
627 An alternate header can be specified in the header argument. When the
628 Content-Type: header is set, we'll always also add a MIME-Version:
629 header.
630 """
631 # BAW: should we be strict?
632 if not type.count('/') == 1:
633 raise ValueError
634 # Set the Content-Type: you get a MIME-Version:
635 if header.lower() == 'content-type':
636 del self['mime-version']
637 self['MIME-Version'] = '1.0'
638 if not self.has_key(header):
639 self[header] = type
640 return
641 params = self.get_params(header, unquote=requote)
642 del self[header]
643 self[header] = type
644 # Skip the first param; it's the old type.
645 for p, v in params[1:]:
646 self.set_param(p, v, header, requote)
647
Barry Warsawba925802001-09-23 03:17:28 +0000648 def get_filename(self, failobj=None):
649 """Return the filename associated with the payload if present.
650
651 The filename is extracted from the Content-Disposition: header's
652 `filename' parameter, and it is unquoted.
653 """
654 missing = []
655 filename = self.get_param('filename', missing, 'content-disposition')
656 if filename is missing:
657 return failobj
Barry Warsaw908dc4b2002-06-29 05:56:15 +0000658 if isinstance(filename, TupleType):
659 # It's an RFC 2231 encoded parameter
660 newvalue = _unquotevalue(filename)
661 return unicode(newvalue[2], newvalue[0])
662 else:
663 newvalue = _unquotevalue(filename.strip())
664 return newvalue
Barry Warsawba925802001-09-23 03:17:28 +0000665
666 def get_boundary(self, failobj=None):
667 """Return the boundary associated with the payload if present.
668
669 The boundary is extracted from the Content-Type: header's `boundary'
670 parameter, and it is unquoted.
671 """
672 missing = []
673 boundary = self.get_param('boundary', missing)
674 if boundary is missing:
675 return failobj
Barry Warsaw908dc4b2002-06-29 05:56:15 +0000676 return _unquotevalue(boundary.strip())
Barry Warsawba925802001-09-23 03:17:28 +0000677
678 def set_boundary(self, boundary):
679 """Set the boundary parameter in Content-Type: to 'boundary'.
680
681 This is subtly different than deleting the Content-Type: header and
682 adding a new one with a new boundary parameter via add_header(). The
683 main difference is that using the set_boundary() method preserves the
684 order of the Content-Type: header in the original message.
685
686 HeaderParseError is raised if the message has no Content-Type: header.
687 """
Barry Warsawbeb59452001-09-26 05:41:51 +0000688 missing = []
689 params = self._get_params_preserve(missing, 'content-type')
690 if params is missing:
Barry Warsawba925802001-09-23 03:17:28 +0000691 # There was no Content-Type: header, and we don't know what type
692 # to set it to, so raise an exception.
693 raise Errors.HeaderParseError, 'No Content-Type: header found'
694 newparams = []
695 foundp = 0
Barry Warsawbeb59452001-09-26 05:41:51 +0000696 for pk, pv in params:
697 if pk.lower() == 'boundary':
698 newparams.append(('boundary', '"%s"' % boundary))
Barry Warsawba925802001-09-23 03:17:28 +0000699 foundp = 1
700 else:
Barry Warsawbeb59452001-09-26 05:41:51 +0000701 newparams.append((pk, pv))
Barry Warsawba925802001-09-23 03:17:28 +0000702 if not foundp:
703 # The original Content-Type: header had no boundary attribute.
704 # Tack one one the end. BAW: should we raise an exception
705 # instead???
Barry Warsawbeb59452001-09-26 05:41:51 +0000706 newparams.append(('boundary', '"%s"' % boundary))
Barry Warsawba925802001-09-23 03:17:28 +0000707 # Replace the existing Content-Type: header with the new value
708 newheaders = []
709 for h, v in self._headers:
710 if h.lower() == 'content-type':
Barry Warsawbeb59452001-09-26 05:41:51 +0000711 parts = []
712 for k, v in newparams:
713 if v == '':
714 parts.append(k)
715 else:
716 parts.append('%s=%s' % (k, v))
717 newheaders.append((h, SEMISPACE.join(parts)))
718
Barry Warsawba925802001-09-23 03:17:28 +0000719 else:
720 newheaders.append((h, v))
721 self._headers = newheaders
722
Barry Warsaw8c1aac22002-05-19 23:44:19 +0000723 try:
724 from email._compat22 import walk
725 except SyntaxError:
726 # Must be using Python 2.1
727 from email._compat21 import walk
Barry Warsawba925802001-09-23 03:17:28 +0000728
729 def get_charsets(self, failobj=None):
730 """Return a list containing the charset(s) used in this message.
Tim Peters527e64f2001-10-04 05:36:56 +0000731
Barry Warsawba925802001-09-23 03:17:28 +0000732 The returned list of items describes the Content-Type: headers'
733 charset parameter for this message and all the subparts in its
734 payload.
735
736 Each item will either be a string (the value of the charset parameter
737 in the Content-Type: header of that part) or the value of the
738 'failobj' parameter (defaults to None), if the part does not have a
739 main MIME type of "text", or the charset is not defined.
740
741 The list will contain one string for each part of the message, plus
742 one for the container message (i.e. self), so that a non-multipart
743 message will still return a list of length 1.
744 """
745 return [part.get_param('charset', failobj) for part in self.walk()]