base64mime.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. # Copyright (C) 2002-2007 Python Software Foundation
  2. # Author: Ben Gertzfield
  3. # Contact: email-sig@python.org
  4. """Base64 content transfer encoding per RFCs 2045-2047.
  5. This module handles the content transfer encoding method defined in RFC 2045
  6. to encode arbitrary 8-bit data using the three 8-bit bytes in four 7-bit
  7. characters encoding known as Base64.
  8. It is used in the MIME standards for email to attach images, audio, and text
  9. using some 8-bit character sets to messages.
  10. This module provides an interface to encode and decode both headers and bodies
  11. with Base64 encoding.
  12. RFC 2045 defines a method for including character set information in an
  13. `encoded-word' in a header. This method is commonly used for 8-bit real names
  14. in To:, From:, Cc:, etc. fields, as well as Subject: lines.
  15. This module does not do the line wrapping or end-of-line character conversion
  16. necessary for proper internationalized headers; it only does dumb encoding and
  17. decoding. To deal with the various line wrapping issues, use the email.header
  18. module.
  19. """
  20. __all__ = [
  21. 'body_decode',
  22. 'body_encode',
  23. 'decode',
  24. 'decodestring',
  25. 'header_encode',
  26. 'header_length',
  27. ]
  28. from base64 import b64encode
  29. from binascii import b2a_base64, a2b_base64
  30. CRLF = '\r\n'
  31. NL = '\n'
  32. EMPTYSTRING = ''
  33. # See also Charset.py
  34. MISC_LEN = 7
  35. # Helpers
  36. def header_length(bytearray):
  37. """Return the length of s when it is encoded with base64."""
  38. groups_of_3, leftover = divmod(len(bytearray), 3)
  39. # 4 bytes out for each 3 bytes (or nonzero fraction thereof) in.
  40. n = groups_of_3 * 4
  41. if leftover:
  42. n += 4
  43. return n
  44. def header_encode(header_bytes, charset='iso-8859-1'):
  45. """Encode a single header line with Base64 encoding in a given charset.
  46. charset names the character set to use to encode the header. It defaults
  47. to iso-8859-1. Base64 encoding is defined in RFC 2045.
  48. """
  49. if not header_bytes:
  50. return ""
  51. if isinstance(header_bytes, str):
  52. header_bytes = header_bytes.encode(charset)
  53. encoded = b64encode(header_bytes).decode("ascii")
  54. return '=?%s?b?%s?=' % (charset, encoded)
  55. def body_encode(s, maxlinelen=76, eol=NL):
  56. r"""Encode a string with base64.
  57. Each line will be wrapped at, at most, maxlinelen characters (defaults to
  58. 76 characters).
  59. Each line of encoded text will end with eol, which defaults to "\n". Set
  60. this to "\r\n" if you will be using the result of this function directly
  61. in an email.
  62. """
  63. if not s:
  64. return s
  65. encvec = []
  66. max_unencoded = maxlinelen * 3 // 4
  67. for i in range(0, len(s), max_unencoded):
  68. # BAW: should encode() inherit b2a_base64()'s dubious behavior in
  69. # adding a newline to the encoded string?
  70. enc = b2a_base64(s[i:i + max_unencoded]).decode("ascii")
  71. if enc.endswith(NL) and eol != NL:
  72. enc = enc[:-1] + eol
  73. encvec.append(enc)
  74. return EMPTYSTRING.join(encvec)
  75. def decode(string):
  76. """Decode a raw base64 string, returning a bytes object.
  77. This function does not parse a full MIME header value encoded with
  78. base64 (like =?iso-8859-1?b?bmloISBuaWgh?=) -- please use the high
  79. level email.header class for that functionality.
  80. """
  81. if not string:
  82. return bytes()
  83. elif isinstance(string, str):
  84. return a2b_base64(string.encode('raw-unicode-escape'))
  85. else:
  86. return a2b_base64(string)
  87. # For convenience and backwards compatibility w/ standard base64 module
  88. body_decode = decode
  89. decodestring = decode