base64mime.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. # Copyright (C) 2002-2006 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. 'base64_len',
  22. 'body_decode',
  23. 'body_encode',
  24. 'decode',
  25. 'decodestring',
  26. 'encode',
  27. 'encodestring',
  28. 'header_encode',
  29. ]
  30. from binascii import b2a_base64, a2b_base64
  31. from email.utils import fix_eols
  32. CRLF = '\r\n'
  33. NL = '\n'
  34. EMPTYSTRING = ''
  35. # See also Charset.py
  36. MISC_LEN = 7
  37. # Helpers
  38. def base64_len(s):
  39. """Return the length of s when it is encoded with base64."""
  40. groups_of_3, leftover = divmod(len(s), 3)
  41. # 4 bytes out for each 3 bytes (or nonzero fraction thereof) in.
  42. # Thanks, Tim!
  43. n = groups_of_3 * 4
  44. if leftover:
  45. n += 4
  46. return n
  47. def header_encode(header, charset='iso-8859-1', keep_eols=False,
  48. maxlinelen=76, eol=NL):
  49. """Encode a single header line with Base64 encoding in a given charset.
  50. Defined in RFC 2045, this Base64 encoding is identical to normal Base64
  51. encoding, except that each line must be intelligently wrapped (respecting
  52. the Base64 encoding), and subsequent lines must start with a space.
  53. charset names the character set to use to encode the header. It defaults
  54. to iso-8859-1.
  55. End-of-line characters (\\r, \\n, \\r\\n) will be automatically converted
  56. to the canonical email line separator \\r\\n unless the keep_eols
  57. parameter is True (the default is False).
  58. Each line of the header will be terminated in the value of eol, which
  59. defaults to "\\n". Set this to "\\r\\n" if you are using the result of
  60. this function directly in email.
  61. The resulting string will be in the form:
  62. "=?charset?b?WW/5ciBtYXp66XLrIHf8eiBhIGhhbXBzdGHuciBBIFlv+XIgbWF6euly?=\\n
  63. =?charset?b?6yB3/HogYSBoYW1wc3Rh7nIgQkMgWW/5ciBtYXp66XLrIHf8eiBhIGhh?="
  64. with each line wrapped at, at most, maxlinelen characters (defaults to 76
  65. characters).
  66. """
  67. # Return empty headers unchanged
  68. if not header:
  69. return header
  70. if not keep_eols:
  71. header = fix_eols(header)
  72. # Base64 encode each line, in encoded chunks no greater than maxlinelen in
  73. # length, after the RFC chrome is added in.
  74. base64ed = []
  75. max_encoded = maxlinelen - len(charset) - MISC_LEN
  76. max_unencoded = max_encoded * 3 // 4
  77. for i in range(0, len(header), max_unencoded):
  78. base64ed.append(b2a_base64(header[i:i+max_unencoded]))
  79. # Now add the RFC chrome to each encoded chunk
  80. lines = []
  81. for line in base64ed:
  82. # Ignore the last character of each line if it is a newline
  83. if line.endswith(NL):
  84. line = line[:-1]
  85. # Add the chrome
  86. lines.append('=?%s?b?%s?=' % (charset, line))
  87. # Glue the lines together and return it. BAW: should we be able to
  88. # specify the leading whitespace in the joiner?
  89. joiner = eol + ' '
  90. return joiner.join(lines)
  91. def encode(s, binary=True, maxlinelen=76, eol=NL):
  92. """Encode a string with base64.
  93. Each line will be wrapped at, at most, maxlinelen characters (defaults to
  94. 76 characters).
  95. If binary is False, end-of-line characters will be converted to the
  96. canonical email end-of-line sequence \\r\\n. Otherwise they will be left
  97. verbatim (this is the default).
  98. Each line of encoded text will end with eol, which defaults to "\\n". Set
  99. this to "\\r\\n" if you will be using the result of this function directly
  100. in an email.
  101. """
  102. if not s:
  103. return s
  104. if not binary:
  105. s = fix_eols(s)
  106. encvec = []
  107. max_unencoded = maxlinelen * 3 // 4
  108. for i in range(0, len(s), max_unencoded):
  109. # BAW: should encode() inherit b2a_base64()'s dubious behavior in
  110. # adding a newline to the encoded string?
  111. enc = b2a_base64(s[i:i + max_unencoded])
  112. if enc.endswith(NL) and eol != NL:
  113. enc = enc[:-1] + eol
  114. encvec.append(enc)
  115. return EMPTYSTRING.join(encvec)
  116. # For convenience and backwards compatibility w/ standard base64 module
  117. body_encode = encode
  118. encodestring = encode
  119. def decode(s, convert_eols=None):
  120. """Decode a raw base64 string.
  121. If convert_eols is set to a string value, all canonical email linefeeds,
  122. e.g. "\\r\\n", in the decoded text will be converted to the value of
  123. convert_eols. os.linesep is a good choice for convert_eols if you are
  124. decoding a text attachment.
  125. This function does not parse a full MIME header value encoded with
  126. base64 (like =?iso-8895-1?b?bmloISBuaWgh?=) -- please use the high
  127. level email.header class for that functionality.
  128. """
  129. if not s:
  130. return s
  131. dec = a2b_base64(s)
  132. if convert_eols:
  133. return dec.replace(CRLF, convert_eols)
  134. return dec
  135. # For convenience and backwards compatibility w/ standard base64 module
  136. body_decode = decode
  137. decodestring = decode