PageRenderTime 61ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/python/lib/python2.7/email/quoprimime.py

https://bitbucket.org/lbesson/web-sphinx-scripts
Python | 336 lines | 292 code | 14 blank | 30 comment | 19 complexity | 6918018cd2adae77d6326fccd6c8fdf9 MD5 | raw file
  1. # Copyright (C) 2001-2006 Python Software Foundation
  2. # Author: Ben Gertzfield
  3. # Contact: email-sig@python.org
  4. """Quoted-printable content transfer encoding per RFCs 2045-2047.
  5. This module handles the content transfer encoding method defined in RFC 2045
  6. to encode US ASCII-like 8-bit data called `quoted-printable'. It is used to
  7. safely encode text that is in a character set similar to the 7-bit US ASCII
  8. character set, but that includes some 8-bit characters that are normally not
  9. allowed in email bodies or headers.
  10. Quoted-printable is very space-inefficient for encoding binary files; use the
  11. email.base64mime module for that instead.
  12. This module provides an interface to encode and decode both headers and bodies
  13. with quoted-printable encoding.
  14. RFC 2045 defines a method for including character set information in an
  15. `encoded-word' in a header. This method is commonly used for 8-bit real names
  16. in To:/From:/Cc: etc. fields, as well as Subject: lines.
  17. This module does not do the line wrapping or end-of-line character
  18. conversion necessary for proper internationalized headers; it only
  19. does dumb encoding and decoding. To deal with the various line
  20. wrapping issues, use the email.header module.
  21. """
  22. __all__ = [
  23. 'body_decode',
  24. 'body_encode',
  25. 'body_quopri_check',
  26. 'body_quopri_len',
  27. 'decode',
  28. 'decodestring',
  29. 'encode',
  30. 'encodestring',
  31. 'header_decode',
  32. 'header_encode',
  33. 'header_quopri_check',
  34. 'header_quopri_len',
  35. 'quote',
  36. 'unquote',
  37. ]
  38. import re
  39. from string import hexdigits
  40. from email.utils import fix_eols
  41. CRLF = '\r\n'
  42. NL = '\n'
  43. # See also Charset.py
  44. MISC_LEN = 7
  45. hqre = re.compile(r'[^-a-zA-Z0-9!*+/ ]')
  46. bqre = re.compile(r'[^ !-<>-~\t]')
  47. # Helpers
  48. def header_quopri_check(c):
  49. """Return True if the character should be escaped with header quopri."""
  50. return bool(hqre.match(c))
  51. def body_quopri_check(c):
  52. """Return True if the character should be escaped with body quopri."""
  53. return bool(bqre.match(c))
  54. def header_quopri_len(s):
  55. """Return the length of str when it is encoded with header quopri."""
  56. count = 0
  57. for c in s:
  58. if hqre.match(c):
  59. count += 3
  60. else:
  61. count += 1
  62. return count
  63. def body_quopri_len(str):
  64. """Return the length of str when it is encoded with body quopri."""
  65. count = 0
  66. for c in str:
  67. if bqre.match(c):
  68. count += 3
  69. else:
  70. count += 1
  71. return count
  72. def _max_append(L, s, maxlen, extra=''):
  73. if not L:
  74. L.append(s.lstrip())
  75. elif len(L[-1]) + len(s) <= maxlen:
  76. L[-1] += extra + s
  77. else:
  78. L.append(s.lstrip())
  79. def unquote(s):
  80. """Turn a string in the form =AB to the ASCII character with value 0xab"""
  81. return chr(int(s[1:3], 16))
  82. def quote(c):
  83. return "=%02X" % ord(c)
  84. def header_encode(header, charset="iso-8859-1", keep_eols=False,
  85. maxlinelen=76, eol=NL):
  86. """Encode a single header line with quoted-printable (like) encoding.
  87. Defined in RFC 2045, this `Q' encoding is similar to quoted-printable, but
  88. used specifically for email header fields to allow charsets with mostly 7
  89. bit characters (and some 8 bit) to remain more or less readable in non-RFC
  90. 2045 aware mail clients.
  91. charset names the character set to use to encode the header. It defaults
  92. to iso-8859-1.
  93. The resulting string will be in the form:
  94. "=?charset?q?I_f=E2rt_in_your_g=E8n=E8ral_dire=E7tion?\\n
  95. =?charset?q?Silly_=C8nglish_Kn=EEghts?="
  96. with each line wrapped safely at, at most, maxlinelen characters (defaults
  97. to 76 characters). If maxlinelen is None, the entire string is encoded in
  98. one chunk with no splitting.
  99. End-of-line characters (\\r, \\n, \\r\\n) will be automatically converted
  100. to the canonical email line separator \\r\\n unless the keep_eols
  101. parameter is True (the default is False).
  102. Each line of the header will be terminated in the value of eol, which
  103. defaults to "\\n". Set this to "\\r\\n" if you are using the result of
  104. this function directly in email.
  105. """
  106. # Return empty headers unchanged
  107. if not header:
  108. return header
  109. if not keep_eols:
  110. header = fix_eols(header)
  111. # Quopri encode each line, in encoded chunks no greater than maxlinelen in
  112. # length, after the RFC chrome is added in.
  113. quoted = []
  114. if maxlinelen is None:
  115. # An obnoxiously large number that's good enough
  116. max_encoded = 100000
  117. else:
  118. max_encoded = maxlinelen - len(charset) - MISC_LEN - 1
  119. for c in header:
  120. # Space may be represented as _ instead of =20 for readability
  121. if c == ' ':
  122. _max_append(quoted, '_', max_encoded)
  123. # These characters can be included verbatim
  124. elif not hqre.match(c):
  125. _max_append(quoted, c, max_encoded)
  126. # Otherwise, replace with hex value like =E2
  127. else:
  128. _max_append(quoted, "=%02X" % ord(c), max_encoded)
  129. # Now add the RFC chrome to each encoded chunk and glue the chunks
  130. # together. BAW: should we be able to specify the leading whitespace in
  131. # the joiner?
  132. joiner = eol + ' '
  133. return joiner.join(['=?%s?q?%s?=' % (charset, line) for line in quoted])
  134. def encode(body, binary=False, maxlinelen=76, eol=NL):
  135. """Encode with quoted-printable, wrapping at maxlinelen characters.
  136. If binary is False (the default), end-of-line characters will be converted
  137. to the canonical email end-of-line sequence \\r\\n. Otherwise they will
  138. be left verbatim.
  139. Each line of encoded text will end with eol, which defaults to "\\n". Set
  140. this to "\\r\\n" if you will be using the result of this function directly
  141. in an email.
  142. Each line will be wrapped at, at most, maxlinelen characters (defaults to
  143. 76 characters). Long lines will have the `soft linefeed' quoted-printable
  144. character "=" appended to them, so the decoded text will be identical to
  145. the original text.
  146. """
  147. if not body:
  148. return body
  149. if not binary:
  150. body = fix_eols(body)
  151. # BAW: We're accumulating the body text by string concatenation. That
  152. # can't be very efficient, but I don't have time now to rewrite it. It
  153. # just feels like this algorithm could be more efficient.
  154. encoded_body = ''
  155. lineno = -1
  156. # Preserve line endings here so we can check later to see an eol needs to
  157. # be added to the output later.
  158. lines = body.splitlines(1)
  159. for line in lines:
  160. # But strip off line-endings for processing this line.
  161. if line.endswith(CRLF):
  162. line = line[:-2]
  163. elif line[-1] in CRLF:
  164. line = line[:-1]
  165. lineno += 1
  166. encoded_line = ''
  167. prev = None
  168. linelen = len(line)
  169. # Now we need to examine every character to see if it needs to be
  170. # quopri encoded. BAW: again, string concatenation is inefficient.
  171. for j in range(linelen):
  172. c = line[j]
  173. prev = c
  174. if bqre.match(c):
  175. c = quote(c)
  176. elif j+1 == linelen:
  177. # Check for whitespace at end of line; special case
  178. if c not in ' \t':
  179. encoded_line += c
  180. prev = c
  181. continue
  182. # Check to see to see if the line has reached its maximum length
  183. if len(encoded_line) + len(c) >= maxlinelen:
  184. encoded_body += encoded_line + '=' + eol
  185. encoded_line = ''
  186. encoded_line += c
  187. # Now at end of line..
  188. if prev and prev in ' \t':
  189. # Special case for whitespace at end of file
  190. if lineno + 1 == len(lines):
  191. prev = quote(prev)
  192. if len(encoded_line) + len(prev) > maxlinelen:
  193. encoded_body += encoded_line + '=' + eol + prev
  194. else:
  195. encoded_body += encoded_line + prev
  196. # Just normal whitespace at end of line
  197. else:
  198. encoded_body += encoded_line + prev + '=' + eol
  199. encoded_line = ''
  200. # Now look at the line we just finished and it has a line ending, we
  201. # need to add eol to the end of the line.
  202. if lines[lineno].endswith(CRLF) or lines[lineno][-1] in CRLF:
  203. encoded_body += encoded_line + eol
  204. else:
  205. encoded_body += encoded_line
  206. encoded_line = ''
  207. return encoded_body
  208. # For convenience and backwards compatibility w/ standard base64 module
  209. body_encode = encode
  210. encodestring = encode
  211. # BAW: I'm not sure if the intent was for the signature of this function to be
  212. # the same as base64MIME.decode() or not...
  213. def decode(encoded, eol=NL):
  214. """Decode a quoted-printable string.
  215. Lines are separated with eol, which defaults to \\n.
  216. """
  217. if not encoded:
  218. return encoded
  219. # BAW: see comment in encode() above. Again, we're building up the
  220. # decoded string with string concatenation, which could be done much more
  221. # efficiently.
  222. decoded = ''
  223. for line in encoded.splitlines():
  224. line = line.rstrip()
  225. if not line:
  226. decoded += eol
  227. continue
  228. i = 0
  229. n = len(line)
  230. while i < n:
  231. c = line[i]
  232. if c != '=':
  233. decoded += c
  234. i += 1
  235. # Otherwise, c == "=". Are we at the end of the line? If so, add
  236. # a soft line break.
  237. elif i+1 == n:
  238. i += 1
  239. continue
  240. # Decode if in form =AB
  241. elif i+2 < n and line[i+1] in hexdigits and line[i+2] in hexdigits:
  242. decoded += unquote(line[i:i+3])
  243. i += 3
  244. # Otherwise, not in form =AB, pass literally
  245. else:
  246. decoded += c
  247. i += 1
  248. if i == n:
  249. decoded += eol
  250. # Special case if original string did not end with eol
  251. if not encoded.endswith(eol) and decoded.endswith(eol):
  252. decoded = decoded[:-1]
  253. return decoded
  254. # For convenience and backwards compatibility w/ standard base64 module
  255. body_decode = decode
  256. decodestring = decode
  257. def _unquote_match(match):
  258. """Turn a match in the form =AB to the ASCII character with value 0xab"""
  259. s = match.group(0)
  260. return unquote(s)
  261. # Header decoding is done a bit differently
  262. def header_decode(s):
  263. """Decode a string encoded with RFC 2045 MIME header `Q' encoding.
  264. This function does not parse a full MIME header value encoded with
  265. quoted-printable (like =?iso-8895-1?q?Hello_World?=) -- please use
  266. the high level email.header class for that functionality.
  267. """
  268. s = s.replace('_', ' ')
  269. return re.sub(r'=[a-fA-F0-9]{2}', _unquote_match, s)