blob: 4a7ef695766aafd54ab09bbbf51fb3f3086d5816 [file] [log] [blame]
Barry Warsaw409a4c02002-04-10 21:01:31 +00001# Copyright (C) 2001,2002 Python Software Foundation
2# Author: che@debian.org (Ben Gertzfield)
3
Guido van Rossum1a7ac352002-05-28 18:49:03 +00004try:
5 unicode
6except NameError:
7 def _is_unicode(x):
8 return 1==0
9else:
10 def _is_unicode(x):
11 return isinstance(x, unicode)
12
Barry Warsaw409a4c02002-04-10 21:01:31 +000013from email.Encoders import encode_7or8bit
14import email.base64MIME
15import email.quopriMIME
16
17
18
19# Flags for types of header encodings
20QP = 1 # Quoted-Printable
21BASE64 = 2 # Base64
22
23# In "=?charset?q?hello_world?=", the =?, ?q?, and ?= add up to 7
Tim Peters8ac14952002-05-23 15:15:30 +000024MISC_LEN = 7
Barry Warsaw409a4c02002-04-10 21:01:31 +000025
26DEFAULT_CHARSET = 'us-ascii'
27
28
29
30# Defaults
31CHARSETS = {
32 # input header enc body enc output conv
Tim Peters8ac14952002-05-23 15:15:30 +000033 'iso-8859-1': (QP, QP, None),
Barry Warsaw409a4c02002-04-10 21:01:31 +000034 'iso-8859-2': (QP, QP, None),
35 'us-ascii': (None, None, None),
36 'big5': (BASE64, BASE64, None),
Tim Peters8ac14952002-05-23 15:15:30 +000037 'gb2312': (BASE64, BASE64, None),
Barry Warsaw409a4c02002-04-10 21:01:31 +000038 'euc-jp': (BASE64, None, 'iso-2022-jp'),
39 'shift_jis': (BASE64, None, 'iso-2022-jp'),
40 'iso-2022-jp': (BASE64, None, None),
41 'koi8-r': (BASE64, BASE64, None),
42 'utf-8': (BASE64, BASE64, 'utf-8'),
43 }
44
45# Aliases for other commonly-used names for character sets. Map
46# them to the real ones used in email.
47ALIASES = {
48 'latin_1': 'iso-8859-1',
49 'latin-1': 'iso-8859-1',
50 'ascii': 'us-ascii',
51 }
52
53# Map charsets to their Unicode codec strings. Note that the Japanese
54# examples included below do not (yet) come with Python! They are available
55# from http://pseudo.grad.sccs.chukyo-u.ac.jp/~kajiyama/python/
56
57# The Chinese and Korean codecs are available from SourceForge:
58#
59# http://sourceforge.net/projects/python-codecs/
60#
61# although you'll need to check them out of cvs since they haven't been file
62# released yet. You might also try to use
63#
64# http://www.freshports.org/port-description.php3?port=6702
65#
66# if you can get logged in. AFAICT, both the Chinese and Korean codecs are
67# fairly experimental at this point.
68CODEC_MAP = {
69 'euc-jp': 'japanese.euc-jp',
70 'iso-2022-jp': 'japanese.iso-2022-jp',
71 'shift_jis': 'japanese.shift_jis',
72 'gb2132': 'eucgb2312_cn',
73 'big5': 'big5_tw',
74 'utf-8': 'utf-8',
75 # Hack: We don't want *any* conversion for stuff marked us-ascii, as all
76 # sorts of garbage might be sent to us in the guise of 7-bit us-ascii.
77 # Let that stuff pass through without conversion to/from Unicode.
78 'us-ascii': None,
79 }
80
81
82
83# Convenience functions for extending the above mappings
84def add_charset(charset, header_enc=None, body_enc=None, output_charset=None):
85 """Add charset properties to the global map.
86
87 charset is the input character set, and must be the canonical name of a
88 character set.
89
90 Optional header_enc and body_enc is either Charset.QP for
91 quoted-printable, Charset.BASE64 for base64 encoding, or None for no
92 encoding. It describes how message headers and message bodies in the
93 input charset are to be encoded. Default is no encoding.
94
95 Optional output_charset is the character set that the output should be
96 in. Conversions will proceed from input charset, to Unicode, to the
97 output charset when the method Charset.convert() is called. The default
98 is to output in the same character set as the input.
99
100 Both input_charset and output_charset must have Unicode codec entries in
101 the module's charset-to-codec mapping; use add_codec(charset, codecname)
102 to add codecs the module does not know about. See the codec module's
103 documentation for more information.
104 """
105 CHARSETS[charset] = (header_enc, body_enc, output_charset)
106
107
108def add_alias(alias, canonical):
109 """Add a character set alias.
110
111 alias is the alias name, e.g. latin-1
112 canonical is the character set's canonical name, e.g. iso-8859-1
113 """
114 ALIASES[alias] = canonical
115
116
117def add_codec(charset, codecname):
118 """Add a codec that map characters in the given charset to/from Unicode.
119
120 charset is the canonical name of a character set. codecname is the name
121 of a Python codec, as appropriate for the second argument to the unicode()
122 built-in, or to the .encode() method of a Unicode string.
123 """
124 CODEC_MAP[charset] = codecname
125
126
127
128class Charset:
129 """Map character sets to their email properties.
130
131 This class provides information about the requirements imposed on email
132 for a specific character set. It also provides convenience routines for
133 converting between character sets, given the availability of the
134 applicable codecs. Given an character set, it will do its best to provide
135 information on how to use that character set in an email.
Tim Peters8ac14952002-05-23 15:15:30 +0000136
Barry Warsaw409a4c02002-04-10 21:01:31 +0000137 Certain character sets must be encoded with quoted-printable or base64
138 when used in email headers or bodies. Certain character sets must be
139 converted outright, and are not allowed in email. Instances of this
140 module expose the following information about a character set:
141
142 input_charset: The initial character set specified. Common aliases
143 are converted to their `official' email names (e.g. latin_1
144 is converted to iso-8859-1). Defaults to 7-bit us-ascii.
145
146 header_encoding: If the character set must be encoded before it can be
147 used in an email header, this attribute will be set to
148 Charset.QP (for quoted-printable) or Charset.BASE64 (for
149 base64 encoding). Otherwise, it will be None.
150
151 body_encoding: Same as header_encoding, but describes the encoding for the
152 mail message's body, which indeed may be different than the
153 header encoding.
154
155 output_charset: Some character sets must be converted before the can be
156 used in email headers or bodies. If the input_charset is
157 one of them, this attribute will contain the name of the
158 charset output will be converted to. Otherwise, it will
159 be None.
160
161 input_codec: The name of the Python codec used to convert the
162 input_charset to Unicode. If no conversion codec is
163 necessary, this attribute will be None.
164
165 output_codec: The name of the Python codec used to convert Unicode
166 to the output_charset. If no conversion codec is necessary,
167 this attribute will have the same value as the input_codec.
168 """
169 def __init__(self, input_charset=DEFAULT_CHARSET):
170 # Set the input charset after filtering through the aliases
171 self.input_charset = ALIASES.get(input_charset, input_charset)
172 # We can try to guess which encoding and conversion to use by the
173 # charset_map dictionary. Try that first, but let the user override
174 # it.
175 henc, benc, conv = CHARSETS.get(self.input_charset,
176 (BASE64, BASE64, None))
177 # Set the attributes, allowing the arguments to override the default.
178 self.header_encoding = henc
179 self.body_encoding = benc
180 self.output_charset = ALIASES.get(conv, conv)
181 # Now set the codecs. If one isn't defined for input_charset,
182 # guess and try a Unicode codec with the same name as input_codec.
183 self.input_codec = CODEC_MAP.get(self.input_charset,
184 self.input_charset)
185 self.output_codec = CODEC_MAP.get(self.output_charset,
186 self.input_codec)
187
188 def __str__(self):
189 return self.input_charset.lower()
190
191 def __eq__(self, other):
192 return str(self) == str(other).lower()
193
194 def __ne__(self, other):
195 return not self.__eq__(other)
196
197 def get_body_encoding(self):
198 """Return the content-transfer-encoding used for body encoding.
199
200 This is either the string `quoted-printable' or `base64' depending on
201 the encoding used, or it is a function in which case you should call
202 the function with a single argument, the Message object being
203 encoded. The function should then set the Content-Transfer-Encoding:
204 header itself to whatever is appropriate.
205
206 Returns "quoted-printable" if self.body_encoding is QP.
207 Returns "base64" if self.body_encoding is BASE64.
208 Returns "7bit" otherwise.
209 """
210 if self.body_encoding == QP:
211 return 'quoted-printable'
212 elif self.body_encoding == BASE64:
213 return 'base64'
214 else:
215 return encode_7or8bit
216
217 def convert(self, s):
218 """Convert a string from the input_codec to the output_codec."""
219 if self.input_codec <> self.output_codec:
220 return unicode(s, self.input_codec).encode(self.output_codec)
221 else:
222 return s
223
224 def to_splittable(self, s):
225 """Convert a possibly multibyte string to a safely splittable format.
226
227 Uses the input_codec to try and convert the string to Unicode, so it
228 can be safely split on character boundaries (even for double-byte
229 characters).
230
231 Returns the string untouched if we don't know how to convert it to
232 Unicode with the input_charset.
233
234 Characters that could not be converted to Unicode will be replaced
235 with the Unicode replacement character U+FFFD.
236 """
Guido van Rossum1a7ac352002-05-28 18:49:03 +0000237 if _is_unicode(s) or self.input_codec is None:
Barry Warsaw409a4c02002-04-10 21:01:31 +0000238 return s
239 try:
240 return unicode(s, self.input_codec, 'replace')
241 except LookupError:
242 # Input codec not installed on system, so return the original
243 # string unchanged.
244 return s
245
246 def from_splittable(self, ustr, to_output=1):
247 """Convert a splittable string back into an encoded string.
248
249 Uses the proper codec to try and convert the string from
250 Unicode back into an encoded format. Return the string as-is
251 if it is not Unicode, or if it could not be encoded from
252 Unicode.
253
254 Characters that could not be converted from Unicode will be replaced
255 with an appropriate character (usually '?').
256
257 If to_output is true, uses output_codec to convert to an encoded
258 format. If to_output is false, uses input_codec. to_output defaults
259 to 1.
260 """
261 if to_output:
262 codec = self.output_codec
263 else:
264 codec = self.input_codec
Guido van Rossum1a7ac352002-05-28 18:49:03 +0000265 if not _is_unicode(ustr) or codec is None:
Barry Warsaw409a4c02002-04-10 21:01:31 +0000266 return ustr
267 try:
268 return ustr.encode(codec, 'replace')
269 except LookupError:
270 # Output codec not installed
271 return ustr
272
273 def get_output_charset(self):
274 """Return the output character set.
275
276 This is self.output_charset if that is set, otherwise it is
277 self.input_charset.
278 """
279 return self.output_charset or self.input_charset
280
281 def encoded_header_len(self, s):
282 """Return the length of the encoded header string."""
283 cset = self.get_output_charset()
284 # The len(s) of a 7bit encoding is len(s)
285 if self.header_encoding is BASE64:
286 return email.base64MIME.base64_len(s) + len(cset) + MISC_LEN
287 elif self.header_encoding is QP:
288 return email.quopriMIME.header_quopri_len(s) + len(cset) + MISC_LEN
289 else:
290 return len(s)
291
292 def header_encode(self, s, convert=0):
293 """Header-encode a string, optionally converting it to output_charset.
294
295 If convert is true, the string will be converted from the input
296 charset to the output charset automatically. This is not useful for
297 multibyte character sets, which have line length issues (multibyte
298 characters must be split on a character, not a byte boundary); use the
299 high-level Header class to deal with these issues. convert defaults
300 to 0.
301
302 The type of encoding (base64 or quoted-printable) will be based on
303 self.header_encoding.
304 """
305 cset = self.get_output_charset()
306 if convert:
307 s = self.convert(s)
308 # 7bit/8bit encodings return the string unchanged (modulo conversions)
309 if self.header_encoding is BASE64:
310 return email.base64MIME.header_encode(s, cset)
311 elif self.header_encoding is QP:
312 return email.quopriMIME.header_encode(s, cset)
313 else:
314 return s
315
316 def body_encode(self, s, convert=1):
317 """Body-encode a string and convert it to output_charset.
318
319 If convert is true (the default), the string will be converted from
320 the input charset to output charset automatically. Unlike
321 header_encode(), there are no issues with byte boundaries and
322 multibyte charsets in email bodies, so this is usually pretty safe.
323
324 The type of encoding (base64 or quoted-printable) will be based on
325 self.body_encoding.
326 """
327 if convert:
328 s = self.convert(s)
329 # 7bit/8bit encodings return the string unchanged (module conversions)
330 if self.body_encoding is BASE64:
331 return email.base64MIME.body_encode(s)
332 elif self.header_encoding is QP:
333 return email.quopriMIME.body_encode(s)
334 else:
335 return s