blob: e368737efdfe62cb505ba8311baf46f0e38af488 [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'):
Barry Warsaw2cc1f6d2007-08-30 14:28:55 +0000204 payload += '\n'
205 in_file = BytesIO(payload.encode('raw-unicode-escape'))
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000206 out_file = BytesIO()
207 try:
208 uu.decode(in_file, out_file, quiet=True)
209 return out_file.getvalue()
210 except uu.Error:
211 # Some decoding problem
212 pass
213 # Is there a better way to do this? We can't use the bytes
214 # constructor.
Guido van Rossum9604e662007-08-30 03:46:43 +0000215 return bytes(payload, 'raw-unicode-escape')
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000216
217 def set_payload(self, payload, charset=None):
218 """Set the payload to the given value.
219
220 Optional charset sets the message's default character set. See
221 set_charset() for details.
222 """
223 self._payload = payload
224 if charset is not None:
225 self.set_charset(charset)
226
227 def set_charset(self, charset):
228 """Set the charset of the payload to a given character set.
229
230 charset can be a Charset instance, a string naming a character set, or
231 None. If it is a string it will be converted to a Charset instance.
232 If charset is None, the charset parameter will be removed from the
233 Content-Type field. Anything else will generate a TypeError.
234
235 The message will be assumed to be of type text/* encoded with
236 charset.input_charset. It will be converted to charset.output_charset
237 and encoded properly, if needed, when generating the plain text
238 representation of the message. MIME headers (MIME-Version,
239 Content-Type, Content-Transfer-Encoding) will be added as needed.
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000240 """
241 if charset is None:
242 self.del_param('charset')
243 self._charset = None
244 return
Guido van Rossum9604e662007-08-30 03:46:43 +0000245 if not isinstance(charset, Charset):
246 charset = Charset(charset)
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000247 self._charset = charset
248 if 'MIME-Version' not in self:
249 self.add_header('MIME-Version', '1.0')
250 if 'Content-Type' not in self:
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())
Guido van Rossum9604e662007-08-30 03:46:43 +0000255 if charset != charset.get_output_charset():
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000256 self._payload = charset.body_encode(self._payload)
257 if 'Content-Transfer-Encoding' not in self:
258 cte = charset.get_body_encoding()
259 try:
260 cte(self)
261 except TypeError:
262 self._payload = charset.body_encode(self._payload)
263 self.add_header('Content-Transfer-Encoding', cte)
264
265 def get_charset(self):
266 """Return the Charset instance associated with the message's payload.
267 """
268 return self._charset
269
270 #
271 # MAPPING INTERFACE (partial)
272 #
273 def __len__(self):
274 """Return the total number of headers, including duplicates."""
275 return len(self._headers)
276
277 def __getitem__(self, name):
278 """Get a header value.
279
280 Return None if the header is missing instead of raising an exception.
281
282 Note that if the header appeared multiple times, exactly which
283 occurrance gets returned is undefined. Use get_all() to get all
284 the values matching a header field name.
285 """
286 return self.get(name)
287
288 def __setitem__(self, name, val):
289 """Set the value of a header.
290
291 Note: this does not overwrite an existing header with the same field
292 name. Use __delitem__() first to delete any existing headers.
293 """
294 self._headers.append((name, val))
295
296 def __delitem__(self, name):
297 """Delete all occurrences of a header, if present.
298
299 Does not raise an exception if the header is missing.
300 """
301 name = name.lower()
302 newheaders = []
303 for k, v in self._headers:
304 if k.lower() != name:
305 newheaders.append((k, v))
306 self._headers = newheaders
307
308 def __contains__(self, name):
309 return name.lower() in [k.lower() for k, v in self._headers]
310
311 def __iter__(self):
312 for field, value in self._headers:
313 yield field
314
315 def __len__(self):
316 return len(self._headers)
317
318 def keys(self):
319 """Return a list of all the message's header field names.
320
321 These will be sorted in the order they appeared in the original
322 message, or were added to the message, and may contain duplicates.
323 Any fields deleted and re-inserted are always appended to the header
324 list.
325 """
326 return [k for k, v in self._headers]
327
328 def values(self):
329 """Return a list of all the message's header values.
330
331 These will be sorted in the order they appeared in the original
332 message, or were added to the message, and may contain duplicates.
333 Any fields deleted and re-inserted are always appended to the header
334 list.
335 """
336 return [v for k, v in self._headers]
337
338 def items(self):
339 """Get all the message's header fields and values.
340
341 These will be sorted in the order they appeared in the original
342 message, or were added to the message, and may contain duplicates.
343 Any fields deleted and re-inserted are always appended to the header
344 list.
345 """
346 return self._headers[:]
347
348 def get(self, name, failobj=None):
349 """Get a header value.
350
351 Like __getitem__() but return failobj instead of None when the field
352 is missing.
353 """
354 name = name.lower()
355 for k, v in self._headers:
356 if k.lower() == name:
357 return v
358 return failobj
359
360 #
361 # Additional useful stuff
362 #
363
364 def get_all(self, name, failobj=None):
365 """Return a list of all the values for the named field.
366
367 These will be sorted in the order they appeared in the original
368 message, and may contain duplicates. Any fields deleted and
369 re-inserted are always appended to the header list.
370
371 If no such fields exist, failobj is returned (defaults to None).
372 """
373 values = []
374 name = name.lower()
375 for k, v in self._headers:
376 if k.lower() == name:
377 values.append(v)
378 if not values:
379 return failobj
380 return values
381
382 def add_header(self, _name, _value, **_params):
383 """Extended header setting.
384
385 name is the header field to add. keyword arguments can be used to set
386 additional parameters for the header field, with underscores converted
387 to dashes. Normally the parameter will be added as key="value" unless
388 value is None, in which case only the key will be added.
389
390 Example:
391
392 msg.add_header('content-disposition', 'attachment', filename='bud.gif')
393 """
394 parts = []
395 for k, v in _params.items():
396 if v is None:
397 parts.append(k.replace('_', '-'))
398 else:
399 parts.append(_formatparam(k.replace('_', '-'), v))
400 if _value is not None:
401 parts.insert(0, _value)
402 self._headers.append((_name, SEMISPACE.join(parts)))
403
404 def replace_header(self, _name, _value):
405 """Replace a header.
406
407 Replace the first matching header found in the message, retaining
408 header order and case. If no matching header was found, a KeyError is
409 raised.
410 """
411 _name = _name.lower()
412 for i, (k, v) in zip(range(len(self._headers)), self._headers):
413 if k.lower() == _name:
414 self._headers[i] = (k, _value)
415 break
416 else:
417 raise KeyError(_name)
418
419 #
420 # Use these three methods instead of the three above.
421 #
422
423 def get_content_type(self):
424 """Return the message's content type.
425
426 The returned string is coerced to lower case of the form
427 `maintype/subtype'. If there was no Content-Type header in the
428 message, the default type as given by get_default_type() will be
429 returned. Since according to RFC 2045, messages always have a default
430 type this will always return a value.
431
432 RFC 2045 defines a message's default type to be text/plain unless it
433 appears inside a multipart/digest container, in which case it would be
434 message/rfc822.
435 """
436 missing = object()
437 value = self.get('content-type', missing)
438 if value is missing:
439 # This should have no parameters
440 return self.get_default_type()
441 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
446
447 def get_content_maintype(self):
448 """Return the message's main content type.
449
450 This is the `maintype' part of the string returned by
451 get_content_type().
452 """
453 ctype = self.get_content_type()
454 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().
461 """
462 ctype = self.get_content_type()
463 return ctype.split('/')[1]
464
465 def get_default_type(self):
466 """Return the `default' content type.
467
468 Most messages have a default content type of text/plain, except for
469 messages that are subparts of multipart/digest containers. Such
470 subparts have a default content type of message/rfc822.
471 """
472 return self._default_type
473
474 def set_default_type(self, ctype):
475 """Set the `default' content type.
476
477 ctype should be either "text/plain" or "message/rfc822", although this
478 is not enforced. The default content type is not stored in the
479 Content-Type header.
480 """
481 self._default_type = ctype
482
483 def _get_params_preserve(self, failobj, header):
484 # Like get_params() but preserves the quoting of values. BAW:
485 # should this be part of the public interface?
486 missing = object()
487 value = self.get(header, missing)
488 if value is missing:
489 return failobj
490 params = []
491 for p in _parseparam(';' + value):
492 try:
493 name, val = p.split('=', 1)
494 name = name.strip()
495 val = val.strip()
496 except ValueError:
497 # Must have been a bare attribute
498 name = p.strip()
499 val = ''
500 params.append((name, val))
501 params = utils.decode_params(params)
502 return params
503
504 def get_params(self, failobj=None, header='content-type', unquote=True):
505 """Return the message's Content-Type parameters, as a list.
506
507 The elements of the returned list are 2-tuples of key/value pairs, as
508 split on the `=' sign. The left hand side of the `=' is the key,
509 while the right hand side is the value. If there is no `=' sign in
510 the parameter the value is the empty string. The value is as
511 described in the get_param() method.
512
513 Optional failobj is the object to return if there is no Content-Type
514 header. Optional header is the header to search instead of
515 Content-Type. If unquote is True, the value is unquoted.
516 """
517 missing = object()
518 params = self._get_params_preserve(missing, header)
519 if params is missing:
520 return failobj
521 if unquote:
522 return [(k, _unquotevalue(v)) for k, v in params]
523 else:
524 return params
525
526 def get_param(self, param, failobj=None, header='content-type',
527 unquote=True):
528 """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, or the Content-Type header has no such parameter. Optional
532 header is the header to search instead of Content-Type.
533
534 Parameter keys are always compared case insensitively. The return
535 value can either be a string, or a 3-tuple if the parameter was RFC
536 2231 encoded. When it's a 3-tuple, the elements of the value are of
537 the form (CHARSET, LANGUAGE, VALUE). Note that both CHARSET and
538 LANGUAGE can be None, in which case you should consider VALUE to be
539 encoded in the us-ascii charset. You can usually ignore LANGUAGE.
540
541 Your application should be prepared to deal with 3-tuple return
542 values, and can convert the parameter to a Unicode string like so:
543
544 param = msg.get_param('foo')
545 if isinstance(param, tuple):
546 param = unicode(param[2], param[0] or 'us-ascii')
547
548 In any case, the parameter value (either the returned string, or the
549 VALUE item in the 3-tuple) is always unquoted, unless unquote is set
550 to False.
551 """
552 if header not in self:
553 return failobj
554 for k, v in self._get_params_preserve(failobj, header):
555 if k.lower() == param.lower():
556 if unquote:
557 return _unquotevalue(v)
558 else:
559 return v
560 return failobj
561
562 def set_param(self, param, value, header='Content-Type', requote=True,
563 charset=None, language=''):
564 """Set a parameter in the Content-Type header.
565
566 If the parameter already exists in the header, its value will be
567 replaced with the new value.
568
569 If header is Content-Type and has not yet been defined for this
570 message, it will be set to "text/plain" and the new parameter and
571 value will be appended as per RFC 2045.
572
573 An alternate header can specified in the header argument, and all
574 parameters will be quoted as necessary unless requote is False.
575
576 If charset is specified, the parameter will be encoded according to RFC
577 2231. Optional language specifies the RFC 2231 language, defaulting
578 to the empty string. Both charset and language should be strings.
579 """
580 if not isinstance(value, tuple) and charset:
581 value = (charset, language, value)
582
583 if header not in self and header.lower() == 'content-type':
584 ctype = 'text/plain'
585 else:
586 ctype = self.get(header)
587 if not self.get_param(param, header=header):
588 if not ctype:
589 ctype = _formatparam(param, value, requote)
590 else:
591 ctype = SEMISPACE.join(
592 [ctype, _formatparam(param, value, requote)])
593 else:
594 ctype = ''
595 for old_param, old_value in self.get_params(header=header,
596 unquote=requote):
597 append_param = ''
598 if old_param.lower() == param.lower():
599 append_param = _formatparam(param, value, requote)
600 else:
601 append_param = _formatparam(old_param, old_value, requote)
602 if not ctype:
603 ctype = append_param
604 else:
605 ctype = SEMISPACE.join([ctype, append_param])
606 if ctype != self.get(header):
607 del self[header]
608 self[header] = ctype
609
610 def del_param(self, param, header='content-type', requote=True):
611 """Remove the given parameter completely from the Content-Type header.
612
613 The header will be re-written in place without the parameter or its
614 value. All values will be quoted as necessary unless requote is
615 False. Optional header specifies an alternative to the Content-Type
616 header.
617 """
618 if header not in self:
619 return
620 new_ctype = ''
621 for p, v in self.get_params(header=header, unquote=requote):
622 if p.lower() != param.lower():
623 if not new_ctype:
624 new_ctype = _formatparam(p, v, requote)
625 else:
626 new_ctype = SEMISPACE.join([new_ctype,
627 _formatparam(p, v, requote)])
628 if new_ctype != self.get(header):
629 del self[header]
630 self[header] = new_ctype
631
632 def set_type(self, type, header='Content-Type', requote=True):
633 """Set the main type and subtype for the Content-Type header.
634
635 type must be a string in the form "maintype/subtype", otherwise a
636 ValueError is raised.
637
638 This method replaces the Content-Type header, keeping all the
639 parameters in place. If requote is False, this leaves the existing
640 header's quoting as is. Otherwise, the parameters will be quoted (the
641 default).
642
643 An alternative header can be specified in the header argument. When
644 the Content-Type header is set, we'll always also add a MIME-Version
645 header.
646 """
647 # BAW: should we be strict?
648 if not type.count('/') == 1:
649 raise ValueError
650 # Set the Content-Type, you get a MIME-Version
651 if header.lower() == 'content-type':
652 del self['mime-version']
653 self['MIME-Version'] = '1.0'
654 if header not in self:
655 self[header] = type
656 return
657 params = self.get_params(header=header, unquote=requote)
658 del self[header]
659 self[header] = type
660 # Skip the first param; it's the old type.
661 for p, v in params[1:]:
662 self.set_param(p, v, header, requote)
663
664 def get_filename(self, failobj=None):
665 """Return the filename associated with the payload if present.
666
667 The filename is extracted from the Content-Disposition header's
668 `filename' parameter, and it is unquoted. If that header is missing
669 the `filename' parameter, this method falls back to looking for the
670 `name' parameter.
671 """
672 missing = object()
673 filename = self.get_param('filename', missing, 'content-disposition')
674 if filename is missing:
675 filename = self.get_param('name', missing, 'content-disposition')
676 if filename is missing:
677 return failobj
678 return utils.collapse_rfc2231_value(filename).strip()
679
680 def get_boundary(self, failobj=None):
681 """Return the boundary associated with the payload if present.
682
683 The boundary is extracted from the Content-Type header's `boundary'
684 parameter, and it is unquoted.
685 """
686 missing = object()
687 boundary = self.get_param('boundary', missing)
688 if boundary is missing:
689 return failobj
690 # RFC 2046 says that boundaries may begin but not end in w/s
691 return utils.collapse_rfc2231_value(boundary).rstrip()
692
693 def set_boundary(self, boundary):
694 """Set the boundary parameter in Content-Type to 'boundary'.
695
696 This is subtly different than deleting the Content-Type header and
697 adding a new one with a new boundary parameter via add_header(). The
698 main difference is that using the set_boundary() method preserves the
699 order of the Content-Type header in the original message.
700
701 HeaderParseError is raised if the message has no Content-Type header.
702 """
703 missing = object()
704 params = self._get_params_preserve(missing, 'content-type')
705 if params is missing:
706 # There was no Content-Type header, and we don't know what type
707 # to set it to, so raise an exception.
708 raise errors.HeaderParseError('No Content-Type header found')
709 newparams = []
710 foundp = False
711 for pk, pv in params:
712 if pk.lower() == 'boundary':
713 newparams.append(('boundary', '"%s"' % boundary))
714 foundp = True
715 else:
716 newparams.append((pk, pv))
717 if not foundp:
718 # The original Content-Type header had no boundary attribute.
719 # Tack one on the end. BAW: should we raise an exception
720 # instead???
721 newparams.append(('boundary', '"%s"' % boundary))
722 # Replace the existing Content-Type header with the new value
723 newheaders = []
724 for h, v in self._headers:
725 if h.lower() == 'content-type':
726 parts = []
727 for k, v in newparams:
728 if v == '':
729 parts.append(k)
730 else:
731 parts.append('%s=%s' % (k, v))
732 newheaders.append((h, SEMISPACE.join(parts)))
733
734 else:
735 newheaders.append((h, v))
736 self._headers = newheaders
737
738 def get_content_charset(self, failobj=None):
739 """Return the charset parameter of the Content-Type header.
740
741 The returned string is always coerced to lower case. If there is no
742 Content-Type header, or if that header has no charset parameter,
743 failobj is returned.
744 """
745 missing = object()
746 charset = self.get_param('charset', missing)
747 if charset is missing:
748 return failobj
749 if isinstance(charset, tuple):
750 # RFC 2231 encoded, so decode it, and it better end up as ascii.
751 pcharset = charset[0] or 'us-ascii'
752 try:
753 # LookupError will be raised if the charset isn't known to
754 # Python. UnicodeError will be raised if the encoded text
755 # contains a character not in the charset.
Barry Warsaw2cc1f6d2007-08-30 14:28:55 +0000756 as_bytes = charset[2].encode('raw-unicode-escape')
757 charset = str(as_bytes, pcharset)
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000758 except (LookupError, UnicodeError):
759 charset = charset[2]
760 # charset characters must be in us-ascii range
761 try:
762 charset.encode('us-ascii')
763 except UnicodeError:
764 return failobj
765 # RFC 2046, $4.1.2 says charsets are not case sensitive
766 return charset.lower()
767
768 def get_charsets(self, failobj=None):
769 """Return a list containing the charset(s) used in this message.
770
771 The returned list of items describes the Content-Type headers'
772 charset parameter for this message and all the subparts in its
773 payload.
774
775 Each item will either be a string (the value of the charset parameter
776 in the Content-Type header of that part) or the value of the
777 'failobj' parameter (defaults to None), if the part does not have a
778 main MIME type of "text", or the charset is not defined.
779
780 The list will contain one string for each part of the message, plus
781 one for the container message (i.e. self), so that a non-multipart
782 message will still return a list of length 1.
783 """
784 return [part.get_content_charset(failobj) for part in self.walk()]
785
786 # I.e. def walk(self): ...
787 from email.iterators import walk