blob: 36db370433ee410f93e5f0e101a7ea224b9ab60e [file] [log] [blame]
Barry Warsawba925802001-09-23 03:17:28 +00001# Copyright (C) 2001 Python Software Foundation
2# Author: barry@zope.com (Barry Warsaw)
3
4"""Module containing encoding functions for Image.Image and Text.Text.
5"""
6
7import base64
8from quopri import encodestring as _encodestring
9
10
11
12# Helpers
13def _qencode(s):
14 return _encodestring(s, quotetabs=1)
15
16def _bencode(s):
17 # We can't quite use base64.encodestring() since it tacks on a "courtesy
18 # newline". Blech!
19 if not s:
20 return s
21 hasnewline = (s[-1] == '\n')
22 value = base64.encodestring(s)
23 if not hasnewline and value[-1] == '\n':
24 return value[:-1]
25 return value
26
27
28
29def encode_base64(msg):
30 """Encode the message's payload in Base64.
31
32 Also, add an appropriate Content-Transfer-Encoding: header.
33 """
34 orig = msg.get_payload()
35 encdata = _bencode(orig)
36 msg.set_payload(encdata)
37 msg['Content-Transfer-Encoding'] = 'base64'
38
39
40
41def encode_quopri(msg):
42 """Encode the message's payload in Quoted-Printable.
43
44 Also, add an appropriate Content-Transfer-Encoding: header.
45 """
46 orig = msg.get_payload()
47 encdata = _qencode(orig)
48 msg.set_payload(encdata)
49 msg['Content-Transfer-Encoding'] = 'quoted-printable'
50
51
52
53def encode_7or8bit(msg):
54 """Set the Content-Transfer-Encoding: header to 7bit or 8bit."""
55 orig = msg.get_payload()
56 # We play a trick to make this go fast. If encoding to ASCII succeeds, we
57 # know the data must be 7bit, otherwise treat it as 8bit.
58 try:
59 orig.encode('ascii')
60 except UnicodeError:
61 msg['Content-Transfer-Encoding'] = '8bit'
62 else:
63 msg['Content-Transfer-Encoding'] = '7bit'
64
65
66
67def encode_noop(msg):
68 """Do nothing."""