base64mime.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  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. from __future__ import unicode_literals
  21. from __future__ import division
  22. from __future__ import absolute_import
  23. from future.builtins import range
  24. from future.builtins import bytes
  25. __all__ = [
  26. 'body_decode',
  27. 'body_encode',
  28. 'decode',
  29. 'decodestring',
  30. 'header_encode',
  31. 'header_length',
  32. ]
  33. from base64 import b64encode
  34. from binascii import b2a_base64, a2b_base64
  35. CRLF = '\r\n'
  36. NL = '\n'
  37. EMPTYSTRING = ''
  38. # See also Charset.py
  39. MISC_LEN = 7
  40. # Helpers
  41. def header_length(bytearray):
  42. """Return the length of s when it is encoded with base64."""
  43. groups_of_3, leftover = divmod(len(bytearray), 3)
  44. # 4 bytes out for each 3 bytes (or nonzero fraction thereof) in.
  45. n = groups_of_3 * 4
  46. if leftover:
  47. n += 4
  48. return n
  49. def header_encode(header_bytes, charset='iso-8859-1'):
  50. """Encode a single header line with Base64 encoding in a given charset.
  51. charset names the character set to use to encode the header. It defaults
  52. to iso-8859-1. Base64 encoding is defined in RFC 2045.
  53. """
  54. if not header_bytes:
  55. return ""
  56. if isinstance(header_bytes, str):
  57. header_bytes = header_bytes.encode(charset)
  58. encoded = b64encode(header_bytes).decode("ascii")
  59. return '=?%s?b?%s?=' % (charset, encoded)
  60. def body_encode(s, maxlinelen=76, eol=NL):
  61. r"""Encode a string with base64.
  62. Each line will be wrapped at, at most, maxlinelen characters (defaults to
  63. 76 characters).
  64. Each line of encoded text will end with eol, which defaults to "\n". Set
  65. this to "\r\n" if you will be using the result of this function directly
  66. in an email.
  67. """
  68. if not s:
  69. return s
  70. encvec = []
  71. max_unencoded = maxlinelen * 3 // 4
  72. for i in range(0, len(s), max_unencoded):
  73. # BAW: should encode() inherit b2a_base64()'s dubious behavior in
  74. # adding a newline to the encoded string?
  75. enc = b2a_base64(s[i:i + max_unencoded]).decode("ascii")
  76. if enc.endswith(NL) and eol != NL:
  77. enc = enc[:-1] + eol
  78. encvec.append(enc)
  79. return EMPTYSTRING.join(encvec)
  80. def decode(string):
  81. """Decode a raw base64 string, returning a bytes object.
  82. This function does not parse a full MIME header value encoded with
  83. base64 (like =?iso-8895-1?b?bmloISBuaWgh?=) -- please use the high
  84. level email.header class for that functionality.
  85. """
  86. if not string:
  87. return bytes()
  88. elif isinstance(string, str):
  89. return a2b_base64(string.encode('raw-unicode-escape'))
  90. else:
  91. return a2b_base64(string)
  92. # For convenience and backwards compatibility w/ standard base64 module
  93. body_decode = decode
  94. decodestring = decode