encoders.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. # Copyright (C) 2001-2006 Python Software Foundation
  2. # Author: Barry Warsaw
  3. # Contact: email-sig@python.org
  4. """Encodings and related functions."""
  5. __all__ = [
  6. 'encode_7or8bit',
  7. 'encode_base64',
  8. 'encode_noop',
  9. 'encode_quopri',
  10. ]
  11. from base64 import encodebytes as _bencode
  12. from quopri import encodestring as _encodestring
  13. def _qencode(s):
  14. enc = _encodestring(s, quotetabs=True)
  15. # Must encode spaces, which quopri.encodestring() doesn't do
  16. return enc.replace(b' ', b'=20')
  17. def encode_base64(msg):
  18. """Encode the message's payload in Base64.
  19. Also, add an appropriate Content-Transfer-Encoding header.
  20. """
  21. orig = msg.get_payload(decode=True)
  22. encdata = str(_bencode(orig), 'ascii')
  23. msg.set_payload(encdata)
  24. msg['Content-Transfer-Encoding'] = 'base64'
  25. def encode_quopri(msg):
  26. """Encode the message's payload in quoted-printable.
  27. Also, add an appropriate Content-Transfer-Encoding header.
  28. """
  29. orig = msg.get_payload(decode=True)
  30. encdata = _qencode(orig)
  31. msg.set_payload(encdata)
  32. msg['Content-Transfer-Encoding'] = 'quoted-printable'
  33. def encode_7or8bit(msg):
  34. """Set the Content-Transfer-Encoding header to 7bit or 8bit."""
  35. orig = msg.get_payload(decode=True)
  36. if orig is None:
  37. # There's no payload. For backwards compatibility we use 7bit
  38. msg['Content-Transfer-Encoding'] = '7bit'
  39. return
  40. # We play a trick to make this go fast. If decoding from ASCII succeeds,
  41. # we know the data must be 7bit, otherwise treat it as 8bit.
  42. try:
  43. orig.decode('ascii')
  44. except UnicodeError:
  45. msg['Content-Transfer-Encoding'] = '8bit'
  46. else:
  47. msg['Content-Transfer-Encoding'] = '7bit'
  48. def encode_noop(msg):
  49. """Do nothing."""