encoders.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. import base64
  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(' ', '=20')
  17. def _bencode(s):
  18. # We can't quite use base64.encodestring() since it tacks on a "courtesy
  19. # newline". Blech!
  20. if not s:
  21. return s
  22. hasnewline = (s[-1] == '\n')
  23. value = base64.encodestring(s)
  24. if not hasnewline and value[-1] == '\n':
  25. return value[:-1]
  26. return value
  27. def encode_base64(msg):
  28. """Encode the message's payload in Base64.
  29. Also, add an appropriate Content-Transfer-Encoding header.
  30. """
  31. orig = msg.get_payload()
  32. encdata = _bencode(orig)
  33. msg.set_payload(encdata)
  34. msg['Content-Transfer-Encoding'] = 'base64'
  35. def encode_quopri(msg):
  36. """Encode the message's payload in quoted-printable.
  37. Also, add an appropriate Content-Transfer-Encoding header.
  38. """
  39. orig = msg.get_payload()
  40. encdata = _qencode(orig)
  41. msg.set_payload(encdata)
  42. msg['Content-Transfer-Encoding'] = 'quoted-printable'
  43. def encode_7or8bit(msg):
  44. """Set the Content-Transfer-Encoding header to 7bit or 8bit."""
  45. orig = msg.get_payload()
  46. if orig is None:
  47. # There's no payload. For backwards compatibility we use 7bit
  48. msg['Content-Transfer-Encoding'] = '7bit'
  49. return
  50. # We play a trick to make this go fast. If encoding to ASCII succeeds, we
  51. # know the data must be 7bit, otherwise treat it as 8bit.
  52. try:
  53. orig.encode('ascii')
  54. except UnicodeError:
  55. msg['Content-Transfer-Encoding'] = '8bit'
  56. else:
  57. msg['Content-Transfer-Encoding'] = '7bit'
  58. def encode_noop(msg):
  59. """Do nothing."""