1 | # Copyright (C) 2001-2006 Python Software Foundation |
---|
2 | # Author: Barry Warsaw |
---|
3 | # Contact: email-sig@python.org |
---|
4 | |
---|
5 | """Encodings and related functions.""" |
---|
6 | |
---|
7 | __all__ = [ |
---|
8 | 'encode_7or8bit', |
---|
9 | 'encode_base64', |
---|
10 | 'encode_noop', |
---|
11 | 'encode_quopri', |
---|
12 | ] |
---|
13 | |
---|
14 | import base64 |
---|
15 | |
---|
16 | from quopri import encodestring as _encodestring |
---|
17 | |
---|
18 | |
---|
19 | |
---|
20 | def _qencode(s): |
---|
21 | enc = _encodestring(s, quotetabs=True) |
---|
22 | # Must encode spaces, which quopri.encodestring() doesn't do |
---|
23 | return enc.replace(' ', '=20') |
---|
24 | |
---|
25 | |
---|
26 | def _bencode(s): |
---|
27 | # We can't quite use base64.encodestring() since it tacks on a "courtesy |
---|
28 | # newline". Blech! |
---|
29 | if not s: |
---|
30 | return s |
---|
31 | hasnewline = (s[-1] == '\n') |
---|
32 | value = base64.encodestring(s) |
---|
33 | if not hasnewline and value[-1] == '\n': |
---|
34 | return value[:-1] |
---|
35 | return value |
---|
36 | |
---|
37 | |
---|
38 | |
---|
39 | def encode_base64(msg): |
---|
40 | """Encode the message's payload in Base64. |
---|
41 | |
---|
42 | Also, add an appropriate Content-Transfer-Encoding header. |
---|
43 | """ |
---|
44 | orig = msg.get_payload() |
---|
45 | encdata = _bencode(orig) |
---|
46 | msg.set_payload(encdata) |
---|
47 | msg['Content-Transfer-Encoding'] = 'base64' |
---|
48 | |
---|
49 | |
---|
50 | |
---|
51 | def encode_quopri(msg): |
---|
52 | """Encode the message's payload in quoted-printable. |
---|
53 | |
---|
54 | Also, add an appropriate Content-Transfer-Encoding header. |
---|
55 | """ |
---|
56 | orig = msg.get_payload() |
---|
57 | encdata = _qencode(orig) |
---|
58 | msg.set_payload(encdata) |
---|
59 | msg['Content-Transfer-Encoding'] = 'quoted-printable' |
---|
60 | |
---|
61 | |
---|
62 | |
---|
63 | def encode_7or8bit(msg): |
---|
64 | """Set the Content-Transfer-Encoding header to 7bit or 8bit.""" |
---|
65 | orig = msg.get_payload() |
---|
66 | if orig is None: |
---|
67 | # There's no payload. For backwards compatibility we use 7bit |
---|
68 | msg['Content-Transfer-Encoding'] = '7bit' |
---|
69 | return |
---|
70 | # We play a trick to make this go fast. If encoding to ASCII succeeds, we |
---|
71 | # know the data must be 7bit, otherwise treat it as 8bit. |
---|
72 | try: |
---|
73 | orig.encode('ascii') |
---|
74 | except UnicodeError: |
---|
75 | msg['Content-Transfer-Encoding'] = '8bit' |
---|
76 | else: |
---|
77 | msg['Content-Transfer-Encoding'] = '7bit' |
---|
78 | |
---|
79 | |
---|
80 | |
---|
81 | def encode_noop(msg): |
---|
82 | """Do nothing.""" |
---|