jpayne@68: # Copyright (C) 2001-2006 Python Software Foundation jpayne@68: # Author: Barry Warsaw jpayne@68: # Contact: email-sig@python.org jpayne@68: jpayne@68: """Encodings and related functions.""" jpayne@68: jpayne@68: __all__ = [ jpayne@68: 'encode_7or8bit', jpayne@68: 'encode_base64', jpayne@68: 'encode_noop', jpayne@68: 'encode_quopri', jpayne@68: ] jpayne@68: jpayne@68: jpayne@68: from base64 import encodebytes as _bencode jpayne@68: from quopri import encodestring as _encodestring jpayne@68: jpayne@68: jpayne@68: jpayne@68: def _qencode(s): jpayne@68: enc = _encodestring(s, quotetabs=True) jpayne@68: # Must encode spaces, which quopri.encodestring() doesn't do jpayne@68: return enc.replace(b' ', b'=20') jpayne@68: jpayne@68: jpayne@68: def encode_base64(msg): jpayne@68: """Encode the message's payload in Base64. jpayne@68: jpayne@68: Also, add an appropriate Content-Transfer-Encoding header. jpayne@68: """ jpayne@68: orig = msg.get_payload(decode=True) jpayne@68: encdata = str(_bencode(orig), 'ascii') jpayne@68: msg.set_payload(encdata) jpayne@68: msg['Content-Transfer-Encoding'] = 'base64' jpayne@68: jpayne@68: jpayne@68: jpayne@68: def encode_quopri(msg): jpayne@68: """Encode the message's payload in quoted-printable. jpayne@68: jpayne@68: Also, add an appropriate Content-Transfer-Encoding header. jpayne@68: """ jpayne@68: orig = msg.get_payload(decode=True) jpayne@68: encdata = _qencode(orig) jpayne@68: msg.set_payload(encdata) jpayne@68: msg['Content-Transfer-Encoding'] = 'quoted-printable' jpayne@68: jpayne@68: jpayne@68: jpayne@68: def encode_7or8bit(msg): jpayne@68: """Set the Content-Transfer-Encoding header to 7bit or 8bit.""" jpayne@68: orig = msg.get_payload(decode=True) jpayne@68: if orig is None: jpayne@68: # There's no payload. For backwards compatibility we use 7bit jpayne@68: msg['Content-Transfer-Encoding'] = '7bit' jpayne@68: return jpayne@68: # We play a trick to make this go fast. If decoding from ASCII succeeds, jpayne@68: # we know the data must be 7bit, otherwise treat it as 8bit. jpayne@68: try: jpayne@68: orig.decode('ascii') jpayne@68: except UnicodeError: jpayne@68: msg['Content-Transfer-Encoding'] = '8bit' jpayne@68: else: jpayne@68: msg['Content-Transfer-Encoding'] = '7bit' jpayne@68: jpayne@68: jpayne@68: jpayne@68: def encode_noop(msg): jpayne@68: """Do nothing."""