blob: e4b9e9f947edbacb881c4032111b526a7ad118ba [file] [log] [blame]
Barry Warsaw409a4c02002-04-10 21:01:31 +00001# Copyright (C) 2001,2002 Python Software Foundation
Barry Warsaw5932c9b2002-09-28 17:47:56 +00002# Author: che@debian.org (Ben Gertzfield), barry@zope.com (Barry Warsaw)
Barry Warsaw409a4c02002-04-10 21:01:31 +00003
Barry Warsaw4a442932003-12-30 16:52:25 +00004# Python 2.3 doesn't come with any Asian codecs by default. Two packages are
5# currently available and supported as of this writing (30-Dec-2003):
6#
7# CJKCodecs
8# http://cjkpython.i18n.org
9# This package contains Chinese, Japanese, and Korean codecs
10
11# JapaneseCodecs
12# http://www.asahi-net.or.jp/~rd6t-kjym/python
13# Some Japanese users prefer this codec package
14
Barry Warsaw5932c9b2002-09-28 17:47:56 +000015from types import UnicodeType
Barry Warsaw409a4c02002-04-10 21:01:31 +000016from email.Encoders import encode_7or8bit
17import email.base64MIME
18import email.quopriMIME
19
Barry Warsaw5932c9b2002-09-28 17:47:56 +000020def _isunicode(s):
21 return isinstance(s, UnicodeType)
22
23# Python 2.2.1 and beyond has these symbols
24try:
25 True, False
26except NameError:
27 True = 1
28 False = 0
29
Barry Warsaw409a4c02002-04-10 21:01:31 +000030
31
32# Flags for types of header encodings
Barry Warsaw5932c9b2002-09-28 17:47:56 +000033QP = 1 # Quoted-Printable
34BASE64 = 2 # Base64
35SHORTEST = 3 # the shorter of QP and base64, but only for headers
Barry Warsaw409a4c02002-04-10 21:01:31 +000036
37# In "=?charset?q?hello_world?=", the =?, ?q?, and ?= add up to 7
Tim Peters8ac14952002-05-23 15:15:30 +000038MISC_LEN = 7
Barry Warsaw409a4c02002-04-10 21:01:31 +000039
40DEFAULT_CHARSET = 'us-ascii'
41
42
43
44# Defaults
45CHARSETS = {
46 # input header enc body enc output conv
Tim Peters8ac14952002-05-23 15:15:30 +000047 'iso-8859-1': (QP, QP, None),
Barry Warsaw409a4c02002-04-10 21:01:31 +000048 'iso-8859-2': (QP, QP, None),
Barry Warsaw4e68a1e2003-01-07 00:29:07 +000049 'iso-8859-3': (QP, QP, None),
50 'iso-8859-4': (QP, QP, None),
51 # iso-8859-5 is Cyrillic, and not especially used
52 # iso-8859-6 is Arabic, also not particularly used
53 # iso-8859-7 is Greek, QP will not make it readable
54 # iso-8859-8 is Hebrew, QP will not make it readable
55 'iso-8859-9': (QP, QP, None),
56 'iso-8859-10': (QP, QP, None),
57 # iso-8859-11 is Thai, QP will not make it readable
58 'iso-8859-13': (QP, QP, None),
59 'iso-8859-14': (QP, QP, None),
60 'iso-8859-15': (QP, QP, None),
61 'windows-1252':(QP, QP, None),
62 'viscii': (QP, QP, None),
Barry Warsaw409a4c02002-04-10 21:01:31 +000063 'us-ascii': (None, None, None),
64 'big5': (BASE64, BASE64, None),
Tim Peters8ac14952002-05-23 15:15:30 +000065 'gb2312': (BASE64, BASE64, None),
Barry Warsaw409a4c02002-04-10 21:01:31 +000066 'euc-jp': (BASE64, None, 'iso-2022-jp'),
67 'shift_jis': (BASE64, None, 'iso-2022-jp'),
68 'iso-2022-jp': (BASE64, None, None),
69 'koi8-r': (BASE64, BASE64, None),
Barry Warsaw5932c9b2002-09-28 17:47:56 +000070 'utf-8': (SHORTEST, BASE64, 'utf-8'),
Barry Warsaw7cd72402002-10-14 15:06:55 +000071 # We're making this one up to represent raw unencoded 8-bit
72 '8bit': (None, BASE64, 'utf-8'),
Barry Warsaw409a4c02002-04-10 21:01:31 +000073 }
74
75# Aliases for other commonly-used names for character sets. Map
76# them to the real ones used in email.
77ALIASES = {
78 'latin_1': 'iso-8859-1',
79 'latin-1': 'iso-8859-1',
Barry Warsaw4e68a1e2003-01-07 00:29:07 +000080 'latin_2': 'iso-8859-2',
81 'latin-2': 'iso-8859-2',
82 'latin_3': 'iso-8859-3',
83 'latin-3': 'iso-8859-3',
84 'latin_4': 'iso-8859-4',
85 'latin-4': 'iso-8859-4',
86 'latin_5': 'iso-8859-9',
87 'latin-5': 'iso-8859-9',
88 'latin_6': 'iso-8859-10',
89 'latin-6': 'iso-8859-10',
90 'latin_7': 'iso-8859-13',
91 'latin-7': 'iso-8859-13',
92 'latin_8': 'iso-8859-14',
93 'latin-8': 'iso-8859-14',
94 'latin_9': 'iso-8859-15',
95 'latin-9': 'iso-8859-15',
96 'cp949': 'ks_c_5601-1987',
97 'euc_jp': 'euc-jp',
98 'euc_kr': 'euc-kr',
Barry Warsaw409a4c02002-04-10 21:01:31 +000099 'ascii': 'us-ascii',
100 }
101
Barry Warsaw409a4c02002-04-10 21:01:31 +0000102
Barry Warsaw4a442932003-12-30 16:52:25 +0000103# Map charsets to their Unicode codec strings.
Barry Warsaw409a4c02002-04-10 21:01:31 +0000104CODEC_MAP = {
Barry Warsaw4a442932003-12-30 16:52:25 +0000105 'gb2312': 'eucgb2312_cn',
Barry Warsaw409a4c02002-04-10 21:01:31 +0000106 'big5': 'big5_tw',
Barry Warsaw409a4c02002-04-10 21:01:31 +0000107 # Hack: We don't want *any* conversion for stuff marked us-ascii, as all
108 # sorts of garbage might be sent to us in the guise of 7-bit us-ascii.
109 # Let that stuff pass through without conversion to/from Unicode.
110 'us-ascii': None,
111 }
112
113
114
115# Convenience functions for extending the above mappings
116def add_charset(charset, header_enc=None, body_enc=None, output_charset=None):
Barry Warsaw12272a22002-10-01 00:05:24 +0000117 """Add character set properties to the global registry.
Barry Warsaw409a4c02002-04-10 21:01:31 +0000118
119 charset is the input character set, and must be the canonical name of a
120 character set.
121
122 Optional header_enc and body_enc is either Charset.QP for
Barry Warsaw5932c9b2002-09-28 17:47:56 +0000123 quoted-printable, Charset.BASE64 for base64 encoding, Charset.SHORTEST for
124 the shortest of qp or base64 encoding, or None for no encoding. SHORTEST
125 is only valid for header_enc. It describes how message headers and
126 message bodies in the input charset are to be encoded. Default is no
127 encoding.
Barry Warsaw409a4c02002-04-10 21:01:31 +0000128
129 Optional output_charset is the character set that the output should be
130 in. Conversions will proceed from input charset, to Unicode, to the
131 output charset when the method Charset.convert() is called. The default
132 is to output in the same character set as the input.
133
134 Both input_charset and output_charset must have Unicode codec entries in
135 the module's charset-to-codec mapping; use add_codec(charset, codecname)
Barry Warsaw12272a22002-10-01 00:05:24 +0000136 to add codecs the module does not know about. See the codecs module's
Barry Warsaw409a4c02002-04-10 21:01:31 +0000137 documentation for more information.
138 """
Barry Warsaw5932c9b2002-09-28 17:47:56 +0000139 if body_enc == SHORTEST:
140 raise ValueError, 'SHORTEST not allowed for body_enc'
Barry Warsaw409a4c02002-04-10 21:01:31 +0000141 CHARSETS[charset] = (header_enc, body_enc, output_charset)
142
143
144def add_alias(alias, canonical):
145 """Add a character set alias.
146
147 alias is the alias name, e.g. latin-1
148 canonical is the character set's canonical name, e.g. iso-8859-1
149 """
150 ALIASES[alias] = canonical
151
152
153def add_codec(charset, codecname):
154 """Add a codec that map characters in the given charset to/from Unicode.
155
156 charset is the canonical name of a character set. codecname is the name
157 of a Python codec, as appropriate for the second argument to the unicode()
Barry Warsaw12272a22002-10-01 00:05:24 +0000158 built-in, or to the encode() method of a Unicode string.
Barry Warsaw409a4c02002-04-10 21:01:31 +0000159 """
160 CODEC_MAP[charset] = codecname
161
162
163
164class Charset:
165 """Map character sets to their email properties.
166
167 This class provides information about the requirements imposed on email
168 for a specific character set. It also provides convenience routines for
169 converting between character sets, given the availability of the
Barry Warsaw12272a22002-10-01 00:05:24 +0000170 applicable codecs. Given a character set, it will do its best to provide
171 information on how to use that character set in an email in an
172 RFC-compliant way.
Tim Peters8ac14952002-05-23 15:15:30 +0000173
Barry Warsaw409a4c02002-04-10 21:01:31 +0000174 Certain character sets must be encoded with quoted-printable or base64
175 when used in email headers or bodies. Certain character sets must be
176 converted outright, and are not allowed in email. Instances of this
177 module expose the following information about a character set:
178
179 input_charset: The initial character set specified. Common aliases
180 are converted to their `official' email names (e.g. latin_1
181 is converted to iso-8859-1). Defaults to 7-bit us-ascii.
182
183 header_encoding: If the character set must be encoded before it can be
184 used in an email header, this attribute will be set to
Barry Warsaw5932c9b2002-09-28 17:47:56 +0000185 Charset.QP (for quoted-printable), Charset.BASE64 (for
186 base64 encoding), or Charset.SHORTEST for the shortest of
187 QP or BASE64 encoding. Otherwise, it will be None.
Barry Warsaw409a4c02002-04-10 21:01:31 +0000188
189 body_encoding: Same as header_encoding, but describes the encoding for the
190 mail message's body, which indeed may be different than the
Barry Warsaw5932c9b2002-09-28 17:47:56 +0000191 header encoding. Charset.SHORTEST is not allowed for
192 body_encoding.
Barry Warsaw409a4c02002-04-10 21:01:31 +0000193
194 output_charset: Some character sets must be converted before the can be
195 used in email headers or bodies. If the input_charset is
196 one of them, this attribute will contain the name of the
197 charset output will be converted to. Otherwise, it will
198 be None.
199
200 input_codec: The name of the Python codec used to convert the
201 input_charset to Unicode. If no conversion codec is
202 necessary, this attribute will be None.
203
204 output_codec: The name of the Python codec used to convert Unicode
205 to the output_charset. If no conversion codec is necessary,
206 this attribute will have the same value as the input_codec.
207 """
208 def __init__(self, input_charset=DEFAULT_CHARSET):
Barry Warsaw14fc4642002-10-10 15:11:20 +0000209 # RFC 2046, $4.1.2 says charsets are not case sensitive
210 input_charset = input_charset.lower()
Barry Warsaw409a4c02002-04-10 21:01:31 +0000211 # Set the input charset after filtering through the aliases
212 self.input_charset = ALIASES.get(input_charset, input_charset)
213 # We can try to guess which encoding and conversion to use by the
214 # charset_map dictionary. Try that first, but let the user override
215 # it.
216 henc, benc, conv = CHARSETS.get(self.input_charset,
Barry Warsaw14fc4642002-10-10 15:11:20 +0000217 (SHORTEST, BASE64, None))
Barry Warsaw4a442932003-12-30 16:52:25 +0000218 if not conv:
219 conv = self.input_charset
Barry Warsaw409a4c02002-04-10 21:01:31 +0000220 # Set the attributes, allowing the arguments to override the default.
221 self.header_encoding = henc
222 self.body_encoding = benc
223 self.output_charset = ALIASES.get(conv, conv)
224 # Now set the codecs. If one isn't defined for input_charset,
225 # guess and try a Unicode codec with the same name as input_codec.
226 self.input_codec = CODEC_MAP.get(self.input_charset,
227 self.input_charset)
228 self.output_codec = CODEC_MAP.get(self.output_charset,
Barry Warsaw4a442932003-12-30 16:52:25 +0000229 self.output_charset)
Barry Warsaw409a4c02002-04-10 21:01:31 +0000230
231 def __str__(self):
232 return self.input_charset.lower()
233
Barry Warsaw784cf6a2003-03-06 05:16:29 +0000234 __repr__ = __str__
235
Barry Warsaw409a4c02002-04-10 21:01:31 +0000236 def __eq__(self, other):
237 return str(self) == str(other).lower()
238
239 def __ne__(self, other):
240 return not self.__eq__(other)
241
242 def get_body_encoding(self):
243 """Return the content-transfer-encoding used for body encoding.
244
245 This is either the string `quoted-printable' or `base64' depending on
246 the encoding used, or it is a function in which case you should call
247 the function with a single argument, the Message object being
Barry Warsaw12272a22002-10-01 00:05:24 +0000248 encoded. The function should then set the Content-Transfer-Encoding
Barry Warsaw409a4c02002-04-10 21:01:31 +0000249 header itself to whatever is appropriate.
250
251 Returns "quoted-printable" if self.body_encoding is QP.
252 Returns "base64" if self.body_encoding is BASE64.
253 Returns "7bit" otherwise.
254 """
Barry Warsaw5932c9b2002-09-28 17:47:56 +0000255 assert self.body_encoding <> SHORTEST
Barry Warsaw409a4c02002-04-10 21:01:31 +0000256 if self.body_encoding == QP:
257 return 'quoted-printable'
258 elif self.body_encoding == BASE64:
259 return 'base64'
260 else:
261 return encode_7or8bit
262
263 def convert(self, s):
264 """Convert a string from the input_codec to the output_codec."""
265 if self.input_codec <> self.output_codec:
266 return unicode(s, self.input_codec).encode(self.output_codec)
267 else:
268 return s
269
270 def to_splittable(self, s):
271 """Convert a possibly multibyte string to a safely splittable format.
272
273 Uses the input_codec to try and convert the string to Unicode, so it
Barry Warsaw12272a22002-10-01 00:05:24 +0000274 can be safely split on character boundaries (even for multibyte
Barry Warsaw409a4c02002-04-10 21:01:31 +0000275 characters).
276
Barry Warsaw12272a22002-10-01 00:05:24 +0000277 Returns the string as-is if it isn't known how to convert it to
Barry Warsaw409a4c02002-04-10 21:01:31 +0000278 Unicode with the input_charset.
279
280 Characters that could not be converted to Unicode will be replaced
281 with the Unicode replacement character U+FFFD.
282 """
Barry Warsaw5932c9b2002-09-28 17:47:56 +0000283 if _isunicode(s) or self.input_codec is None:
Barry Warsaw409a4c02002-04-10 21:01:31 +0000284 return s
285 try:
286 return unicode(s, self.input_codec, 'replace')
287 except LookupError:
288 # Input codec not installed on system, so return the original
289 # string unchanged.
290 return s
291
Barry Warsaw5932c9b2002-09-28 17:47:56 +0000292 def from_splittable(self, ustr, to_output=True):
Barry Warsaw409a4c02002-04-10 21:01:31 +0000293 """Convert a splittable string back into an encoded string.
294
Barry Warsaw12272a22002-10-01 00:05:24 +0000295 Uses the proper codec to try and convert the string from Unicode back
296 into an encoded format. Return the string as-is if it is not Unicode,
297 or if it could not be converted from Unicode.
Barry Warsaw409a4c02002-04-10 21:01:31 +0000298
299 Characters that could not be converted from Unicode will be replaced
300 with an appropriate character (usually '?').
301
Barry Warsaw5932c9b2002-09-28 17:47:56 +0000302 If to_output is True (the default), uses output_codec to convert to an
303 encoded format. If to_output is False, uses input_codec.
Barry Warsaw409a4c02002-04-10 21:01:31 +0000304 """
305 if to_output:
306 codec = self.output_codec
307 else:
308 codec = self.input_codec
Barry Warsaw5932c9b2002-09-28 17:47:56 +0000309 if not _isunicode(ustr) or codec is None:
Barry Warsaw409a4c02002-04-10 21:01:31 +0000310 return ustr
311 try:
312 return ustr.encode(codec, 'replace')
313 except LookupError:
314 # Output codec not installed
315 return ustr
316
317 def get_output_charset(self):
318 """Return the output character set.
319
Barry Warsaw12272a22002-10-01 00:05:24 +0000320 This is self.output_charset if that is not None, otherwise it is
Barry Warsaw409a4c02002-04-10 21:01:31 +0000321 self.input_charset.
322 """
323 return self.output_charset or self.input_charset
324
325 def encoded_header_len(self, s):
326 """Return the length of the encoded header string."""
327 cset = self.get_output_charset()
328 # The len(s) of a 7bit encoding is len(s)
Barry Warsaw5932c9b2002-09-28 17:47:56 +0000329 if self.header_encoding == BASE64:
Barry Warsaw409a4c02002-04-10 21:01:31 +0000330 return email.base64MIME.base64_len(s) + len(cset) + MISC_LEN
Barry Warsaw5932c9b2002-09-28 17:47:56 +0000331 elif self.header_encoding == QP:
Barry Warsaw409a4c02002-04-10 21:01:31 +0000332 return email.quopriMIME.header_quopri_len(s) + len(cset) + MISC_LEN
Barry Warsaw5932c9b2002-09-28 17:47:56 +0000333 elif self.header_encoding == SHORTEST:
334 lenb64 = email.base64MIME.base64_len(s)
335 lenqp = email.quopriMIME.header_quopri_len(s)
336 return min(lenb64, lenqp) + len(cset) + MISC_LEN
Barry Warsaw409a4c02002-04-10 21:01:31 +0000337 else:
338 return len(s)
339
Barry Warsaw5932c9b2002-09-28 17:47:56 +0000340 def header_encode(self, s, convert=False):
Barry Warsaw409a4c02002-04-10 21:01:31 +0000341 """Header-encode a string, optionally converting it to output_charset.
342
Barry Warsaw5932c9b2002-09-28 17:47:56 +0000343 If convert is True, the string will be converted from the input
Barry Warsaw409a4c02002-04-10 21:01:31 +0000344 charset to the output charset automatically. This is not useful for
345 multibyte character sets, which have line length issues (multibyte
346 characters must be split on a character, not a byte boundary); use the
347 high-level Header class to deal with these issues. convert defaults
Barry Warsaw5932c9b2002-09-28 17:47:56 +0000348 to False.
Barry Warsaw409a4c02002-04-10 21:01:31 +0000349
350 The type of encoding (base64 or quoted-printable) will be based on
351 self.header_encoding.
352 """
353 cset = self.get_output_charset()
354 if convert:
355 s = self.convert(s)
356 # 7bit/8bit encodings return the string unchanged (modulo conversions)
Barry Warsaw5932c9b2002-09-28 17:47:56 +0000357 if self.header_encoding == BASE64:
Barry Warsaw409a4c02002-04-10 21:01:31 +0000358 return email.base64MIME.header_encode(s, cset)
Barry Warsaw5932c9b2002-09-28 17:47:56 +0000359 elif self.header_encoding == QP:
Barry Warsaw784cf6a2003-03-06 05:16:29 +0000360 return email.quopriMIME.header_encode(s, cset, maxlinelen=None)
Barry Warsaw5932c9b2002-09-28 17:47:56 +0000361 elif self.header_encoding == SHORTEST:
362 lenb64 = email.base64MIME.base64_len(s)
363 lenqp = email.quopriMIME.header_quopri_len(s)
364 if lenb64 < lenqp:
365 return email.base64MIME.header_encode(s, cset)
366 else:
Barry Warsaw784cf6a2003-03-06 05:16:29 +0000367 return email.quopriMIME.header_encode(s, cset, maxlinelen=None)
Barry Warsaw409a4c02002-04-10 21:01:31 +0000368 else:
369 return s
370
Barry Warsaw5932c9b2002-09-28 17:47:56 +0000371 def body_encode(self, s, convert=True):
Barry Warsaw409a4c02002-04-10 21:01:31 +0000372 """Body-encode a string and convert it to output_charset.
373
Barry Warsaw5932c9b2002-09-28 17:47:56 +0000374 If convert is True (the default), the string will be converted from
Barry Warsaw409a4c02002-04-10 21:01:31 +0000375 the input charset to output charset automatically. Unlike
376 header_encode(), there are no issues with byte boundaries and
377 multibyte charsets in email bodies, so this is usually pretty safe.
378
379 The type of encoding (base64 or quoted-printable) will be based on
380 self.body_encoding.
381 """
382 if convert:
383 s = self.convert(s)
384 # 7bit/8bit encodings return the string unchanged (module conversions)
385 if self.body_encoding is BASE64:
386 return email.base64MIME.body_encode(s)
Barry Warsaw3d575892002-10-21 05:29:53 +0000387 elif self.body_encoding is QP:
Barry Warsaw409a4c02002-04-10 21:01:31 +0000388 return email.quopriMIME.body_encode(s)
389 else:
390 return s