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