generator.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. # Copyright (C) 2001-2010 Python Software Foundation
  2. # Contact: email-sig@python.org
  3. """Classes to generate plain text from a message object tree."""
  4. __all__ = ['Generator', 'DecodedGenerator']
  5. import re
  6. import sys
  7. import time
  8. import random
  9. import warnings
  10. from cStringIO import StringIO
  11. from email.header import Header
  12. UNDERSCORE = '_'
  13. NL = '\n'
  14. fcre = re.compile(r'^From ', re.MULTILINE)
  15. def _is8bitstring(s):
  16. if isinstance(s, str):
  17. try:
  18. unicode(s, 'us-ascii')
  19. except UnicodeError:
  20. return True
  21. return False
  22. class Generator:
  23. """Generates output from a Message object tree.
  24. This basic generator writes the message to the given file object as plain
  25. text.
  26. """
  27. #
  28. # Public interface
  29. #
  30. def __init__(self, outfp, mangle_from_=True, maxheaderlen=78):
  31. """Create the generator for message flattening.
  32. outfp is the output file-like object for writing the message to. It
  33. must have a write() method.
  34. Optional mangle_from_ is a flag that, when True (the default), escapes
  35. From_ lines in the body of the message by putting a `>' in front of
  36. them.
  37. Optional maxheaderlen specifies the longest length for a non-continued
  38. header. When a header line is longer (in characters, with tabs
  39. expanded to 8 spaces) than maxheaderlen, the header will split as
  40. defined in the Header class. Set maxheaderlen to zero to disable
  41. header wrapping. The default is 78, as recommended (but not required)
  42. by RFC 2822.
  43. """
  44. self._fp = outfp
  45. self._mangle_from_ = mangle_from_
  46. self._maxheaderlen = maxheaderlen
  47. def write(self, s):
  48. # Just delegate to the file object
  49. self._fp.write(s)
  50. def flatten(self, msg, unixfrom=False):
  51. """Print the message object tree rooted at msg to the output file
  52. specified when the Generator instance was created.
  53. unixfrom is a flag that forces the printing of a Unix From_ delimiter
  54. before the first object in the message tree. If the original message
  55. has no From_ delimiter, a `standard' one is crafted. By default, this
  56. is False to inhibit the printing of any From_ delimiter.
  57. Note that for subobjects, no From_ line is printed.
  58. """
  59. if unixfrom:
  60. ufrom = msg.get_unixfrom()
  61. if not ufrom:
  62. ufrom = 'From nobody ' + time.ctime(time.time())
  63. print >> self._fp, ufrom
  64. self._write(msg)
  65. def clone(self, fp):
  66. """Clone this generator with the exact same options."""
  67. return self.__class__(fp, self._mangle_from_, self._maxheaderlen)
  68. #
  69. # Protected interface - undocumented ;/
  70. #
  71. def _write(self, msg):
  72. # We can't write the headers yet because of the following scenario:
  73. # say a multipart message includes the boundary string somewhere in
  74. # its body. We'd have to calculate the new boundary /before/ we write
  75. # the headers so that we can write the correct Content-Type:
  76. # parameter.
  77. #
  78. # The way we do this, so as to make the _handle_*() methods simpler,
  79. # is to cache any subpart writes into a StringIO. The we write the
  80. # headers and the StringIO contents. That way, subpart handlers can
  81. # Do The Right Thing, and can still modify the Content-Type: header if
  82. # necessary.
  83. oldfp = self._fp
  84. try:
  85. self._fp = sfp = StringIO()
  86. self._dispatch(msg)
  87. finally:
  88. self._fp = oldfp
  89. # Write the headers. First we see if the message object wants to
  90. # handle that itself. If not, we'll do it generically.
  91. meth = getattr(msg, '_write_headers', None)
  92. if meth is None:
  93. self._write_headers(msg)
  94. else:
  95. meth(self)
  96. self._fp.write(sfp.getvalue())
  97. def _dispatch(self, msg):
  98. # Get the Content-Type: for the message, then try to dispatch to
  99. # self._handle_<maintype>_<subtype>(). If there's no handler for the
  100. # full MIME type, then dispatch to self._handle_<maintype>(). If
  101. # that's missing too, then dispatch to self._writeBody().
  102. main = msg.get_content_maintype()
  103. sub = msg.get_content_subtype()
  104. specific = UNDERSCORE.join((main, sub)).replace('-', '_')
  105. meth = getattr(self, '_handle_' + specific, None)
  106. if meth is None:
  107. generic = main.replace('-', '_')
  108. meth = getattr(self, '_handle_' + generic, None)
  109. if meth is None:
  110. meth = self._writeBody
  111. meth(msg)
  112. #
  113. # Default handlers
  114. #
  115. def _write_headers(self, msg):
  116. for h, v in msg.items():
  117. print >> self._fp, '%s:' % h,
  118. if self._maxheaderlen == 0:
  119. # Explicit no-wrapping
  120. print >> self._fp, v
  121. elif isinstance(v, Header):
  122. # Header instances know what to do
  123. print >> self._fp, v.encode()
  124. elif _is8bitstring(v):
  125. # If we have raw 8bit data in a byte string, we have no idea
  126. # what the encoding is. There is no safe way to split this
  127. # string. If it's ascii-subset, then we could do a normal
  128. # ascii split, but if it's multibyte then we could break the
  129. # string. There's no way to know so the least harm seems to
  130. # be to not split the string and risk it being too long.
  131. print >> self._fp, v
  132. else:
  133. # Header's got lots of smarts, so use it. Note that this is
  134. # fundamentally broken though because we lose idempotency when
  135. # the header string is continued with tabs. It will now be
  136. # continued with spaces. This was reversedly broken before we
  137. # fixed bug 1974. Either way, we lose.
  138. print >> self._fp, Header(
  139. v, maxlinelen=self._maxheaderlen, header_name=h).encode()
  140. # A blank line always separates headers from body
  141. print >> self._fp
  142. #
  143. # Handlers for writing types and subtypes
  144. #
  145. def _handle_text(self, msg):
  146. payload = msg.get_payload()
  147. if payload is None:
  148. return
  149. if not isinstance(payload, basestring):
  150. raise TypeError('string payload expected: %s' % type(payload))
  151. if self._mangle_from_:
  152. payload = fcre.sub('>From ', payload)
  153. self._fp.write(payload)
  154. # Default body handler
  155. _writeBody = _handle_text
  156. def _handle_multipart(self, msg):
  157. # The trick here is to write out each part separately, merge them all
  158. # together, and then make sure that the boundary we've chosen isn't
  159. # present in the payload.
  160. msgtexts = []
  161. subparts = msg.get_payload()
  162. if subparts is None:
  163. subparts = []
  164. elif isinstance(subparts, basestring):
  165. # e.g. a non-strict parse of a message with no starting boundary.
  166. self._fp.write(subparts)
  167. return
  168. elif not isinstance(subparts, list):
  169. # Scalar payload
  170. subparts = [subparts]
  171. for part in subparts:
  172. s = StringIO()
  173. g = self.clone(s)
  174. g.flatten(part, unixfrom=False)
  175. msgtexts.append(s.getvalue())
  176. # BAW: What about boundaries that are wrapped in double-quotes?
  177. boundary = msg.get_boundary()
  178. if not boundary:
  179. # Create a boundary that doesn't appear in any of the
  180. # message texts.
  181. alltext = NL.join(msgtexts)
  182. boundary = _make_boundary(alltext)
  183. msg.set_boundary(boundary)
  184. # If there's a preamble, write it out, with a trailing CRLF
  185. if msg.preamble is not None:
  186. if self._mangle_from_:
  187. preamble = fcre.sub('>From ', msg.preamble)
  188. else:
  189. preamble = msg.preamble
  190. print >> self._fp, preamble
  191. # dash-boundary transport-padding CRLF
  192. print >> self._fp, '--' + boundary
  193. # body-part
  194. if msgtexts:
  195. self._fp.write(msgtexts.pop(0))
  196. # *encapsulation
  197. # --> delimiter transport-padding
  198. # --> CRLF body-part
  199. for body_part in msgtexts:
  200. # delimiter transport-padding CRLF
  201. print >> self._fp, '\n--' + boundary
  202. # body-part
  203. self._fp.write(body_part)
  204. # close-delimiter transport-padding
  205. self._fp.write('\n--' + boundary + '--' + NL)
  206. if msg.epilogue is not None:
  207. if self._mangle_from_:
  208. epilogue = fcre.sub('>From ', msg.epilogue)
  209. else:
  210. epilogue = msg.epilogue
  211. self._fp.write(epilogue)
  212. def _handle_multipart_signed(self, msg):
  213. # The contents of signed parts has to stay unmodified in order to keep
  214. # the signature intact per RFC1847 2.1, so we disable header wrapping.
  215. # RDM: This isn't enough to completely preserve the part, but it helps.
  216. old_maxheaderlen = self._maxheaderlen
  217. try:
  218. self._maxheaderlen = 0
  219. self._handle_multipart(msg)
  220. finally:
  221. self._maxheaderlen = old_maxheaderlen
  222. def _handle_message_delivery_status(self, msg):
  223. # We can't just write the headers directly to self's file object
  224. # because this will leave an extra newline between the last header
  225. # block and the boundary. Sigh.
  226. blocks = []
  227. for part in msg.get_payload():
  228. s = StringIO()
  229. g = self.clone(s)
  230. g.flatten(part, unixfrom=False)
  231. text = s.getvalue()
  232. lines = text.split('\n')
  233. # Strip off the unnecessary trailing empty line
  234. if lines and lines[-1] == '':
  235. blocks.append(NL.join(lines[:-1]))
  236. else:
  237. blocks.append(text)
  238. # Now join all the blocks with an empty line. This has the lovely
  239. # effect of separating each block with an empty line, but not adding
  240. # an extra one after the last one.
  241. self._fp.write(NL.join(blocks))
  242. def _handle_message(self, msg):
  243. s = StringIO()
  244. g = self.clone(s)
  245. # The payload of a message/rfc822 part should be a multipart sequence
  246. # of length 1. The zeroth element of the list should be the Message
  247. # object for the subpart. Extract that object, stringify it, and
  248. # write it out.
  249. # Except, it turns out, when it's a string instead, which happens when
  250. # and only when HeaderParser is used on a message of mime type
  251. # message/rfc822. Such messages are generated by, for example,
  252. # Groupwise when forwarding unadorned messages. (Issue 7970.) So
  253. # in that case we just emit the string body.
  254. payload = msg.get_payload()
  255. if isinstance(payload, list):
  256. g.flatten(msg.get_payload(0), unixfrom=False)
  257. payload = s.getvalue()
  258. self._fp.write(payload)
  259. _FMT = '[Non-text (%(type)s) part of message omitted, filename %(filename)s]'
  260. class DecodedGenerator(Generator):
  261. """Generates a text representation of a message.
  262. Like the Generator base class, except that non-text parts are substituted
  263. with a format string representing the part.
  264. """
  265. def __init__(self, outfp, mangle_from_=True, maxheaderlen=78, fmt=None):
  266. """Like Generator.__init__() except that an additional optional
  267. argument is allowed.
  268. Walks through all subparts of a message. If the subpart is of main
  269. type `text', then it prints the decoded payload of the subpart.
  270. Otherwise, fmt is a format string that is used instead of the message
  271. payload. fmt is expanded with the following keywords (in
  272. %(keyword)s format):
  273. type : Full MIME type of the non-text part
  274. maintype : Main MIME type of the non-text part
  275. subtype : Sub-MIME type of the non-text part
  276. filename : Filename of the non-text part
  277. description: Description associated with the non-text part
  278. encoding : Content transfer encoding of the non-text part
  279. The default value for fmt is None, meaning
  280. [Non-text (%(type)s) part of message omitted, filename %(filename)s]
  281. """
  282. Generator.__init__(self, outfp, mangle_from_, maxheaderlen)
  283. if fmt is None:
  284. self._fmt = _FMT
  285. else:
  286. self._fmt = fmt
  287. def _dispatch(self, msg):
  288. for part in msg.walk():
  289. maintype = part.get_content_maintype()
  290. if maintype == 'text':
  291. print >> self, part.get_payload(decode=True)
  292. elif maintype == 'multipart':
  293. # Just skip this
  294. pass
  295. else:
  296. print >> self, self._fmt % {
  297. 'type' : part.get_content_type(),
  298. 'maintype' : part.get_content_maintype(),
  299. 'subtype' : part.get_content_subtype(),
  300. 'filename' : part.get_filename('[no filename]'),
  301. 'description': part.get('Content-Description',
  302. '[no description]'),
  303. 'encoding' : part.get('Content-Transfer-Encoding',
  304. '[no encoding]'),
  305. }
  306. # Helper
  307. _width = len(repr(sys.maxint-1))
  308. _fmt = '%%0%dd' % _width
  309. def _make_boundary(text=None):
  310. # Craft a random boundary. If text is given, ensure that the chosen
  311. # boundary doesn't appear in the text.
  312. token = random.randrange(sys.maxint)
  313. boundary = ('=' * 15) + (_fmt % token) + '=='
  314. if text is None:
  315. return boundary
  316. b = boundary
  317. counter = 0
  318. while True:
  319. cre = re.compile('^--' + re.escape(b) + '(--)?$', re.MULTILINE)
  320. if not cre.search(text):
  321. break
  322. b = boundary + '.' + str(counter)
  323. counter += 1
  324. return b