1 # Copyright (C) 2001-2006 Python Software Foundation 2 # Author: Barry Warsaw 3 # Contact: email-sig (at] 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 15 from base64 import encodebytes as _bencode 16 from quopri import encodestring as _encodestring 17 18 19 21 def _qencode(s): 22 enc = _encodestring(s, quotetabs=True) 23 # Must encode spaces, which quopri.encodestring() doesn't do 24 return enc.replace(b' ', b'=20') 25 26 27 def encode_base64(msg): 28 """Encode the message's payload in Base64. 29 30 Also, add an appropriate Content-Transfer-Encoding header. 31 """ 32 orig = msg.get_payload(decode=True) 33 encdata = str(_bencode(orig), 'ascii') 34 msg.set_payload(encdata) 35 msg['Content-Transfer-Encoding'] = 'base64' 36 37 38 40 def encode_quopri(msg): 41 """Encode the message's payload in quoted-printable. 42 43 Also, add an appropriate Content-Transfer-Encoding header. 44 """ 45 orig = msg.get_payload(decode=True) 46 encdata = _qencode(orig) 47 msg.set_payload(encdata) 48 msg['Content-Transfer-Encoding'] = 'quoted-printable' 49 50 51 53 def encode_7or8bit(msg): 54 """Set the Content-Transfer-Encoding header to 7bit or 8bit.""" 55 orig = msg.get_payload(decode=True) 56 if orig is None: 57 # There's no payload. For backwards compatibility we use 7bit 58 msg['Content-Transfer-Encoding'] = '7bit' 59 return 60 # We play a trick to make this go fast. If decoding from ASCII succeeds, 61 # we know the data must be 7bit, otherwise treat it as 8bit. 62 try: 63 orig.decode('ascii') 64 except UnicodeError: 65 msg['Content-Transfer-Encoding'] = '8bit' 66 else: 67 msg['Content-Transfer-Encoding'] = '7bit' 68 69 70 72 def encode_noop(msg): 73 """Do nothing.""" 74