blob: 50d66041c1e643eb6b8a9c6973f2479740f73e65 [file] [log] [blame]
Guido van Rossum8b3febe2007-08-30 01:15:14 +00001# Copyright (C) 2001-2007 Python Software Foundation
2# Author: Barry Warsaw
3# Contact: email-sig@python.org
4
5"""Basic message object for the email package object model."""
6
7__all__ = ['Message']
8
9import re
10import uu
11import binascii
12import warnings
13from io import BytesIO, StringIO
14
15# Intrapackage imports
Guido van Rossum8b3febe2007-08-30 01:15:14 +000016from email import utils
17from email import errors
Guido van Rossum9604e662007-08-30 03:46:43 +000018from email.charset import Charset
Guido van Rossum8b3febe2007-08-30 01:15:14 +000019
20SEMISPACE = '; '
21
22# Regular expression used to split header parameters. BAW: this may be too
23# simple. It isn't strictly RFC 2045 (section 5.1) compliant, but it catches
24# most headers found in the wild. We may eventually need a full fledged
25# parser eventually.
26paramre = re.compile(r'\s*;\s*')
27# Regular expression that matches `special' characters in parameters, the
28# existance of which force quoting of the parameter value.
29tspecials = re.compile(r'[ \(\)<>@,;:\\"/\[\]\?=]')
30
31
32
33# Helper functions
34def _formatparam(param, value=None, quote=True):
35 """Convenience function to format and return a key=value pair.
36
37 This will quote the value if needed or if quote is true.
38 """
39 if value is not None and len(value) > 0:
40 # A tuple is used for RFC 2231 encoded parameter values where items
41 # are (charset, language, value). charset is a string, not a Charset
42 # instance.
43 if isinstance(value, tuple):
44 # Encode as per RFC 2231
45 param += '*'
46 value = utils.encode_rfc2231(value[2], value[0], value[1])
47 # BAW: Please check this. I think that if quote is set it should
48 # force quoting even if not necessary.
49 if quote or tspecials.search(value):
50 return '%s="%s"' % (param, utils.quote(value))
51 else:
52 return '%s=%s' % (param, value)
53 else:
54 return param
55
56def _parseparam(s):
57 plist = []
58 while s[:1] == ';':
59 s = s[1:]
60 end = s.find(';')
61 while end > 0 and s.count('"', 0, end) % 2:
62 end = s.find(';', end + 1)
63 if end < 0:
64 end = len(s)
65 f = s[:end]
66 if '=' in f:
67 i = f.index('=')
68 f = f[:i].strip().lower() + '=' + f[i+1:].strip()
69 plist.append(f.strip())
70 s = s[end:]
71 return plist
72
73
74def _unquotevalue(value):
75 # This is different than utils.collapse_rfc2231_value() because it doesn't
76 # try to convert the value to a unicode. Message.get_param() and
77 # Message.get_params() are both currently defined to return the tuple in
78 # the face of RFC 2231 parameters.
79 if isinstance(value, tuple):
80 return value[0], value[1], utils.unquote(value[2])
81 else:
82 return utils.unquote(value)
83
84
85
86class Message:
87 """Basic message object.
88
89 A message object is defined as something that has a bunch of RFC 2822
90 headers and a payload. It may optionally have an envelope header
91 (a.k.a. Unix-From or From_ header). If the message is a container (i.e. a
92 multipart or a message/rfc822), then the payload is a list of Message
93 objects, otherwise it is a string.
94
95 Message objects implement part of the `mapping' interface, which assumes
96 there is exactly one occurrance of the header per message. Some headers
97 do in fact appear multiple times (e.g. Received) and for those headers,
98 you must use the explicit API to set or get all the headers. Not all of
99 the mapping methods are implemented.
100 """
101 def __init__(self):
102 self._headers = []
103 self._unixfrom = None
104 self._payload = None
105 self._charset = None
106 # Defaults for multipart messages
107 self.preamble = self.epilogue = None
108 self.defects = []
109 # Default content type
110 self._default_type = 'text/plain'
111
112 def __str__(self):
113 """Return the entire formatted message as a string.
114 This includes the headers, body, and envelope header.
115 """
116 return self.as_string()
117
118 def as_string(self, unixfrom=False, maxheaderlen=0):
119 """Return the entire formatted message as a string.
120 Optional `unixfrom' when True, means include the Unix From_ envelope
121 header.
122
123 This is a convenience method and may not generate the message exactly
124 as you intend because by default it mangles lines that begin with
125 "From ". For more flexibility, use the flatten() method of a
126 Generator instance.
127 """
128 from email.generator import Generator
129 fp = StringIO()
130 g = Generator(fp, mangle_from_=False, maxheaderlen=maxheaderlen)
131 g.flatten(self, unixfrom=unixfrom)
132 return fp.getvalue()
133
134 def is_multipart(self):
135 """Return True if the message consists of multiple parts."""
136 return isinstance(self._payload, list)
137
138 #
139 # Unix From_ line
140 #
141 def set_unixfrom(self, unixfrom):
142 self._unixfrom = unixfrom
143
144 def get_unixfrom(self):
145 return self._unixfrom
146
147 #
148 # Payload manipulation.
149 #
150 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
154 is called. If you want to set the payload to a scalar object, use
155 set_payload() instead.
156 """
157 if self._payload is None:
158 self._payload = [payload]
159 else:
160 self._payload.append(payload)
161
162 def get_payload(self, i=None, decode=False):
163 """Return a reference to the payload.
164
165 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.
168
169 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.
178
179 If the message is a multipart and the decode flag is True, then None
180 is returned.
181 """
182 if i is None:
183 payload = self._payload
184 elif not isinstance(self._payload, list):
185 raise TypeError('Expected list, got %s' % type(self._payload))
186 else:
187 payload = self._payload[i]
188 if not decode:
189 return payload
190 # Decoded payloads always return bytes. XXX split this part out into
191 # a new method called .get_decoded_payload().
192 if self.is_multipart():
193 return None
194 cte = self.get('content-transfer-encoding', '').lower()
195 if cte == 'quoted-printable':
196 return utils._qdecode(payload)
197 elif cte == 'base64':
198 try:
199 return utils._bdecode(payload)
200 except binascii.Error:
201 # Incorrect padding
202 pass
203 elif cte in ('x-uuencode', 'uuencode', 'uue', 'x-uue'):
Guido van Rossum9604e662007-08-30 03:46:43 +0000204 in_file = BytesIO(bytes(payload + '\n'))
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000205 out_file = BytesIO()
206 try:
207 uu.decode(in_file, out_file, quiet=True)
208 return out_file.getvalue()
209 except uu.Error:
210 # Some decoding problem
211 pass
212 # Is there a better way to do this? We can't use the bytes
213 # constructor.
Guido van Rossum9604e662007-08-30 03:46:43 +0000214 return bytes(payload, 'raw-unicode-escape')
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000215
216 def set_payload(self, payload, charset=None):
217 """Set the payload to the given value.
218
219 Optional charset sets the message's default character set. See
220 set_charset() for details.
221 """
222 self._payload = payload
223 if charset is not None:
224 self.set_charset(charset)
225
226 def set_charset(self, charset):
227 """Set the charset of the payload to a given character set.
228
229 charset can be a Charset instance, a string naming a character set, or
230 None. If it is a string it will be converted to a Charset instance.
231 If charset is None, the charset parameter will be removed from the
232 Content-Type field. Anything else will generate a TypeError.
233
234 The message will be assumed to be of type text/* encoded with
235 charset.input_charset. It will be converted to charset.output_charset
236 and encoded properly, if needed, when generating the plain text
237 representation of the message. MIME headers (MIME-Version,
238 Content-Type, Content-Transfer-Encoding) will be added as needed.
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000239 """
240 if charset is None:
241 self.del_param('charset')
242 self._charset = None
243 return
Guido van Rossum9604e662007-08-30 03:46:43 +0000244 if not isinstance(charset, Charset):
245 charset = Charset(charset)
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000246 self._charset = charset
247 if 'MIME-Version' not in self:
248 self.add_header('MIME-Version', '1.0')
249 if 'Content-Type' not in self:
250 self.add_header('Content-Type', 'text/plain',
251 charset=charset.get_output_charset())
252 else:
253 self.set_param('charset', charset.get_output_charset())
Guido van Rossum9604e662007-08-30 03:46:43 +0000254 if charset != charset.get_output_charset():
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000255 self._payload = charset.body_encode(self._payload)
256 if 'Content-Transfer-Encoding' not in self:
257 cte = charset.get_body_encoding()
258 try:
259 cte(self)
260 except TypeError:
261 self._payload = charset.body_encode(self._payload)
262 self.add_header('Content-Transfer-Encoding', cte)
263
264 def get_charset(self):
265 """Return the Charset instance associated with the message's payload.
266 """
267 return self._charset
268
269 #
270 # MAPPING INTERFACE (partial)
271 #
272 def __len__(self):
273 """Return the total number of headers, including duplicates."""
274 return len(self._headers)
275
276 def __getitem__(self, name):
277 """Get a header value.
278
279 Return None if the header is missing instead of raising an exception.
280
281 Note that if the header appeared multiple times, exactly which
282 occurrance gets returned is undefined. Use get_all() to get all
283 the values matching a header field name.
284 """
285 return self.get(name)
286
287 def __setitem__(self, name, val):
288 """Set the value of a header.
289
290 Note: this does not overwrite an existing header with the same field
291 name. Use __delitem__() first to delete any existing headers.
292 """
293 self._headers.append((name, val))
294
295 def __delitem__(self, name):
296 """Delete all occurrences of a header, if present.
297
298 Does not raise an exception if the header is missing.
299 """
300 name = name.lower()
301 newheaders = []
302 for k, v in self._headers:
303 if k.lower() != name:
304 newheaders.append((k, v))
305 self._headers = newheaders
306
307 def __contains__(self, name):
308 return name.lower() in [k.lower() for k, v in self._headers]
309
310 def __iter__(self):
311 for field, value in self._headers:
312 yield field
313
314 def __len__(self):
315 return len(self._headers)
316
317 def keys(self):
318 """Return a list of all the message's header field names.
319
320 These will be sorted in the order they appeared in the original
321 message, or were added to the message, and may contain duplicates.
322 Any fields deleted and re-inserted are always appended to the header
323 list.
324 """
325 return [k for k, v in self._headers]
326
327 def values(self):
328 """Return a list of all the message's header values.
329
330 These will be sorted in the order they appeared in the original
331 message, or were added to the message, and may contain duplicates.
332 Any fields deleted and re-inserted are always appended to the header
333 list.
334 """
335 return [v for k, v in self._headers]
336
337 def items(self):
338 """Get all the message's header fields and values.
339
340 These will be sorted in the order they appeared in the original
341 message, or were added to the message, and may contain duplicates.
342 Any fields deleted and re-inserted are always appended to the header
343 list.
344 """
345 return self._headers[:]
346
347 def get(self, name, failobj=None):
348 """Get a header value.
349
350 Like __getitem__() but return failobj instead of None when the field
351 is missing.
352 """
353 name = name.lower()
354 for k, v in self._headers:
355 if k.lower() == name:
356 return v
357 return failobj
358
359 #
360 # Additional useful stuff
361 #
362
363 def get_all(self, name, failobj=None):
364 """Return a list of all the values for the named field.
365
366 These will be sorted in the order they appeared in the original
367 message, and may contain duplicates. Any fields deleted and
368 re-inserted are always appended to the header list.
369
370 If no such fields exist, failobj is returned (defaults to None).
371 """
372 values = []
373 name = name.lower()
374 for k, v in self._headers:
375 if k.lower() == name:
376 values.append(v)
377 if not values:
378 return failobj
379 return values
380
381 def add_header(self, _name, _value, **_params):
382 """Extended header setting.
383
384 name is the header field to add. keyword arguments can be used to set
385 additional parameters for the header field, with underscores converted
386 to dashes. Normally the parameter will be added as key="value" unless
387 value is None, in which case only the key will be added.
388
389 Example:
390
391 msg.add_header('content-disposition', 'attachment', filename='bud.gif')
392 """
393 parts = []
394 for k, v in _params.items():
395 if v is None:
396 parts.append(k.replace('_', '-'))
397 else:
398 parts.append(_formatparam(k.replace('_', '-'), v))
399 if _value is not None:
400 parts.insert(0, _value)
401 self._headers.append((_name, SEMISPACE.join(parts)))
402
403 def replace_header(self, _name, _value):
404 """Replace a header.
405
406 Replace the first matching header found in the message, retaining
407 header order and case. If no matching header was found, a KeyError is
408 raised.
409 """
410 _name = _name.lower()
411 for i, (k, v) in zip(range(len(self._headers)), self._headers):
412 if k.lower() == _name:
413 self._headers[i] = (k, _value)
414 break
415 else:
416 raise KeyError(_name)
417
418 #
419 # Use these three methods instead of the three above.
420 #
421
422 def get_content_type(self):
423 """Return the message's content type.
424
425 The returned string is coerced to lower case of the form
426 `maintype/subtype'. If there was no Content-Type header in the
427 message, the default type as given by get_default_type() will be
428 returned. Since according to RFC 2045, messages always have a default
429 type this will always return a value.
430
431 RFC 2045 defines a message's default type to be text/plain unless it
432 appears inside a multipart/digest container, in which case it would be
433 message/rfc822.
434 """
435 missing = object()
436 value = self.get('content-type', missing)
437 if value is missing:
438 # This should have no parameters
439 return self.get_default_type()
440 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
445
446 def get_content_maintype(self):
447 """Return the message's main content type.
448
449 This is the `maintype' part of the string returned by
450 get_content_type().
451 """
452 ctype = self.get_content_type()
453 return ctype.split('/')[0]
454
455 def get_content_subtype(self):
456 """Returns the message's sub-content type.
457
458 This is the `subtype' part of the string returned by
459 get_content_type().
460 """
461 ctype = self.get_content_type()
462 return ctype.split('/')[1]
463
464 def get_default_type(self):
465 """Return the `default' content type.
466
467 Most messages have a default content type of text/plain, except for
468 messages that are subparts of multipart/digest containers. Such
469 subparts have a default content type of message/rfc822.
470 """
471 return self._default_type
472
473 def set_default_type(self, ctype):
474 """Set the `default' content type.
475
476 ctype should be either "text/plain" or "message/rfc822", although this
477 is not enforced. The default content type is not stored in the
478 Content-Type header.
479 """
480 self._default_type = ctype
481
482 def _get_params_preserve(self, failobj, header):
483 # Like get_params() but preserves the quoting of values. BAW:
484 # should this be part of the public interface?
485 missing = object()
486 value = self.get(header, missing)
487 if value is missing:
488 return failobj
489 params = []
490 for p in _parseparam(';' + value):
491 try:
492 name, val = p.split('=', 1)
493 name = name.strip()
494 val = val.strip()
495 except ValueError:
496 # Must have been a bare attribute
497 name = p.strip()
498 val = ''
499 params.append((name, val))
500 params = utils.decode_params(params)
501 return params
502
503 def get_params(self, failobj=None, header='content-type', unquote=True):
504 """Return the message's Content-Type parameters, as a list.
505
506 The elements of the returned list are 2-tuples of key/value pairs, as
507 split on the `=' sign. The left hand side of the `=' is the key,
508 while the right hand side is the value. If there is no `=' sign in
509 the parameter the value is the empty string. The value is as
510 described in the get_param() method.
511
512 Optional failobj is the object to return if there is no Content-Type
513 header. Optional header is the header to search instead of
514 Content-Type. If unquote is True, the value is unquoted.
515 """
516 missing = object()
517 params = self._get_params_preserve(missing, header)
518 if params is missing:
519 return failobj
520 if unquote:
521 return [(k, _unquotevalue(v)) for k, v in params]
522 else:
523 return params
524
525 def get_param(self, param, failobj=None, header='content-type',
526 unquote=True):
527 """Return the parameter value if found in the Content-Type header.
528
529 Optional failobj is the object to return if there is no Content-Type
530 header, or the Content-Type header has no such parameter. Optional
531 header is the header to search instead of Content-Type.
532
533 Parameter keys are always compared case insensitively. The return
534 value can either be a string, or a 3-tuple if the parameter was RFC
535 2231 encoded. When it's a 3-tuple, the elements of the value are of
536 the form (CHARSET, LANGUAGE, VALUE). Note that both CHARSET and
537 LANGUAGE can be None, in which case you should consider VALUE to be
538 encoded in the us-ascii charset. You can usually ignore LANGUAGE.
539
540 Your application should be prepared to deal with 3-tuple return
541 values, and can convert the parameter to a Unicode string like so:
542
543 param = msg.get_param('foo')
544 if isinstance(param, tuple):
545 param = unicode(param[2], param[0] or 'us-ascii')
546
547 In any case, the parameter value (either the returned string, or the
548 VALUE item in the 3-tuple) is always unquoted, unless unquote is set
549 to False.
550 """
551 if header not in self:
552 return failobj
553 for k, v in self._get_params_preserve(failobj, header):
554 if k.lower() == param.lower():
555 if unquote:
556 return _unquotevalue(v)
557 else:
558 return v
559 return failobj
560
561 def set_param(self, param, value, header='Content-Type', requote=True,
562 charset=None, language=''):
563 """Set a parameter in the Content-Type header.
564
565 If the parameter already exists in the header, its value will be
566 replaced with the new value.
567
568 If header is Content-Type and has not yet been defined for this
569 message, it will be set to "text/plain" and the new parameter and
570 value will be appended as per RFC 2045.
571
572 An alternate header can specified in the header argument, and all
573 parameters will be quoted as necessary unless requote is False.
574
575 If charset is specified, the parameter will be encoded according to RFC
576 2231. Optional language specifies the RFC 2231 language, defaulting
577 to the empty string. Both charset and language should be strings.
578 """
579 if not isinstance(value, tuple) and charset:
580 value = (charset, language, value)
581
582 if header not in self and header.lower() == 'content-type':
583 ctype = 'text/plain'
584 else:
585 ctype = self.get(header)
586 if not self.get_param(param, header=header):
587 if not ctype:
588 ctype = _formatparam(param, value, requote)
589 else:
590 ctype = SEMISPACE.join(
591 [ctype, _formatparam(param, value, requote)])
592 else:
593 ctype = ''
594 for old_param, old_value in self.get_params(header=header,
595 unquote=requote):
596 append_param = ''
597 if old_param.lower() == param.lower():
598 append_param = _formatparam(param, value, requote)
599 else:
600 append_param = _formatparam(old_param, old_value, requote)
601 if not ctype:
602 ctype = append_param
603 else:
604 ctype = SEMISPACE.join([ctype, append_param])
605 if ctype != self.get(header):
606 del self[header]
607 self[header] = ctype
608
609 def del_param(self, param, header='content-type', requote=True):
610 """Remove the given parameter completely from the Content-Type header.
611
612 The header will be re-written in place without the parameter or its
613 value. All values will be quoted as necessary unless requote is
614 False. Optional header specifies an alternative to the Content-Type
615 header.
616 """
617 if header not in self:
618 return
619 new_ctype = ''
620 for p, v in self.get_params(header=header, unquote=requote):
621 if p.lower() != param.lower():
622 if not new_ctype:
623 new_ctype = _formatparam(p, v, requote)
624 else:
625 new_ctype = SEMISPACE.join([new_ctype,
626 _formatparam(p, v, requote)])
627 if new_ctype != self.get(header):
628 del self[header]
629 self[header] = new_ctype
630
631 def set_type(self, type, header='Content-Type', requote=True):
632 """Set the main type and subtype for the Content-Type header.
633
634 type must be a string in the form "maintype/subtype", otherwise a
635 ValueError is raised.
636
637 This method replaces the Content-Type header, keeping all the
638 parameters in place. If requote is False, this leaves the existing
639 header's quoting as is. Otherwise, the parameters will be quoted (the
640 default).
641
642 An alternative header can be specified in the header argument. When
643 the Content-Type header is set, we'll always also add a MIME-Version
644 header.
645 """
646 # BAW: should we be strict?
647 if not type.count('/') == 1:
648 raise ValueError
649 # Set the Content-Type, you get a MIME-Version
650 if header.lower() == 'content-type':
651 del self['mime-version']
652 self['MIME-Version'] = '1.0'
653 if header not in self:
654 self[header] = type
655 return
656 params = self.get_params(header=header, unquote=requote)
657 del self[header]
658 self[header] = type
659 # Skip the first param; it's the old type.
660 for p, v in params[1:]:
661 self.set_param(p, v, header, requote)
662
663 def get_filename(self, failobj=None):
664 """Return the filename associated with the payload if present.
665
666 The filename is extracted from the Content-Disposition header's
667 `filename' parameter, and it is unquoted. If that header is missing
668 the `filename' parameter, this method falls back to looking for the
669 `name' parameter.
670 """
671 missing = object()
672 filename = self.get_param('filename', missing, 'content-disposition')
673 if filename is missing:
674 filename = self.get_param('name', missing, 'content-disposition')
675 if filename is missing:
676 return failobj
677 return utils.collapse_rfc2231_value(filename).strip()
678
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 = object()
686 boundary = self.get_param('boundary', missing)
687 if boundary is missing:
688 return failobj
689 # RFC 2046 says that boundaries may begin but not end in w/s
690 return utils.collapse_rfc2231_value(boundary).rstrip()
691
692 def set_boundary(self, boundary):
693 """Set the boundary parameter in Content-Type to 'boundary'.
694
695 This is subtly different than deleting the Content-Type header and
696 adding a new one with a new boundary parameter via add_header(). The
697 main difference is that using the set_boundary() method preserves the
698 order of the Content-Type header in the original message.
699
700 HeaderParseError is raised if the message has no Content-Type header.
701 """
702 missing = object()
703 params = self._get_params_preserve(missing, 'content-type')
704 if params is missing:
705 # There was no Content-Type header, and we don't know what type
706 # to set it to, so raise an exception.
707 raise errors.HeaderParseError('No Content-Type header found')
708 newparams = []
709 foundp = False
710 for pk, pv in params:
711 if pk.lower() == 'boundary':
712 newparams.append(('boundary', '"%s"' % boundary))
713 foundp = True
714 else:
715 newparams.append((pk, pv))
716 if not foundp:
717 # The original Content-Type header had no boundary attribute.
718 # Tack one on the end. BAW: should we raise an exception
719 # instead???
720 newparams.append(('boundary', '"%s"' % boundary))
721 # Replace the existing Content-Type header with the new value
722 newheaders = []
723 for h, v in self._headers:
724 if h.lower() == 'content-type':
725 parts = []
726 for k, v in newparams:
727 if v == '':
728 parts.append(k)
729 else:
730 parts.append('%s=%s' % (k, v))
731 newheaders.append((h, SEMISPACE.join(parts)))
732
733 else:
734 newheaders.append((h, v))
735 self._headers = newheaders
736
737 def get_content_charset(self, failobj=None):
738 """Return the charset parameter of the Content-Type header.
739
740 The returned string is always coerced to lower case. If there is no
741 Content-Type header, or if that header has no charset parameter,
742 failobj is returned.
743 """
744 missing = object()
745 charset = self.get_param('charset', missing)
746 if charset is missing:
747 return failobj
748 if isinstance(charset, tuple):
749 # RFC 2231 encoded, so decode it, and it better end up as ascii.
750 pcharset = charset[0] or 'us-ascii'
751 try:
752 # LookupError will be raised if the charset isn't known to
753 # Python. UnicodeError will be raised if the encoded text
754 # contains a character not in the charset.
Guido van Rossum9604e662007-08-30 03:46:43 +0000755 charset = str(bytes(charset[2]), pcharset)
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000756 except (LookupError, UnicodeError):
757 charset = charset[2]
758 # charset characters must be in us-ascii range
759 try:
760 charset.encode('us-ascii')
761 except UnicodeError:
762 return failobj
763 # RFC 2046, $4.1.2 says charsets are not case sensitive
764 return charset.lower()
765
766 def get_charsets(self, failobj=None):
767 """Return a list containing the charset(s) used in this message.
768
769 The returned list of items describes the Content-Type headers'
770 charset parameter for this message and all the subparts in its
771 payload.
772
773 Each item will either be a string (the value of the charset parameter
774 in the Content-Type header of that part) or the value of the
775 'failobj' parameter (defaults to None), if the part does not have a
776 main MIME type of "text", or the charset is not defined.
777
778 The list will contain one string for each part of the message, plus
779 one for the container message (i.e. self), so that a non-multipart
780 message will still return a list of length 1.
781 """
782 return [part.get_content_charset(failobj) for part in self.walk()]
783
784 # I.e. def walk(self): ...
785 from email.iterators import walk