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