blob: 94320a2579b9b4fc24fbfcc15424501e2af72e2b [file] [log] [blame]
Barry Warsawe58df822006-02-08 14:34:21 +00001# Copyright (C) 2001-2006 Python Software Foundation
Barry Warsawbb113862004-10-03 03:16:19 +00002# Author: Barry Warsaw
3# Contact: email-sig@python.org
Barry Warsawba925802001-09-23 03:17:28 +00004
Barry Warsawbb113862004-10-03 03:16:19 +00005"""Classes to generate plain text from a message object tree."""
Barry Warsawba925802001-09-23 03:17:28 +00006
Barry Warsaw40ef0062006-03-18 15:41:53 +00007__all__ = ['Generator', 'DecodedGenerator']
8
Barry Warsawba925802001-09-23 03:17:28 +00009import re
Barry Warsawdb6888b2003-05-29 19:39:33 +000010import sys
Barry Warsaw5d384ef2003-03-06 05:22:02 +000011import time
Barry Warsawba925802001-09-23 03:17:28 +000012import random
Barry Warsawbb113862004-10-03 03:16:19 +000013import warnings
Barry Warsawba925802001-09-23 03:17:28 +000014
Barry Warsaw40ef0062006-03-18 15:41:53 +000015from cStringIO import StringIO
16from email.header import Header
Barry Warsaw062749a2002-06-28 23:41:42 +000017
Barry Warsawba925802001-09-23 03:17:28 +000018UNDERSCORE = '_'
19NL = '\n'
Barry Warsawba925802001-09-23 03:17:28 +000020
21fcre = re.compile(r'^From ', re.MULTILINE)
22
Barry Warsaw6c2bc462002-10-14 15:09:30 +000023def _is8bitstring(s):
Barry Warsaw36112f22004-05-09 03:35:17 +000024 if isinstance(s, str):
Barry Warsaw6c2bc462002-10-14 15:09:30 +000025 try:
26 unicode(s, 'us-ascii')
27 except UnicodeError:
28 return True
29 return False
30
Barry Warsawba925802001-09-23 03:17:28 +000031
Barry Warsawe968ead2001-10-04 17:05:11 +000032
Barry Warsawba925802001-09-23 03:17:28 +000033class Generator:
34 """Generates output from a Message object tree.
35
36 This basic generator writes the message to the given file object as plain
37 text.
38 """
39 #
40 # Public interface
41 #
42
Barry Warsaw56835dd2002-09-28 18:04:55 +000043 def __init__(self, outfp, mangle_from_=True, maxheaderlen=78):
Barry Warsawba925802001-09-23 03:17:28 +000044 """Create the generator for message flattening.
45
46 outfp is the output file-like object for writing the message to. It
47 must have a write() method.
48
Barry Warsaw56835dd2002-09-28 18:04:55 +000049 Optional mangle_from_ is a flag that, when True (the default), escapes
50 From_ lines in the body of the message by putting a `>' in front of
51 them.
Barry Warsawba925802001-09-23 03:17:28 +000052
53 Optional maxheaderlen specifies the longest length for a non-continued
54 header. When a header line is longer (in characters, with tabs
Barry Warsawb03136a2003-11-19 02:23:01 +000055 expanded to 8 spaces) than maxheaderlen, the header will split as
56 defined in the Header class. Set maxheaderlen to zero to disable
57 header wrapping. The default is 78, as recommended (but not required)
58 by RFC 2822.
Barry Warsawba925802001-09-23 03:17:28 +000059 """
60 self._fp = outfp
61 self._mangle_from_ = mangle_from_
Barry Warsaw36112f22004-05-09 03:35:17 +000062 self._maxheaderlen = maxheaderlen
Barry Warsawba925802001-09-23 03:17:28 +000063
64 def write(self, s):
65 # Just delegate to the file object
66 self._fp.write(s)
67
Barry Warsaw56835dd2002-09-28 18:04:55 +000068 def flatten(self, msg, unixfrom=False):
Barry Warsawba925802001-09-23 03:17:28 +000069 """Print the message object tree rooted at msg to the output file
70 specified when the Generator instance was created.
71
72 unixfrom is a flag that forces the printing of a Unix From_ delimiter
73 before the first object in the message tree. If the original message
74 has no From_ delimiter, a `standard' one is crafted. By default, this
Barry Warsaw56835dd2002-09-28 18:04:55 +000075 is False to inhibit the printing of any From_ delimiter.
Barry Warsawba925802001-09-23 03:17:28 +000076
77 Note that for subobjects, no From_ line is printed.
78 """
79 if unixfrom:
80 ufrom = msg.get_unixfrom()
81 if not ufrom:
82 ufrom = 'From nobody ' + time.ctime(time.time())
83 print >> self._fp, ufrom
84 self._write(msg)
85
Barry Warsaw93c40f02002-07-09 02:43:47 +000086 def clone(self, fp):
87 """Clone this generator with the exact same options."""
Barry Warsaw36112f22004-05-09 03:35:17 +000088 return self.__class__(fp, self._mangle_from_, self._maxheaderlen)
Barry Warsaw93c40f02002-07-09 02:43:47 +000089
Barry Warsawba925802001-09-23 03:17:28 +000090 #
91 # Protected interface - undocumented ;/
92 #
93
94 def _write(self, msg):
95 # We can't write the headers yet because of the following scenario:
96 # say a multipart message includes the boundary string somewhere in
97 # its body. We'd have to calculate the new boundary /before/ we write
98 # the headers so that we can write the correct Content-Type:
99 # parameter.
100 #
101 # The way we do this, so as to make the _handle_*() methods simpler,
102 # is to cache any subpart writes into a StringIO. The we write the
103 # headers and the StringIO contents. That way, subpart handlers can
104 # Do The Right Thing, and can still modify the Content-Type: header if
105 # necessary.
106 oldfp = self._fp
107 try:
108 self._fp = sfp = StringIO()
109 self._dispatch(msg)
110 finally:
111 self._fp = oldfp
112 # Write the headers. First we see if the message object wants to
113 # handle that itself. If not, we'll do it generically.
114 meth = getattr(msg, '_write_headers', None)
115 if meth is None:
116 self._write_headers(msg)
117 else:
118 meth(self)
119 self._fp.write(sfp.getvalue())
120
121 def _dispatch(self, msg):
122 # Get the Content-Type: for the message, then try to dispatch to
Barry Warsawf488b2c2002-07-11 18:48:40 +0000123 # self._handle_<maintype>_<subtype>(). If there's no handler for the
124 # full MIME type, then dispatch to self._handle_<maintype>(). If
125 # that's missing too, then dispatch to self._writeBody().
Barry Warsawdfea3b32002-08-20 14:47:30 +0000126 main = msg.get_content_maintype()
127 sub = msg.get_content_subtype()
Barry Warsaw93c40f02002-07-09 02:43:47 +0000128 specific = UNDERSCORE.join((main, sub)).replace('-', '_')
129 meth = getattr(self, '_handle_' + specific, None)
130 if meth is None:
131 generic = main.replace('-', '_')
132 meth = getattr(self, '_handle_' + generic, None)
Barry Warsawba925802001-09-23 03:17:28 +0000133 if meth is None:
Barry Warsaw93c40f02002-07-09 02:43:47 +0000134 meth = self._writeBody
135 meth(msg)
Barry Warsawba925802001-09-23 03:17:28 +0000136
137 #
138 # Default handlers
139 #
140
141 def _write_headers(self, msg):
142 for h, v in msg.items():
Barry Warsawce6bf592003-03-07 15:43:17 +0000143 print >> self._fp, '%s:' % h,
Barry Warsaw36112f22004-05-09 03:35:17 +0000144 if self._maxheaderlen == 0:
Barry Warsawce6bf592003-03-07 15:43:17 +0000145 # Explicit no-wrapping
146 print >> self._fp, v
147 elif isinstance(v, Header):
148 # Header instances know what to do
149 print >> self._fp, v.encode()
150 elif _is8bitstring(v):
151 # If we have raw 8bit data in a byte string, we have no idea
152 # what the encoding is. There is no safe way to split this
153 # string. If it's ascii-subset, then we could do a normal
154 # ascii split, but if it's multibyte then we could break the
155 # string. There's no way to know so the least harm seems to
156 # be to not split the string and risk it being too long.
157 print >> self._fp, v
158 else:
159 # Header's got lots of smarts, so use it.
160 print >> self._fp, Header(
Barry Warsaw36112f22004-05-09 03:35:17 +0000161 v, maxlinelen=self._maxheaderlen,
Barry Warsawce6bf592003-03-07 15:43:17 +0000162 header_name=h, continuation_ws='\t').encode()
Barry Warsawba925802001-09-23 03:17:28 +0000163 # A blank line always separates headers from body
164 print >> self._fp
165
Barry Warsawba925802001-09-23 03:17:28 +0000166 #
167 # Handlers for writing types and subtypes
168 #
169
170 def _handle_text(self, msg):
171 payload = msg.get_payload()
Barry Warsawb384e012001-09-26 05:32:41 +0000172 if payload is None:
173 return
Barry Warsaw36112f22004-05-09 03:35:17 +0000174 if not isinstance(payload, basestring):
Barry Warsawbb113862004-10-03 03:16:19 +0000175 raise TypeError('string payload expected: %s' % type(payload))
Barry Warsawba925802001-09-23 03:17:28 +0000176 if self._mangle_from_:
177 payload = fcre.sub('>From ', payload)
178 self._fp.write(payload)
179
180 # Default body handler
181 _writeBody = _handle_text
182
Barry Warsaw93c40f02002-07-09 02:43:47 +0000183 def _handle_multipart(self, msg):
Barry Warsawba925802001-09-23 03:17:28 +0000184 # The trick here is to write out each part separately, merge them all
185 # together, and then make sure that the boundary we've chosen isn't
186 # present in the payload.
187 msgtexts = []
Barry Warsaw409a4c02002-04-10 21:01:31 +0000188 subparts = msg.get_payload()
189 if subparts is None:
Barry Warsaw36112f22004-05-09 03:35:17 +0000190 subparts = []
191 elif isinstance(subparts, basestring):
Barry Warsawb1c1de32002-09-10 16:13:45 +0000192 # e.g. a non-strict parse of a message with no starting boundary.
193 self._fp.write(subparts)
194 return
Barry Warsaw36112f22004-05-09 03:35:17 +0000195 elif not isinstance(subparts, list):
Barry Warsaw409a4c02002-04-10 21:01:31 +0000196 # Scalar payload
197 subparts = [subparts]
198 for part in subparts:
Barry Warsawba925802001-09-23 03:17:28 +0000199 s = StringIO()
Barry Warsaw93c40f02002-07-09 02:43:47 +0000200 g = self.clone(s)
Barry Warsaw56835dd2002-09-28 18:04:55 +0000201 g.flatten(part, unixfrom=False)
Barry Warsawba925802001-09-23 03:17:28 +0000202 msgtexts.append(s.getvalue())
203 # Now make sure the boundary we've selected doesn't appear in any of
204 # the message texts.
205 alltext = NL.join(msgtexts)
206 # BAW: What about boundaries that are wrapped in double-quotes?
207 boundary = msg.get_boundary(failobj=_make_boundary(alltext))
208 # If we had to calculate a new boundary because the body text
209 # contained that string, set the new boundary. We don't do it
210 # unconditionally because, while set_boundary() preserves order, it
211 # doesn't preserve newlines/continuations in headers. This is no big
212 # deal in practice, but turns out to be inconvenient for the unittest
213 # suite.
Brett Cannon1f571c62008-08-03 23:27:32 +0000214 if msg.get_boundary() != boundary:
Barry Warsawba925802001-09-23 03:17:28 +0000215 msg.set_boundary(boundary)
Barry Warsaw36112f22004-05-09 03:35:17 +0000216 # If there's a preamble, write it out, with a trailing CRLF
Barry Warsawba925802001-09-23 03:17:28 +0000217 if msg.preamble is not None:
Barry Warsaw36112f22004-05-09 03:35:17 +0000218 print >> self._fp, msg.preamble
219 # dash-boundary transport-padding CRLF
Barry Warsawba925802001-09-23 03:17:28 +0000220 print >> self._fp, '--' + boundary
Barry Warsaw36112f22004-05-09 03:35:17 +0000221 # body-part
222 if msgtexts:
223 self._fp.write(msgtexts.pop(0))
224 # *encapsulation
225 # --> delimiter transport-padding
226 # --> CRLF body-part
227 for body_part in msgtexts:
228 # delimiter transport-padding CRLF
229 print >> self._fp, '\n--' + boundary
230 # body-part
231 self._fp.write(body_part)
232 # close-delimiter transport-padding
233 self._fp.write('\n--' + boundary + '--')
Barry Warsawba925802001-09-23 03:17:28 +0000234 if msg.epilogue is not None:
Barry Warsaw36112f22004-05-09 03:35:17 +0000235 print >> self._fp
Barry Warsawba925802001-09-23 03:17:28 +0000236 self._fp.write(msg.epilogue)
237
R. David Murray3cc61912010-01-16 16:32:39 +0000238 def _handle_multipart_signed(self, msg):
239 # The contents of signed parts has to stay unmodified in order to keep
240 # the signature intact per RFC1847 2.1, so we disable header wrapping.
241 # RDM: This isn't enough to completely preserve the part, but it helps.
242 old_maxheaderlen = self._maxheaderlen
243 try:
244 self._maxheaderlen = 0
245 self._handle_multipart(msg)
246 finally:
247 self._maxheaderlen = old_maxheaderlen
248
Barry Warsawb384e012001-09-26 05:32:41 +0000249 def _handle_message_delivery_status(self, msg):
250 # We can't just write the headers directly to self's file object
251 # because this will leave an extra newline between the last header
252 # block and the boundary. Sigh.
253 blocks = []
254 for part in msg.get_payload():
255 s = StringIO()
Barry Warsaw93c40f02002-07-09 02:43:47 +0000256 g = self.clone(s)
Barry Warsaw56835dd2002-09-28 18:04:55 +0000257 g.flatten(part, unixfrom=False)
Barry Warsawb384e012001-09-26 05:32:41 +0000258 text = s.getvalue()
259 lines = text.split('\n')
260 # Strip off the unnecessary trailing empty line
261 if lines and lines[-1] == '':
262 blocks.append(NL.join(lines[:-1]))
263 else:
264 blocks.append(text)
265 # Now join all the blocks with an empty line. This has the lovely
266 # effect of separating each block with an empty line, but not adding
267 # an extra one after the last one.
268 self._fp.write(NL.join(blocks))
269
270 def _handle_message(self, msg):
Barry Warsawba925802001-09-23 03:17:28 +0000271 s = StringIO()
Barry Warsaw93c40f02002-07-09 02:43:47 +0000272 g = self.clone(s)
Barry Warsaw7dc865a2002-06-02 19:02:37 +0000273 # The payload of a message/rfc822 part should be a multipart sequence
274 # of length 1. The zeroth element of the list should be the Message
Barry Warsaw93c40f02002-07-09 02:43:47 +0000275 # object for the subpart. Extract that object, stringify it, and
276 # write it out.
R. David Murray1fa91162010-02-21 04:30:12 +0000277 # Except, it turns out, when it's a string instead, which happens when
278 # and only when HeaderParser is used on a message of mime type
279 # message/rfc822. Such messages are generated by, for example,
280 # Groupwise when forwarding unadorned messages. (Issue 7970.) So
281 # in that case we just emit the string body.
282 payload = msg.get_payload()
283 if isinstance(payload, list):
284 g.flatten(msg.get_payload(0), unixfrom=False)
285 payload = s.getvalue()
286 self._fp.write(payload)
Barry Warsawba925802001-09-23 03:17:28 +0000287
288
Barry Warsawe968ead2001-10-04 17:05:11 +0000289
Barry Warsawbb113862004-10-03 03:16:19 +0000290_FMT = '[Non-text (%(type)s) part of message omitted, filename %(filename)s]'
291
Barry Warsawba925802001-09-23 03:17:28 +0000292class DecodedGenerator(Generator):
293 """Generator a text representation of a message.
294
295 Like the Generator base class, except that non-text parts are substituted
296 with a format string representing the part.
297 """
Barry Warsaw56835dd2002-09-28 18:04:55 +0000298 def __init__(self, outfp, mangle_from_=True, maxheaderlen=78, fmt=None):
Barry Warsawba925802001-09-23 03:17:28 +0000299 """Like Generator.__init__() except that an additional optional
300 argument is allowed.
301
302 Walks through all subparts of a message. If the subpart is of main
303 type `text', then it prints the decoded payload of the subpart.
304
305 Otherwise, fmt is a format string that is used instead of the message
306 payload. fmt is expanded with the following keywords (in
307 %(keyword)s format):
308
309 type : Full MIME type of the non-text part
310 maintype : Main MIME type of the non-text part
311 subtype : Sub-MIME type of the non-text part
312 filename : Filename of the non-text part
313 description: Description associated with the non-text part
314 encoding : Content transfer encoding of the non-text part
315
316 The default value for fmt is None, meaning
317
318 [Non-text (%(type)s) part of message omitted, filename %(filename)s]
319 """
320 Generator.__init__(self, outfp, mangle_from_, maxheaderlen)
321 if fmt is None:
Barry Warsawbb113862004-10-03 03:16:19 +0000322 self._fmt = _FMT
323 else:
324 self._fmt = fmt
Barry Warsawba925802001-09-23 03:17:28 +0000325
326 def _dispatch(self, msg):
327 for part in msg.walk():
Barry Warsawbb113862004-10-03 03:16:19 +0000328 maintype = part.get_content_maintype()
Barry Warsawb384e012001-09-26 05:32:41 +0000329 if maintype == 'text':
Barry Warsaw56835dd2002-09-28 18:04:55 +0000330 print >> self, part.get_payload(decode=True)
Barry Warsawb384e012001-09-26 05:32:41 +0000331 elif maintype == 'multipart':
332 # Just skip this
333 pass
Barry Warsawba925802001-09-23 03:17:28 +0000334 else:
335 print >> self, self._fmt % {
Barry Warsawbb113862004-10-03 03:16:19 +0000336 'type' : part.get_content_type(),
337 'maintype' : part.get_content_maintype(),
338 'subtype' : part.get_content_subtype(),
Barry Warsawba925802001-09-23 03:17:28 +0000339 'filename' : part.get_filename('[no filename]'),
340 'description': part.get('Content-Description',
341 '[no description]'),
342 'encoding' : part.get('Content-Transfer-Encoding',
343 '[no encoding]'),
344 }
345
346
Barry Warsawe968ead2001-10-04 17:05:11 +0000347
Barry Warsawba925802001-09-23 03:17:28 +0000348# Helper
Barry Warsawdb6888b2003-05-29 19:39:33 +0000349_width = len(repr(sys.maxint-1))
350_fmt = '%%0%dd' % _width
351
Barry Warsaw409a4c02002-04-10 21:01:31 +0000352def _make_boundary(text=None):
Barry Warsawba925802001-09-23 03:17:28 +0000353 # Craft a random boundary. If text is given, ensure that the chosen
354 # boundary doesn't appear in the text.
Barry Warsaw663219a2003-06-24 20:19:34 +0000355 token = random.randrange(sys.maxint)
Barry Warsawdb6888b2003-05-29 19:39:33 +0000356 boundary = ('=' * 15) + (_fmt % token) + '=='
Barry Warsawba925802001-09-23 03:17:28 +0000357 if text is None:
358 return boundary
359 b = boundary
360 counter = 0
Barry Warsaw56835dd2002-09-28 18:04:55 +0000361 while True:
Barry Warsawba925802001-09-23 03:17:28 +0000362 cre = re.compile('^--' + re.escape(b) + '(--)?$', re.MULTILINE)
363 if not cre.search(text):
364 break
365 b = boundary + '.' + str(counter)
366 counter += 1
367 return b