blob: d9cd42d45cb03e9dca9baa0e8c35bbc7694a8fd8 [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
Barry Warsawe968ead2001-10-04 17:05:11 +000011
Barry Warsawba925802001-09-23 03:17:28 +000012# Helpers
13def _qencode(s):
14 return _encodestring(s, quotetabs=1)
15
Barry Warsaw6f70c412001-09-26 05:26:22 +000016
Barry Warsawba925802001-09-23 03:17:28 +000017def _bencode(s):
18 # We can't quite use base64.encodestring() since it tacks on a "courtesy
19 # newline". Blech!
20 if not s:
21 return s
22 hasnewline = (s[-1] == '\n')
23 value = base64.encodestring(s)
24 if not hasnewline and value[-1] == '\n':
25 return value[:-1]
26 return value
27
28
Barry Warsawe968ead2001-10-04 17:05:11 +000029
Barry Warsawba925802001-09-23 03:17:28 +000030def encode_base64(msg):
31 """Encode the message's payload in Base64.
32
33 Also, add an appropriate Content-Transfer-Encoding: header.
34 """
35 orig = msg.get_payload()
36 encdata = _bencode(orig)
37 msg.set_payload(encdata)
38 msg['Content-Transfer-Encoding'] = 'base64'
39
40
Barry Warsawe968ead2001-10-04 17:05:11 +000041
Barry Warsawba925802001-09-23 03:17:28 +000042def encode_quopri(msg):
43 """Encode the message's payload in Quoted-Printable.
44
45 Also, add an appropriate Content-Transfer-Encoding: header.
46 """
47 orig = msg.get_payload()
48 encdata = _qencode(orig)
49 msg.set_payload(encdata)
50 msg['Content-Transfer-Encoding'] = 'quoted-printable'
51
52
Barry Warsawe968ead2001-10-04 17:05:11 +000053
Barry Warsawba925802001-09-23 03:17:28 +000054def encode_7or8bit(msg):
55 """Set the Content-Transfer-Encoding: header to 7bit or 8bit."""
56 orig = msg.get_payload()
57 # We play a trick to make this go fast. If encoding to ASCII succeeds, we
58 # know the data must be 7bit, otherwise treat it as 8bit.
59 try:
60 orig.encode('ascii')
61 except UnicodeError:
62 msg['Content-Transfer-Encoding'] = '8bit'
63 else:
64 msg['Content-Transfer-Encoding'] = '7bit'
65
66
Barry Warsawe968ead2001-10-04 17:05:11 +000067
Barry Warsawba925802001-09-23 03:17:28 +000068def encode_noop(msg):
69 """Do nothing."""