home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2009 February / PCWFEB09.iso / Software / Linux / Kubuntu 8.10 / kubuntu-8.10-desktop-i386.iso / casper / filesystem.squashfs / usr / lib / python2.5 / email / message.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2008-10-29  |  27.6 KB  |  833 lines

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