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