1 # Copyright (C) 2001 Python Software Foundation
2 # Author: barry@zope.com (Barry Warsaw)
4 """Classes to generate plain text from a message object tree.
11 from types
import ListType
, StringType
12 from cStringIO
import StringIO
14 # Intrapackage imports
27 fcre
= re
.compile(r
'^From ', re
.MULTILINE
)
32 """Generates output from a Message object tree.
34 This basic generator writes the message to the given file object as plain
41 def __init__(self
, outfp
, mangle_from_
=1, maxheaderlen
=78):
42 """Create the generator for message flattening.
44 outfp is the output file-like object for writing the message to. It
45 must have a write() method.
47 Optional mangle_from_ is a flag that, when true, escapes From_ lines
48 in the body of the message by putting a `>' in front of them.
50 Optional maxheaderlen specifies the longest length for a non-continued
51 header. When a header line is longer (in characters, with tabs
52 expanded to 8 spaces), than maxheaderlen, the header will be broken on
53 semicolons and continued as per RFC 2822. If no semicolon is found,
54 then the header is left alone. Set to zero to disable wrapping
55 headers. Default is 78, as recommended (but not required by RFC
59 self
._mangle
_from
_ = mangle_from_
61 self
.__maxheaderlen
= maxheaderlen
64 # Just delegate to the file object
67 def __call__(self
, msg
, unixfrom
=0):
68 """Print the message object tree rooted at msg to the output file
69 specified when the Generator instance was created.
71 unixfrom is a flag that forces the printing of a Unix From_ delimiter
72 before the first object in the message tree. If the original message
73 has no From_ delimiter, a `standard' one is crafted. By default, this
74 is 0 to inhibit the printing of any From_ delimiter.
76 Note that for subobjects, no From_ line is printed.
79 ufrom
= msg
.get_unixfrom()
81 ufrom
= 'From nobody ' + time
.ctime(time
.time())
82 print >> self
._fp
, ufrom
86 # Protected interface - undocumented ;/
89 def _write(self
, msg
):
90 # We can't write the headers yet because of the following scenario:
91 # say a multipart message includes the boundary string somewhere in
92 # its body. We'd have to calculate the new boundary /before/ we write
93 # the headers so that we can write the correct Content-Type:
96 # The way we do this, so as to make the _handle_*() methods simpler,
97 # is to cache any subpart writes into a StringIO. The we write the
98 # headers and the StringIO contents. That way, subpart handlers can
99 # Do The Right Thing, and can still modify the Content-Type: header if
103 self
._fp
= sfp
= StringIO()
107 # Write the headers. First we see if the message object wants to
108 # handle that itself. If not, we'll do it generically.
109 meth
= getattr(msg
, '_write_headers', None)
111 self
._write
_headers
(msg
)
114 self
._fp
.write(sfp
.getvalue())
116 def _dispatch(self
, msg
):
117 # Get the Content-Type: for the message, then try to dispatch to
118 # self._handle_maintype_subtype(). If there's no handler for the full
119 # MIME type, then dispatch to self._handle_maintype(). If that's
120 # missing too, then dispatch to self._writeBody().
121 ctype
= msg
.get_type()
123 # No Content-Type: header so try the default handler
126 # We do have a Content-Type: header.
127 specific
= UNDERSCORE
.join(ctype
.split('/')).replace('-', '_')
128 meth
= getattr(self
, '_handle_' + specific
, None)
130 generic
= msg
.get_main_type().replace('-', '_')
131 meth
= getattr(self
, '_handle_' + generic
, None)
133 meth
= self
._writeBody
140 def _write_headers(self
, msg
):
141 for h
, v
in msg
.items():
142 # We only write the MIME-Version: header for the outermost
143 # container message. Unfortunately, we can't use same technique
144 # as for the Unix-From above because we don't know when
145 # MIME-Version: will occur.
146 if h
.lower() == 'mime-version' and not self
.__first
:
148 # RFC 2822 says that lines SHOULD be no more than maxheaderlen
149 # characters wide, so we're well within our rights to split long
151 text
= '%s: %s' % (h
, v
)
152 if self
.__maxheaderlen
> 0 and len(text
) > self
.__maxheaderlen
:
153 text
= self
._split
_header
(text
)
154 print >> self
._fp
, text
155 # A blank line always separates headers from body
158 def _split_header(self
, text
):
159 maxheaderlen
= self
.__maxheaderlen
160 # Find out whether any lines in the header are really longer than
161 # maxheaderlen characters wide. There could be continuation lines
162 # that actually shorten it. Also, replace hard tabs with 8 spaces.
163 lines
= [s
.replace('\t', SPACE8
) for s
in text
.split('\n')]
165 if len(line
) > maxheaderlen
:
168 # No line was actually longer than maxheaderlen characters, so
169 # just return the original unchanged.
172 for line
in text
.split('\n'):
173 # Short lines can remain unchanged
174 if len(line
.replace('\t', SPACE8
)) <= maxheaderlen
:
179 # Try to break the line on semicolons, but if that doesn't
180 # work, try to split on folding whitespace.
181 while len(text
) > maxheaderlen
:
182 i
= text
.rfind(';', 0, maxheaderlen
)
186 text
= text
[i
+1:].lstrip()
187 if len(text
) <> oldlen
:
188 # Splitting on semis worked
190 return SEMINLTAB
.join(rtn
)
191 # Splitting on semis didn't help, so try to split on
193 parts
= re
.split(r
'(\s+)', text
)
194 # Watch out though for "Header: longnonsplittableline"
195 if parts
[0].endswith(':') and len(parts
) == 3:
203 if acc
+ len0
+ len1
< maxheaderlen
:
204 sublines
.append(parts
.pop(0))
205 sublines
.append(parts
.pop(0))
208 # Split it here, but don't forget to ignore the
209 # next whitespace-only part
210 rtn
.append(EMPTYSTRING
.join(sublines
))
215 rtn
.append(EMPTYSTRING
.join(sublines
))
216 return NLTAB
.join(rtn
)
219 # Handlers for writing types and subtypes
222 def _handle_text(self
, msg
):
223 payload
= msg
.get_payload()
226 if not isinstance(payload
, StringType
):
227 raise TypeError, 'string payload expected: %s' % type(payload
)
228 if self
._mangle
_from
_:
229 payload
= fcre
.sub('>From ', payload
)
230 self
._fp
.write(payload
)
232 # Default body handler
233 _writeBody
= _handle_text
235 def _handle_multipart(self
, msg
, isdigest
=0):
236 # The trick here is to write out each part separately, merge them all
237 # together, and then make sure that the boundary we've chosen isn't
238 # present in the payload.
240 # BAW: kludge for broken add_payload() semantics; watch out for
241 # multipart/* MIME types with None or scalar payloads.
242 subparts
= msg
.get_payload()
244 # Nothing has every been attached
245 boundary
= msg
.get_boundary(failobj
=_make_boundary())
246 print >> self
._fp
, '--' + boundary
247 print >> self
._fp
, '\n'
248 print >> self
._fp
, '--' + boundary
+ '--'
250 elif not isinstance(subparts
, ListType
):
252 subparts
= [subparts
]
253 for part
in subparts
:
255 g
= self
.__class
__(s
, self
._mangle
_from
_, self
.__maxheaderlen
)
257 msgtexts
.append(s
.getvalue())
258 # Now make sure the boundary we've selected doesn't appear in any of
260 alltext
= NL
.join(msgtexts
)
261 # BAW: What about boundaries that are wrapped in double-quotes?
262 boundary
= msg
.get_boundary(failobj
=_make_boundary(alltext
))
263 # If we had to calculate a new boundary because the body text
264 # contained that string, set the new boundary. We don't do it
265 # unconditionally because, while set_boundary() preserves order, it
266 # doesn't preserve newlines/continuations in headers. This is no big
267 # deal in practice, but turns out to be inconvenient for the unittest
269 if msg
.get_boundary() <> boundary
:
270 msg
.set_boundary(boundary
)
271 # Write out any preamble
272 if msg
.preamble
is not None:
273 self
._fp
.write(msg
.preamble
)
274 # First boundary is a bit different; it doesn't have a leading extra
276 print >> self
._fp
, '--' + boundary
279 # Join and write the individual parts
280 joiner
= '\n--' + boundary
+ '\n'
282 # multipart/digest types effectively add an extra newline between
283 # the boundary and the body part.
285 self
._fp
.write(joiner
.join(msgtexts
))
286 print >> self
._fp
, '\n--' + boundary
+ '--',
287 # Write out any epilogue
288 if msg
.epilogue
is not None:
289 if not msg
.epilogue
.startswith('\n'):
291 self
._fp
.write(msg
.epilogue
)
293 def _handle_multipart_digest(self
, msg
):
294 self
._handle
_multipart
(msg
, isdigest
=1)
296 def _handle_message_delivery_status(self
, msg
):
297 # We can't just write the headers directly to self's file object
298 # because this will leave an extra newline between the last header
299 # block and the boundary. Sigh.
301 for part
in msg
.get_payload():
303 g
= self
.__class
__(s
, self
._mangle
_from
_, self
.__maxheaderlen
)
306 lines
= text
.split('\n')
307 # Strip off the unnecessary trailing empty line
308 if lines
and lines
[-1] == '':
309 blocks
.append(NL
.join(lines
[:-1]))
312 # Now join all the blocks with an empty line. This has the lovely
313 # effect of separating each block with an empty line, but not adding
314 # an extra one after the last one.
315 self
._fp
.write(NL
.join(blocks
))
317 def _handle_message(self
, msg
):
319 g
= self
.__class
__(s
, self
._mangle
_from
_, self
.__maxheaderlen
)
320 # A message/rfc822 should contain a scalar payload which is another
321 # Message object. Extract that object, stringify it, and write that
323 g(msg
.get_payload(), unixfrom
=0)
324 self
._fp
.write(s
.getvalue())
328 class DecodedGenerator(Generator
):
329 """Generator a text representation of a message.
331 Like the Generator base class, except that non-text parts are substituted
332 with a format string representing the part.
334 def __init__(self
, outfp
, mangle_from_
=1, maxheaderlen
=78, fmt
=None):
335 """Like Generator.__init__() except that an additional optional
338 Walks through all subparts of a message. If the subpart is of main
339 type `text', then it prints the decoded payload of the subpart.
341 Otherwise, fmt is a format string that is used instead of the message
342 payload. fmt is expanded with the following keywords (in
345 type : Full MIME type of the non-text part
346 maintype : Main MIME type of the non-text part
347 subtype : Sub-MIME type of the non-text part
348 filename : Filename of the non-text part
349 description: Description associated with the non-text part
350 encoding : Content transfer encoding of the non-text part
352 The default value for fmt is None, meaning
354 [Non-text (%(type)s) part of message omitted, filename %(filename)s]
356 Generator
.__init
__(self
, outfp
, mangle_from_
, maxheaderlen
)
358 fmt
= ('[Non-text (%(type)s) part of message omitted, '
359 'filename %(filename)s]')
362 def _dispatch(self
, msg
):
363 for part
in msg
.walk():
364 maintype
= part
.get_main_type('text')
365 if maintype
== 'text':
366 print >> self
, part
.get_payload(decode
=1)
367 elif maintype
== 'multipart':
371 print >> self
, self
._fmt
% {
372 'type' : part
.get_type('[no MIME type]'),
373 'maintype' : part
.get_main_type('[no main MIME type]'),
374 'subtype' : part
.get_subtype('[no sub-MIME type]'),
375 'filename' : part
.get_filename('[no filename]'),
376 'description': part
.get('Content-Description',
378 'encoding' : part
.get('Content-Transfer-Encoding',
385 def _make_boundary(text
=None):
386 # Craft a random boundary. If text is given, ensure that the chosen
387 # boundary doesn't appear in the text.
388 boundary
= ('=' * 15) + repr(random
.random()).split('.')[1] + '=='
394 cre
= re
.compile('^--' + re
.escape(b
) + '(--)?$', re
.MULTILINE
)
395 if not cre
.search(text
):
397 b
= boundary
+ '.' + str(counter
)