0001 # Copyright (C) 2001-2004 Python Software Foundation 0002 # Author: Barry Warsaw 0003 # Contact: email-sig@python.org 0004 0005 """Encodings and related functions.""" 0006 0007 import base64 0008 from quopri import encodestring as _encodestring 0009 0010 def _qencode(s): 0011 enc = _encodestring(s, quotetabs=True) 0012 # Must encode spaces, which quopri.encodestring() doesn't do 0013 return enc.replace(' ', '=20') 0014 0015 0016 def _bencode(s): 0017 # We can't quite use base64.encodestring() since it tacks on a "courtesy 0018 # newline". Blech! 0019 if not s: 0020 return s 0021 hasnewline = (s[-1] == '\n') 0022 value = base64.encodestring(s) 0023 if not hasnewline and value[-1] == '\n': 0024 return value[:-1] 0025 return value 0026 0027 0028 0029 def encode_base64(msg): 0030 """Encode the message's payload in Base64. 0031 0032 Also, add an appropriate Content-Transfer-Encoding header. 0033 """ 0034 orig = msg.get_payload() 0035 encdata = _bencode(orig) 0036 msg.set_payload(encdata) 0037 msg['Content-Transfer-Encoding'] = 'base64' 0038 0039 0040 0041 def encode_quopri(msg): 0042 """Encode the message's payload in quoted-printable. 0043 0044 Also, add an appropriate Content-Transfer-Encoding header. 0045 """ 0046 orig = msg.get_payload() 0047 encdata = _qencode(orig) 0048 msg.set_payload(encdata) 0049 msg['Content-Transfer-Encoding'] = 'quoted-printable' 0050 0051 0052 0053 def encode_7or8bit(msg): 0054 """Set the Content-Transfer-Encoding header to 7bit or 8bit.""" 0055 orig = msg.get_payload() 0056 if orig is None: 0057 # There's no payload. For backwards compatibility we use 7bit 0058 msg['Content-Transfer-Encoding'] = '7bit' 0059 return 0060 # We play a trick to make this go fast. If encoding to ASCII succeeds, we 0061 # know the data must be 7bit, otherwise treat it as 8bit. 0062 try: 0063 orig.encode('ascii') 0064 except UnicodeError: 0065 # iso-2022-* is non-ASCII but still 7-bit 0066 charset = msg.get_charset() 0067 output_cset = charset and charset.output_charset 0068 if output_cset and output_cset.lower().startswith('iso-2202-'): 0069 msg['Content-Transfer-Encoding'] = '7bit' 0070 else: 0071 msg['Content-Transfer-Encoding'] = '8bit' 0072 else: 0073 msg['Content-Transfer-Encoding'] = '7bit' 0074 0075 0076 0077 def encode_noop(msg): 0078 """Do nothing.""" 0079
Generated by PyXR 0.9.4