blob: 6a3e3ca10f8b349d1c22f29df64e93922d01acf9 [file] [log] [blame]
Barry Warsaw41f6ad62004-05-09 03:24:43 +00001# Copyright (C) 2001-2004 Python Software Foundation
Barry Warsawbb113862004-10-03 03:16:19 +00002# Author: Ben Gertzfield, Barry Warsaw
3# Contact: email-sig@python.org
Barry Warsaw4a442932003-12-30 16:52:25 +00004
Barry Warsaw409a4c02002-04-10 21:01:31 +00005import email.base64MIME
6import email.quopriMIME
Barry Warsaw41f6ad62004-05-09 03:24:43 +00007from email.Encoders import encode_7or8bit
Barry Warsaw5932c9b2002-09-28 17:47:56 +00008
Barry Warsaw409a4c02002-04-10 21:01:31 +00009
10
11# Flags for types of header encodings
Barry Warsawbb113862004-10-03 03:16:19 +000012QP = 1 # Quoted-Printable
13BASE64 = 2 # Base64
14SHORTEST = 3 # the shorter of QP and base64, but only for headers
Barry Warsaw409a4c02002-04-10 21:01:31 +000015
16# In "=?charset?q?hello_world?=", the =?, ?q?, and ?= add up to 7
Tim Peters8ac14952002-05-23 15:15:30 +000017MISC_LEN = 7
Barry Warsaw409a4c02002-04-10 21:01:31 +000018
19DEFAULT_CHARSET = 'us-ascii'
20
21
22
23# Defaults
24CHARSETS = {
25 # input header enc body enc output conv
Tim Peters8ac14952002-05-23 15:15:30 +000026 'iso-8859-1': (QP, QP, None),
Barry Warsaw409a4c02002-04-10 21:01:31 +000027 'iso-8859-2': (QP, QP, None),
Barry Warsaw4e68a1e2003-01-07 00:29:07 +000028 'iso-8859-3': (QP, QP, None),
29 'iso-8859-4': (QP, QP, None),
30 # iso-8859-5 is Cyrillic, and not especially used
31 # iso-8859-6 is Arabic, also not particularly used
32 # iso-8859-7 is Greek, QP will not make it readable
33 # iso-8859-8 is Hebrew, QP will not make it readable
34 'iso-8859-9': (QP, QP, None),
35 'iso-8859-10': (QP, QP, None),
36 # iso-8859-11 is Thai, QP will not make it readable
37 'iso-8859-13': (QP, QP, None),
38 'iso-8859-14': (QP, QP, None),
39 'iso-8859-15': (QP, QP, None),
40 'windows-1252':(QP, QP, None),
41 'viscii': (QP, QP, None),
Barry Warsaw409a4c02002-04-10 21:01:31 +000042 'us-ascii': (None, None, None),
43 'big5': (BASE64, BASE64, None),
Tim Peters8ac14952002-05-23 15:15:30 +000044 'gb2312': (BASE64, BASE64, None),
Barry Warsaw409a4c02002-04-10 21:01:31 +000045 'euc-jp': (BASE64, None, 'iso-2022-jp'),
46 'shift_jis': (BASE64, None, 'iso-2022-jp'),
47 'iso-2022-jp': (BASE64, None, None),
48 'koi8-r': (BASE64, BASE64, None),
Barry Warsaw5932c9b2002-09-28 17:47:56 +000049 'utf-8': (SHORTEST, BASE64, 'utf-8'),
Barry Warsaw7cd72402002-10-14 15:06:55 +000050 # We're making this one up to represent raw unencoded 8-bit
51 '8bit': (None, BASE64, 'utf-8'),
Barry Warsaw409a4c02002-04-10 21:01:31 +000052 }
53
54# Aliases for other commonly-used names for character sets. Map
55# them to the real ones used in email.
56ALIASES = {
57 'latin_1': 'iso-8859-1',
58 'latin-1': 'iso-8859-1',
Barry Warsaw4e68a1e2003-01-07 00:29:07 +000059 'latin_2': 'iso-8859-2',
60 'latin-2': 'iso-8859-2',
61 'latin_3': 'iso-8859-3',
62 'latin-3': 'iso-8859-3',
63 'latin_4': 'iso-8859-4',
64 'latin-4': 'iso-8859-4',
65 'latin_5': 'iso-8859-9',
66 'latin-5': 'iso-8859-9',
67 'latin_6': 'iso-8859-10',
68 'latin-6': 'iso-8859-10',
69 'latin_7': 'iso-8859-13',
70 'latin-7': 'iso-8859-13',
71 'latin_8': 'iso-8859-14',
72 'latin-8': 'iso-8859-14',
73 'latin_9': 'iso-8859-15',
74 'latin-9': 'iso-8859-15',
75 'cp949': 'ks_c_5601-1987',
76 'euc_jp': 'euc-jp',
77 'euc_kr': 'euc-kr',
Barry Warsaw409a4c02002-04-10 21:01:31 +000078 'ascii': 'us-ascii',
79 }
80
Barry Warsaw409a4c02002-04-10 21:01:31 +000081
Barry Warsaw4a442932003-12-30 16:52:25 +000082# Map charsets to their Unicode codec strings.
Barry Warsaw409a4c02002-04-10 21:01:31 +000083CODEC_MAP = {
Barry Warsaw4a442932003-12-30 16:52:25 +000084 'gb2312': 'eucgb2312_cn',
Barry Warsaw409a4c02002-04-10 21:01:31 +000085 'big5': 'big5_tw',
Barry Warsaw409a4c02002-04-10 21:01:31 +000086 # Hack: We don't want *any* conversion for stuff marked us-ascii, as all
87 # sorts of garbage might be sent to us in the guise of 7-bit us-ascii.
88 # Let that stuff pass through without conversion to/from Unicode.
89 'us-ascii': None,
90 }
91
92
93
94# Convenience functions for extending the above mappings
95def add_charset(charset, header_enc=None, body_enc=None, output_charset=None):
Barry Warsaw12272a22002-10-01 00:05:24 +000096 """Add character set properties to the global registry.
Barry Warsaw409a4c02002-04-10 21:01:31 +000097
98 charset is the input character set, and must be the canonical name of a
99 character set.
100
101 Optional header_enc and body_enc is either Charset.QP for
Barry Warsaw5932c9b2002-09-28 17:47:56 +0000102 quoted-printable, Charset.BASE64 for base64 encoding, Charset.SHORTEST for
103 the shortest of qp or base64 encoding, or None for no encoding. SHORTEST
104 is only valid for header_enc. It describes how message headers and
105 message bodies in the input charset are to be encoded. Default is no
106 encoding.
Barry Warsaw409a4c02002-04-10 21:01:31 +0000107
108 Optional output_charset is the character set that the output should be
109 in. Conversions will proceed from input charset, to Unicode, to the
110 output charset when the method Charset.convert() is called. The default
111 is to output in the same character set as the input.
112
113 Both input_charset and output_charset must have Unicode codec entries in
114 the module's charset-to-codec mapping; use add_codec(charset, codecname)
Barry Warsaw12272a22002-10-01 00:05:24 +0000115 to add codecs the module does not know about. See the codecs module's
Barry Warsaw409a4c02002-04-10 21:01:31 +0000116 documentation for more information.
117 """
Barry Warsaw5932c9b2002-09-28 17:47:56 +0000118 if body_enc == SHORTEST:
Barry Warsawbb113862004-10-03 03:16:19 +0000119 raise ValueError('SHORTEST not allowed for body_enc')
Barry Warsaw409a4c02002-04-10 21:01:31 +0000120 CHARSETS[charset] = (header_enc, body_enc, output_charset)
121
122
123def add_alias(alias, canonical):
124 """Add a character set alias.
125
126 alias is the alias name, e.g. latin-1
127 canonical is the character set's canonical name, e.g. iso-8859-1
128 """
129 ALIASES[alias] = canonical
130
131
132def add_codec(charset, codecname):
133 """Add a codec that map characters in the given charset to/from Unicode.
134
135 charset is the canonical name of a character set. codecname is the name
136 of a Python codec, as appropriate for the second argument to the unicode()
Barry Warsaw12272a22002-10-01 00:05:24 +0000137 built-in, or to the encode() method of a Unicode string.
Barry Warsaw409a4c02002-04-10 21:01:31 +0000138 """
139 CODEC_MAP[charset] = codecname
140
141
142
143class Charset:
144 """Map character sets to their email properties.
145
146 This class provides information about the requirements imposed on email
147 for a specific character set. It also provides convenience routines for
148 converting between character sets, given the availability of the
Barry Warsaw12272a22002-10-01 00:05:24 +0000149 applicable codecs. Given a character set, it will do its best to provide
150 information on how to use that character set in an email in an
151 RFC-compliant way.
Tim Peters8ac14952002-05-23 15:15:30 +0000152
Barry Warsaw409a4c02002-04-10 21:01:31 +0000153 Certain character sets must be encoded with quoted-printable or base64
154 when used in email headers or bodies. Certain character sets must be
155 converted outright, and are not allowed in email. Instances of this
156 module expose the following information about a character set:
157
158 input_charset: The initial character set specified. Common aliases
159 are converted to their `official' email names (e.g. latin_1
160 is converted to iso-8859-1). Defaults to 7-bit us-ascii.
161
162 header_encoding: If the character set must be encoded before it can be
163 used in an email header, this attribute will be set to
Barry Warsaw5932c9b2002-09-28 17:47:56 +0000164 Charset.QP (for quoted-printable), Charset.BASE64 (for
165 base64 encoding), or Charset.SHORTEST for the shortest of
166 QP or BASE64 encoding. Otherwise, it will be None.
Barry Warsaw409a4c02002-04-10 21:01:31 +0000167
168 body_encoding: Same as header_encoding, but describes the encoding for the
169 mail message's body, which indeed may be different than the
Barry Warsaw5932c9b2002-09-28 17:47:56 +0000170 header encoding. Charset.SHORTEST is not allowed for
171 body_encoding.
Barry Warsaw409a4c02002-04-10 21:01:31 +0000172
173 output_charset: Some character sets must be converted before the can be
174 used in email headers or bodies. If the input_charset is
175 one of them, this attribute will contain the name of the
176 charset output will be converted to. Otherwise, it will
177 be None.
178
179 input_codec: The name of the Python codec used to convert the
180 input_charset to Unicode. If no conversion codec is
181 necessary, this attribute will be None.
182
183 output_codec: The name of the Python codec used to convert Unicode
184 to the output_charset. If no conversion codec is necessary,
185 this attribute will have the same value as the input_codec.
186 """
187 def __init__(self, input_charset=DEFAULT_CHARSET):
Barry Warsaw14fc4642002-10-10 15:11:20 +0000188 # RFC 2046, $4.1.2 says charsets are not case sensitive
189 input_charset = input_charset.lower()
Barry Warsaw409a4c02002-04-10 21:01:31 +0000190 # Set the input charset after filtering through the aliases
191 self.input_charset = ALIASES.get(input_charset, input_charset)
192 # We can try to guess which encoding and conversion to use by the
193 # charset_map dictionary. Try that first, but let the user override
194 # it.
195 henc, benc, conv = CHARSETS.get(self.input_charset,
Barry Warsaw14fc4642002-10-10 15:11:20 +0000196 (SHORTEST, BASE64, None))
Barry Warsaw4a442932003-12-30 16:52:25 +0000197 if not conv:
198 conv = self.input_charset
Barry Warsaw409a4c02002-04-10 21:01:31 +0000199 # Set the attributes, allowing the arguments to override the default.
200 self.header_encoding = henc
201 self.body_encoding = benc
202 self.output_charset = ALIASES.get(conv, conv)
203 # Now set the codecs. If one isn't defined for input_charset,
204 # guess and try a Unicode codec with the same name as input_codec.
205 self.input_codec = CODEC_MAP.get(self.input_charset,
206 self.input_charset)
207 self.output_codec = CODEC_MAP.get(self.output_charset,
Barry Warsaw4a442932003-12-30 16:52:25 +0000208 self.output_charset)
Barry Warsaw409a4c02002-04-10 21:01:31 +0000209
210 def __str__(self):
211 return self.input_charset.lower()
212
Barry Warsaw784cf6a2003-03-06 05:16:29 +0000213 __repr__ = __str__
214
Barry Warsaw409a4c02002-04-10 21:01:31 +0000215 def __eq__(self, other):
216 return str(self) == str(other).lower()
217
218 def __ne__(self, other):
219 return not self.__eq__(other)
220
221 def get_body_encoding(self):
222 """Return the content-transfer-encoding used for body encoding.
223
224 This is either the string `quoted-printable' or `base64' depending on
225 the encoding used, or it is a function in which case you should call
226 the function with a single argument, the Message object being
Barry Warsaw12272a22002-10-01 00:05:24 +0000227 encoded. The function should then set the Content-Transfer-Encoding
Barry Warsaw409a4c02002-04-10 21:01:31 +0000228 header itself to whatever is appropriate.
229
230 Returns "quoted-printable" if self.body_encoding is QP.
231 Returns "base64" if self.body_encoding is BASE64.
232 Returns "7bit" otherwise.
233 """
Barry Warsaw5932c9b2002-09-28 17:47:56 +0000234 assert self.body_encoding <> SHORTEST
Barry Warsaw409a4c02002-04-10 21:01:31 +0000235 if self.body_encoding == QP:
236 return 'quoted-printable'
237 elif self.body_encoding == BASE64:
238 return 'base64'
239 else:
240 return encode_7or8bit
241
242 def convert(self, s):
243 """Convert a string from the input_codec to the output_codec."""
244 if self.input_codec <> self.output_codec:
245 return unicode(s, self.input_codec).encode(self.output_codec)
246 else:
247 return s
248
249 def to_splittable(self, s):
250 """Convert a possibly multibyte string to a safely splittable format.
251
252 Uses the input_codec to try and convert the string to Unicode, so it
Barry Warsaw12272a22002-10-01 00:05:24 +0000253 can be safely split on character boundaries (even for multibyte
Barry Warsaw409a4c02002-04-10 21:01:31 +0000254 characters).
255
Barry Warsaw12272a22002-10-01 00:05:24 +0000256 Returns the string as-is if it isn't known how to convert it to
Barry Warsaw409a4c02002-04-10 21:01:31 +0000257 Unicode with the input_charset.
258
259 Characters that could not be converted to Unicode will be replaced
260 with the Unicode replacement character U+FFFD.
261 """
Barry Warsaw41f6ad62004-05-09 03:24:43 +0000262 if isinstance(s, unicode) or self.input_codec is None:
Barry Warsaw409a4c02002-04-10 21:01:31 +0000263 return s
264 try:
265 return unicode(s, self.input_codec, 'replace')
266 except LookupError:
267 # Input codec not installed on system, so return the original
268 # string unchanged.
269 return s
270
Barry Warsaw5932c9b2002-09-28 17:47:56 +0000271 def from_splittable(self, ustr, to_output=True):
Barry Warsaw409a4c02002-04-10 21:01:31 +0000272 """Convert a splittable string back into an encoded string.
273
Barry Warsaw12272a22002-10-01 00:05:24 +0000274 Uses the proper codec to try and convert the string from Unicode back
275 into an encoded format. Return the string as-is if it is not Unicode,
276 or if it could not be converted from Unicode.
Barry Warsaw409a4c02002-04-10 21:01:31 +0000277
278 Characters that could not be converted from Unicode will be replaced
279 with an appropriate character (usually '?').
280
Barry Warsaw5932c9b2002-09-28 17:47:56 +0000281 If to_output is True (the default), uses output_codec to convert to an
282 encoded format. If to_output is False, uses input_codec.
Barry Warsaw409a4c02002-04-10 21:01:31 +0000283 """
284 if to_output:
285 codec = self.output_codec
286 else:
287 codec = self.input_codec
Barry Warsaw41f6ad62004-05-09 03:24:43 +0000288 if not isinstance(ustr, unicode) or codec is None:
Barry Warsaw409a4c02002-04-10 21:01:31 +0000289 return ustr
290 try:
291 return ustr.encode(codec, 'replace')
292 except LookupError:
293 # Output codec not installed
294 return ustr
295
296 def get_output_charset(self):
297 """Return the output character set.
298
Barry Warsaw12272a22002-10-01 00:05:24 +0000299 This is self.output_charset if that is not None, otherwise it is
Barry Warsaw409a4c02002-04-10 21:01:31 +0000300 self.input_charset.
301 """
302 return self.output_charset or self.input_charset
303
304 def encoded_header_len(self, s):
305 """Return the length of the encoded header string."""
306 cset = self.get_output_charset()
307 # The len(s) of a 7bit encoding is len(s)
Barry Warsaw5932c9b2002-09-28 17:47:56 +0000308 if self.header_encoding == BASE64:
Barry Warsaw409a4c02002-04-10 21:01:31 +0000309 return email.base64MIME.base64_len(s) + len(cset) + MISC_LEN
Barry Warsaw5932c9b2002-09-28 17:47:56 +0000310 elif self.header_encoding == QP:
Barry Warsaw409a4c02002-04-10 21:01:31 +0000311 return email.quopriMIME.header_quopri_len(s) + len(cset) + MISC_LEN
Barry Warsaw5932c9b2002-09-28 17:47:56 +0000312 elif self.header_encoding == SHORTEST:
313 lenb64 = email.base64MIME.base64_len(s)
314 lenqp = email.quopriMIME.header_quopri_len(s)
315 return min(lenb64, lenqp) + len(cset) + MISC_LEN
Barry Warsaw409a4c02002-04-10 21:01:31 +0000316 else:
317 return len(s)
318
Barry Warsaw5932c9b2002-09-28 17:47:56 +0000319 def header_encode(self, s, convert=False):
Barry Warsaw409a4c02002-04-10 21:01:31 +0000320 """Header-encode a string, optionally converting it to output_charset.
321
Barry Warsaw5932c9b2002-09-28 17:47:56 +0000322 If convert is True, the string will be converted from the input
Barry Warsaw409a4c02002-04-10 21:01:31 +0000323 charset to the output charset automatically. This is not useful for
324 multibyte character sets, which have line length issues (multibyte
325 characters must be split on a character, not a byte boundary); use the
326 high-level Header class to deal with these issues. convert defaults
Barry Warsaw5932c9b2002-09-28 17:47:56 +0000327 to False.
Barry Warsaw409a4c02002-04-10 21:01:31 +0000328
329 The type of encoding (base64 or quoted-printable) will be based on
330 self.header_encoding.
331 """
332 cset = self.get_output_charset()
333 if convert:
334 s = self.convert(s)
335 # 7bit/8bit encodings return the string unchanged (modulo conversions)
Barry Warsaw5932c9b2002-09-28 17:47:56 +0000336 if self.header_encoding == BASE64:
Barry Warsaw409a4c02002-04-10 21:01:31 +0000337 return email.base64MIME.header_encode(s, cset)
Barry Warsaw5932c9b2002-09-28 17:47:56 +0000338 elif self.header_encoding == QP:
Barry Warsaw784cf6a2003-03-06 05:16:29 +0000339 return email.quopriMIME.header_encode(s, cset, maxlinelen=None)
Barry Warsaw5932c9b2002-09-28 17:47:56 +0000340 elif self.header_encoding == SHORTEST:
341 lenb64 = email.base64MIME.base64_len(s)
342 lenqp = email.quopriMIME.header_quopri_len(s)
343 if lenb64 < lenqp:
344 return email.base64MIME.header_encode(s, cset)
345 else:
Barry Warsaw784cf6a2003-03-06 05:16:29 +0000346 return email.quopriMIME.header_encode(s, cset, maxlinelen=None)
Barry Warsaw409a4c02002-04-10 21:01:31 +0000347 else:
348 return s
349
Barry Warsaw5932c9b2002-09-28 17:47:56 +0000350 def body_encode(self, s, convert=True):
Barry Warsaw409a4c02002-04-10 21:01:31 +0000351 """Body-encode a string and convert it to output_charset.
352
Barry Warsaw5932c9b2002-09-28 17:47:56 +0000353 If convert is True (the default), the string will be converted from
Barry Warsaw409a4c02002-04-10 21:01:31 +0000354 the input charset to output charset automatically. Unlike
355 header_encode(), there are no issues with byte boundaries and
356 multibyte charsets in email bodies, so this is usually pretty safe.
357
358 The type of encoding (base64 or quoted-printable) will be based on
359 self.body_encoding.
360 """
361 if convert:
362 s = self.convert(s)
363 # 7bit/8bit encodings return the string unchanged (module conversions)
364 if self.body_encoding is BASE64:
365 return email.base64MIME.body_encode(s)
Barry Warsaw3d575892002-10-21 05:29:53 +0000366 elif self.body_encoding is QP:
Barry Warsaw409a4c02002-04-10 21:01:31 +0000367 return email.quopriMIME.body_encode(s)
368 else:
369 return s