blob: 7969916ff96d997fe927cae125e2c759801fd8a4 [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 Warsawba925802001-09-23 03:17:28 +00007import re
Barry Warsawdb6888b2003-05-29 19:39:33 +00008import sys
Barry Warsaw5d384ef2003-03-06 05:22:02 +00009import time
Barry Warsawba925802001-09-23 03:17:28 +000010import random
Barry Warsawbb113862004-10-03 03:16:19 +000011import warnings
Barry Warsawba925802001-09-23 03:17:28 +000012from cStringIO import StringIO
13
Barry Warsaw062749a2002-06-28 23:41:42 +000014from email.Header import Header
15
Barry Warsawba925802001-09-23 03:17:28 +000016UNDERSCORE = '_'
17NL = '\n'
Barry Warsawba925802001-09-23 03:17:28 +000018
19fcre = re.compile(r'^From ', re.MULTILINE)
20
Barry Warsaw6c2bc462002-10-14 15:09:30 +000021def _is8bitstring(s):
Barry Warsaw36112f22004-05-09 03:35:17 +000022 if isinstance(s, str):
Barry Warsaw6c2bc462002-10-14 15:09:30 +000023 try:
24 unicode(s, 'us-ascii')
25 except UnicodeError:
26 return True
27 return False
28
Barry Warsawba925802001-09-23 03:17:28 +000029
Barry Warsawe968ead2001-10-04 17:05:11 +000030
Barry Warsawba925802001-09-23 03:17:28 +000031class Generator:
32 """Generates output from a Message object tree.
33
34 This basic generator writes the message to the given file object as plain
35 text.
36 """
37 #
38 # Public interface
39 #
40
Barry Warsaw56835dd2002-09-28 18:04:55 +000041 def __init__(self, outfp, mangle_from_=True, maxheaderlen=78):
Barry Warsawba925802001-09-23 03:17:28 +000042 """Create the generator for message flattening.
43
44 outfp is the output file-like object for writing the message to. It
45 must have a write() method.
46
Barry Warsaw56835dd2002-09-28 18:04:55 +000047 Optional mangle_from_ is a flag that, when True (the default), escapes
48 From_ lines in the body of the message by putting a `>' in front of
49 them.
Barry Warsawba925802001-09-23 03:17:28 +000050
51 Optional maxheaderlen specifies the longest length for a non-continued
52 header. When a header line is longer (in characters, with tabs
Barry Warsawb03136a2003-11-19 02:23:01 +000053 expanded to 8 spaces) than maxheaderlen, the header will split as
54 defined in the Header class. Set maxheaderlen to zero to disable
55 header wrapping. The default is 78, as recommended (but not required)
56 by RFC 2822.
Barry Warsawba925802001-09-23 03:17:28 +000057 """
58 self._fp = outfp
59 self._mangle_from_ = mangle_from_
Barry Warsaw36112f22004-05-09 03:35:17 +000060 self._maxheaderlen = maxheaderlen
Barry Warsawba925802001-09-23 03:17:28 +000061
62 def write(self, s):
63 # Just delegate to the file object
64 self._fp.write(s)
65
Barry Warsaw56835dd2002-09-28 18:04:55 +000066 def flatten(self, msg, unixfrom=False):
Barry Warsawba925802001-09-23 03:17:28 +000067 """Print the message object tree rooted at msg to the output file
68 specified when the Generator instance was created.
69
70 unixfrom is a flag that forces the printing of a Unix From_ delimiter
71 before the first object in the message tree. If the original message
72 has no From_ delimiter, a `standard' one is crafted. By default, this
Barry Warsaw56835dd2002-09-28 18:04:55 +000073 is False to inhibit the printing of any From_ delimiter.
Barry Warsawba925802001-09-23 03:17:28 +000074
75 Note that for subobjects, no From_ line is printed.
76 """
77 if unixfrom:
78 ufrom = msg.get_unixfrom()
79 if not ufrom:
80 ufrom = 'From nobody ' + time.ctime(time.time())
81 print >> self._fp, ufrom
82 self._write(msg)
83
Barry Warsaw7dc865a2002-06-02 19:02:37 +000084 # For backwards compatibility, but this is slower
Barry Warsawbb113862004-10-03 03:16:19 +000085 def __call__(self, msg, unixfrom=False):
86 warnings.warn('__call__() deprecated; use flatten()',
87 DeprecationWarning, 2)
88 self.flatten(msg, unixfrom)
Barry Warsaw7dc865a2002-06-02 19:02:37 +000089
Barry Warsaw93c40f02002-07-09 02:43:47 +000090 def clone(self, fp):
91 """Clone this generator with the exact same options."""
Barry Warsaw36112f22004-05-09 03:35:17 +000092 return self.__class__(fp, self._mangle_from_, self._maxheaderlen)
Barry Warsaw93c40f02002-07-09 02:43:47 +000093
Barry Warsawba925802001-09-23 03:17:28 +000094 #
95 # Protected interface - undocumented ;/
96 #
97
98 def _write(self, msg):
99 # We can't write the headers yet because of the following scenario:
100 # say a multipart message includes the boundary string somewhere in
101 # its body. We'd have to calculate the new boundary /before/ we write
102 # the headers so that we can write the correct Content-Type:
103 # parameter.
104 #
105 # The way we do this, so as to make the _handle_*() methods simpler,
106 # is to cache any subpart writes into a StringIO. The we write the
107 # headers and the StringIO contents. That way, subpart handlers can
108 # Do The Right Thing, and can still modify the Content-Type: header if
109 # necessary.
110 oldfp = self._fp
111 try:
112 self._fp = sfp = StringIO()
113 self._dispatch(msg)
114 finally:
115 self._fp = oldfp
116 # Write the headers. First we see if the message object wants to
117 # handle that itself. If not, we'll do it generically.
118 meth = getattr(msg, '_write_headers', None)
119 if meth is None:
120 self._write_headers(msg)
121 else:
122 meth(self)
123 self._fp.write(sfp.getvalue())
124
125 def _dispatch(self, msg):
126 # Get the Content-Type: for the message, then try to dispatch to
Barry Warsawf488b2c2002-07-11 18:48:40 +0000127 # self._handle_<maintype>_<subtype>(). If there's no handler for the
128 # full MIME type, then dispatch to self._handle_<maintype>(). If
129 # that's missing too, then dispatch to self._writeBody().
Barry Warsawdfea3b32002-08-20 14:47:30 +0000130 main = msg.get_content_maintype()
131 sub = msg.get_content_subtype()
Barry Warsaw93c40f02002-07-09 02:43:47 +0000132 specific = UNDERSCORE.join((main, sub)).replace('-', '_')
133 meth = getattr(self, '_handle_' + specific, None)
134 if meth is None:
135 generic = main.replace('-', '_')
136 meth = getattr(self, '_handle_' + generic, None)
Barry Warsawba925802001-09-23 03:17:28 +0000137 if meth is None:
Barry Warsaw93c40f02002-07-09 02:43:47 +0000138 meth = self._writeBody
139 meth(msg)
Barry Warsawba925802001-09-23 03:17:28 +0000140
141 #
142 # Default handlers
143 #
144
145 def _write_headers(self, msg):
146 for h, v in msg.items():
Barry Warsawce6bf592003-03-07 15:43:17 +0000147 print >> self._fp, '%s:' % h,
Barry Warsaw36112f22004-05-09 03:35:17 +0000148 if self._maxheaderlen == 0:
Barry Warsawce6bf592003-03-07 15:43:17 +0000149 # Explicit no-wrapping
150 print >> self._fp, v
151 elif isinstance(v, Header):
152 # Header instances know what to do
153 print >> self._fp, v.encode()
154 elif _is8bitstring(v):
155 # If we have raw 8bit data in a byte string, we have no idea
156 # what the encoding is. There is no safe way to split this
157 # string. If it's ascii-subset, then we could do a normal
158 # ascii split, but if it's multibyte then we could break the
159 # string. There's no way to know so the least harm seems to
160 # be to not split the string and risk it being too long.
161 print >> self._fp, v
162 else:
163 # Header's got lots of smarts, so use it.
164 print >> self._fp, Header(
Barry Warsaw36112f22004-05-09 03:35:17 +0000165 v, maxlinelen=self._maxheaderlen,
Barry Warsawce6bf592003-03-07 15:43:17 +0000166 header_name=h, continuation_ws='\t').encode()
Barry Warsawba925802001-09-23 03:17:28 +0000167 # A blank line always separates headers from body
168 print >> self._fp
169
Barry Warsawba925802001-09-23 03:17:28 +0000170 #
171 # Handlers for writing types and subtypes
172 #
173
174 def _handle_text(self, msg):
175 payload = msg.get_payload()
Barry Warsawb384e012001-09-26 05:32:41 +0000176 if payload is None:
177 return
Barry Warsaw36112f22004-05-09 03:35:17 +0000178 if not isinstance(payload, basestring):
Barry Warsawbb113862004-10-03 03:16:19 +0000179 raise TypeError('string payload expected: %s' % type(payload))
Barry Warsawba925802001-09-23 03:17:28 +0000180 if self._mangle_from_:
181 payload = fcre.sub('>From ', payload)
182 self._fp.write(payload)
183
184 # Default body handler
185 _writeBody = _handle_text
186
Barry Warsaw93c40f02002-07-09 02:43:47 +0000187 def _handle_multipart(self, msg):
Barry Warsawba925802001-09-23 03:17:28 +0000188 # The trick here is to write out each part separately, merge them all
189 # together, and then make sure that the boundary we've chosen isn't
190 # present in the payload.
191 msgtexts = []
Barry Warsaw409a4c02002-04-10 21:01:31 +0000192 subparts = msg.get_payload()
193 if subparts is None:
Barry Warsaw36112f22004-05-09 03:35:17 +0000194 subparts = []
195 elif isinstance(subparts, basestring):
Barry Warsawb1c1de32002-09-10 16:13:45 +0000196 # e.g. a non-strict parse of a message with no starting boundary.
197 self._fp.write(subparts)
198 return
Barry Warsaw36112f22004-05-09 03:35:17 +0000199 elif not isinstance(subparts, list):
Barry Warsaw409a4c02002-04-10 21:01:31 +0000200 # Scalar payload
201 subparts = [subparts]
202 for part in subparts:
Barry Warsawba925802001-09-23 03:17:28 +0000203 s = StringIO()
Barry Warsaw93c40f02002-07-09 02:43:47 +0000204 g = self.clone(s)
Barry Warsaw56835dd2002-09-28 18:04:55 +0000205 g.flatten(part, unixfrom=False)
Barry Warsawba925802001-09-23 03:17:28 +0000206 msgtexts.append(s.getvalue())
207 # Now make sure the boundary we've selected doesn't appear in any of
208 # the message texts.
209 alltext = NL.join(msgtexts)
210 # BAW: What about boundaries that are wrapped in double-quotes?
211 boundary = msg.get_boundary(failobj=_make_boundary(alltext))
212 # If we had to calculate a new boundary because the body text
213 # contained that string, set the new boundary. We don't do it
214 # unconditionally because, while set_boundary() preserves order, it
215 # doesn't preserve newlines/continuations in headers. This is no big
216 # deal in practice, but turns out to be inconvenient for the unittest
217 # suite.
218 if msg.get_boundary() <> boundary:
219 msg.set_boundary(boundary)
Barry Warsaw36112f22004-05-09 03:35:17 +0000220 # If there's a preamble, write it out, with a trailing CRLF
Barry Warsawba925802001-09-23 03:17:28 +0000221 if msg.preamble is not None:
Barry Warsaw36112f22004-05-09 03:35:17 +0000222 print >> self._fp, msg.preamble
223 # dash-boundary transport-padding CRLF
Barry Warsawba925802001-09-23 03:17:28 +0000224 print >> self._fp, '--' + boundary
Barry Warsaw36112f22004-05-09 03:35:17 +0000225 # body-part
226 if msgtexts:
227 self._fp.write(msgtexts.pop(0))
228 # *encapsulation
229 # --> delimiter transport-padding
230 # --> CRLF body-part
231 for body_part in msgtexts:
232 # delimiter transport-padding CRLF
233 print >> self._fp, '\n--' + boundary
234 # body-part
235 self._fp.write(body_part)
236 # close-delimiter transport-padding
237 self._fp.write('\n--' + boundary + '--')
Barry Warsawba925802001-09-23 03:17:28 +0000238 if msg.epilogue is not None:
Barry Warsaw36112f22004-05-09 03:35:17 +0000239 print >> self._fp
Barry Warsawba925802001-09-23 03:17:28 +0000240 self._fp.write(msg.epilogue)
241
Barry Warsawb384e012001-09-26 05:32:41 +0000242 def _handle_message_delivery_status(self, msg):
243 # We can't just write the headers directly to self's file object
244 # because this will leave an extra newline between the last header
245 # block and the boundary. Sigh.
246 blocks = []
247 for part in msg.get_payload():
248 s = StringIO()
Barry Warsaw93c40f02002-07-09 02:43:47 +0000249 g = self.clone(s)
Barry Warsaw56835dd2002-09-28 18:04:55 +0000250 g.flatten(part, unixfrom=False)
Barry Warsawb384e012001-09-26 05:32:41 +0000251 text = s.getvalue()
252 lines = text.split('\n')
253 # Strip off the unnecessary trailing empty line
254 if lines and lines[-1] == '':
255 blocks.append(NL.join(lines[:-1]))
256 else:
257 blocks.append(text)
258 # Now join all the blocks with an empty line. This has the lovely
259 # effect of separating each block with an empty line, but not adding
260 # an extra one after the last one.
261 self._fp.write(NL.join(blocks))
262
263 def _handle_message(self, msg):
Barry Warsawba925802001-09-23 03:17:28 +0000264 s = StringIO()
Barry Warsaw93c40f02002-07-09 02:43:47 +0000265 g = self.clone(s)
Barry Warsaw7dc865a2002-06-02 19:02:37 +0000266 # The payload of a message/rfc822 part should be a multipart sequence
267 # of length 1. The zeroth element of the list should be the Message
Barry Warsaw93c40f02002-07-09 02:43:47 +0000268 # object for the subpart. Extract that object, stringify it, and
269 # write it out.
Barry Warsaw56835dd2002-09-28 18:04:55 +0000270 g.flatten(msg.get_payload(0), unixfrom=False)
Barry Warsawba925802001-09-23 03:17:28 +0000271 self._fp.write(s.getvalue())
272
273
Barry Warsawe968ead2001-10-04 17:05:11 +0000274
Barry Warsawbb113862004-10-03 03:16:19 +0000275_FMT = '[Non-text (%(type)s) part of message omitted, filename %(filename)s]'
276
Barry Warsawba925802001-09-23 03:17:28 +0000277class DecodedGenerator(Generator):
278 """Generator a text representation of a message.
279
280 Like the Generator base class, except that non-text parts are substituted
281 with a format string representing the part.
282 """
Barry Warsaw56835dd2002-09-28 18:04:55 +0000283 def __init__(self, outfp, mangle_from_=True, maxheaderlen=78, fmt=None):
Barry Warsawba925802001-09-23 03:17:28 +0000284 """Like Generator.__init__() except that an additional optional
285 argument is allowed.
286
287 Walks through all subparts of a message. If the subpart is of main
288 type `text', then it prints the decoded payload of the subpart.
289
290 Otherwise, fmt is a format string that is used instead of the message
291 payload. fmt is expanded with the following keywords (in
292 %(keyword)s format):
293
294 type : Full MIME type of the non-text part
295 maintype : Main MIME type of the non-text part
296 subtype : Sub-MIME type of the non-text part
297 filename : Filename of the non-text part
298 description: Description associated with the non-text part
299 encoding : Content transfer encoding of the non-text part
300
301 The default value for fmt is None, meaning
302
303 [Non-text (%(type)s) part of message omitted, filename %(filename)s]
304 """
305 Generator.__init__(self, outfp, mangle_from_, maxheaderlen)
306 if fmt is None:
Barry Warsawbb113862004-10-03 03:16:19 +0000307 self._fmt = _FMT
308 else:
309 self._fmt = fmt
Barry Warsawba925802001-09-23 03:17:28 +0000310
311 def _dispatch(self, msg):
312 for part in msg.walk():
Barry Warsawbb113862004-10-03 03:16:19 +0000313 maintype = part.get_content_maintype()
Barry Warsawb384e012001-09-26 05:32:41 +0000314 if maintype == 'text':
Barry Warsaw56835dd2002-09-28 18:04:55 +0000315 print >> self, part.get_payload(decode=True)
Barry Warsawb384e012001-09-26 05:32:41 +0000316 elif maintype == 'multipart':
317 # Just skip this
318 pass
Barry Warsawba925802001-09-23 03:17:28 +0000319 else:
320 print >> self, self._fmt % {
Barry Warsawbb113862004-10-03 03:16:19 +0000321 'type' : part.get_content_type(),
322 'maintype' : part.get_content_maintype(),
323 'subtype' : part.get_content_subtype(),
Barry Warsawba925802001-09-23 03:17:28 +0000324 'filename' : part.get_filename('[no filename]'),
325 'description': part.get('Content-Description',
326 '[no description]'),
327 'encoding' : part.get('Content-Transfer-Encoding',
328 '[no encoding]'),
329 }
330
331
Barry Warsawe968ead2001-10-04 17:05:11 +0000332
Barry Warsawba925802001-09-23 03:17:28 +0000333# Helper
Barry Warsawdb6888b2003-05-29 19:39:33 +0000334_width = len(repr(sys.maxint-1))
335_fmt = '%%0%dd' % _width
336
Barry Warsaw409a4c02002-04-10 21:01:31 +0000337def _make_boundary(text=None):
Barry Warsawba925802001-09-23 03:17:28 +0000338 # Craft a random boundary. If text is given, ensure that the chosen
339 # boundary doesn't appear in the text.
Barry Warsaw663219a2003-06-24 20:19:34 +0000340 token = random.randrange(sys.maxint)
Barry Warsawdb6888b2003-05-29 19:39:33 +0000341 boundary = ('=' * 15) + (_fmt % token) + '=='
Barry Warsawba925802001-09-23 03:17:28 +0000342 if text is None:
343 return boundary
344 b = boundary
345 counter = 0
Barry Warsaw56835dd2002-09-28 18:04:55 +0000346 while True:
Barry Warsawba925802001-09-23 03:17:28 +0000347 cre = re.compile('^--' + re.escape(b) + '(--)?$', re.MULTILINE)
348 if not cre.search(text):
349 break
350 b = boundary + '.' + str(counter)
351 counter += 1
352 return b