1 # Copyright (C) 2001,2002 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 from email
.Header
import Header
17 from email
._compat
22 import _isstring
19 from email
._compat
21 import _isstring
36 fcre
= re
.compile(r
'^From ', re
.MULTILINE
)
39 if isinstance(s
, StringType
):
41 unicode(s
, 'us-ascii')
49 """Generates output from a Message object tree.
51 This basic generator writes the message to the given file object as plain
58 def __init__(self
, outfp
, mangle_from_
=True, maxheaderlen
=78):
59 """Create the generator for message flattening.
61 outfp is the output file-like object for writing the message to. It
62 must have a write() method.
64 Optional mangle_from_ is a flag that, when True (the default), escapes
65 From_ lines in the body of the message by putting a `>' in front of
68 Optional maxheaderlen specifies the longest length for a non-continued
69 header. When a header line is longer (in characters, with tabs
70 expanded to 8 spaces), than maxheaderlen, the header will be broken on
71 semicolons and continued as per RFC 2822. If no semicolon is found,
72 then the header is left alone. Set to zero to disable wrapping
73 headers. Default is 78, as recommended (but not required by RFC
77 self
._mangle
_from
_ = mangle_from_
78 self
.__maxheaderlen
= maxheaderlen
81 # Just delegate to the file object
84 def flatten(self
, msg
, unixfrom
=False):
85 """Print the message object tree rooted at msg to the output file
86 specified when the Generator instance was created.
88 unixfrom is a flag that forces the printing of a Unix From_ delimiter
89 before the first object in the message tree. If the original message
90 has no From_ delimiter, a `standard' one is crafted. By default, this
91 is False to inhibit the printing of any From_ delimiter.
93 Note that for subobjects, no From_ line is printed.
96 ufrom
= msg
.get_unixfrom()
98 ufrom
= 'From nobody ' + time
.ctime(time
.time())
99 print >> self
._fp
, ufrom
102 # For backwards compatibility, but this is slower
106 """Clone this generator with the exact same options."""
107 return self
.__class
__(fp
, self
._mangle
_from
_, self
.__maxheaderlen
)
110 # Protected interface - undocumented ;/
113 def _write(self
, msg
):
114 # We can't write the headers yet because of the following scenario:
115 # say a multipart message includes the boundary string somewhere in
116 # its body. We'd have to calculate the new boundary /before/ we write
117 # the headers so that we can write the correct Content-Type:
120 # The way we do this, so as to make the _handle_*() methods simpler,
121 # is to cache any subpart writes into a StringIO. The we write the
122 # headers and the StringIO contents. That way, subpart handlers can
123 # Do The Right Thing, and can still modify the Content-Type: header if
127 self
._fp
= sfp
= StringIO()
131 # Write the headers. First we see if the message object wants to
132 # handle that itself. If not, we'll do it generically.
133 meth
= getattr(msg
, '_write_headers', None)
135 self
._write
_headers
(msg
)
138 self
._fp
.write(sfp
.getvalue())
140 def _dispatch(self
, msg
):
141 # Get the Content-Type: for the message, then try to dispatch to
142 # self._handle_<maintype>_<subtype>(). If there's no handler for the
143 # full MIME type, then dispatch to self._handle_<maintype>(). If
144 # that's missing too, then dispatch to self._writeBody().
145 main
= msg
.get_content_maintype()
146 sub
= msg
.get_content_subtype()
147 specific
= UNDERSCORE
.join((main
, sub
)).replace('-', '_')
148 meth
= getattr(self
, '_handle_' + specific
, None)
150 generic
= main
.replace('-', '_')
151 meth
= getattr(self
, '_handle_' + generic
, None)
153 meth
= self
._writeBody
160 def _write_headers(self
, msg
):
161 for h
, v
in msg
.items():
162 # RFC 2822 says that lines SHOULD be no more than maxheaderlen
163 # characters wide, so we're well within our rights to split long
165 text
= '%s: %s' % (h
, v
)
166 if self
.__maxheaderlen
> 0 and len(text
) > self
.__maxheaderlen
:
167 text
= self
._split
_header
(text
)
168 print >> self
._fp
, text
169 # A blank line always separates headers from body
172 def _split_header(self
, text
):
173 maxheaderlen
= self
.__maxheaderlen
174 # Find out whether any lines in the header are really longer than
175 # maxheaderlen characters wide. There could be continuation lines
176 # that actually shorten it. Also, replace hard tabs with 8 spaces.
177 lines
= [s
.replace('\t', SPACE8
) for s
in text
.splitlines()]
179 if len(line
) > maxheaderlen
:
182 # No line was actually longer than maxheaderlen characters, so
183 # just return the original unchanged.
185 # If we have raw 8bit data in a byte string, we have no idea what the
186 # encoding is. I think there is no safe way to split this string. If
187 # it's ascii-subset, then we could do a normal ascii split, but if
188 # it's multibyte then we could break the string. There's no way to
189 # know so the least harm seems to be to not split the string and risk
191 if _is8bitstring(text
):
193 # The `text' argument already has the field name prepended, so don't
194 # provide it here or the first line will get folded too short.
195 h
= Header(text
, maxlinelen
=maxheaderlen
,
196 # For backwards compatibility, we use a hard tab here
197 continuation_ws
='\t')
201 # Handlers for writing types and subtypes
204 def _handle_text(self
, msg
):
205 payload
= msg
.get_payload()
208 cset
= msg
.get_charset()
210 payload
= cset
.body_encode(payload
)
211 if not _isstring(payload
):
212 raise TypeError, 'string payload expected: %s' % type(payload
)
213 if self
._mangle
_from
_:
214 payload
= fcre
.sub('>From ', payload
)
215 self
._fp
.write(payload
)
217 # Default body handler
218 _writeBody
= _handle_text
220 def _handle_multipart(self
, msg
):
221 # The trick here is to write out each part separately, merge them all
222 # together, and then make sure that the boundary we've chosen isn't
223 # present in the payload.
225 subparts
= msg
.get_payload()
227 # Nothing has ever been attached
228 boundary
= msg
.get_boundary(failobj
=_make_boundary())
229 print >> self
._fp
, '--' + boundary
230 print >> self
._fp
, '\n'
231 print >> self
._fp
, '--' + boundary
+ '--'
233 elif _isstring(subparts
):
234 # e.g. a non-strict parse of a message with no starting boundary.
235 self
._fp
.write(subparts
)
237 elif not isinstance(subparts
, ListType
):
239 subparts
= [subparts
]
240 for part
in subparts
:
243 g
.flatten(part
, unixfrom
=False)
244 msgtexts
.append(s
.getvalue())
245 # Now make sure the boundary we've selected doesn't appear in any of
247 alltext
= NL
.join(msgtexts
)
248 # BAW: What about boundaries that are wrapped in double-quotes?
249 boundary
= msg
.get_boundary(failobj
=_make_boundary(alltext
))
250 # If we had to calculate a new boundary because the body text
251 # contained that string, set the new boundary. We don't do it
252 # unconditionally because, while set_boundary() preserves order, it
253 # doesn't preserve newlines/continuations in headers. This is no big
254 # deal in practice, but turns out to be inconvenient for the unittest
256 if msg
.get_boundary() <> boundary
:
257 msg
.set_boundary(boundary
)
258 # Write out any preamble
259 if msg
.preamble
is not None:
260 self
._fp
.write(msg
.preamble
)
261 # First boundary is a bit different; it doesn't have a leading extra
263 print >> self
._fp
, '--' + boundary
264 # Join and write the individual parts
265 joiner
= '\n--' + boundary
+ '\n'
266 self
._fp
.write(joiner
.join(msgtexts
))
267 print >> self
._fp
, '\n--' + boundary
+ '--',
268 # Write out any epilogue
269 if msg
.epilogue
is not None:
270 if not msg
.epilogue
.startswith('\n'):
272 self
._fp
.write(msg
.epilogue
)
274 def _handle_message_delivery_status(self
, msg
):
275 # We can't just write the headers directly to self's file object
276 # because this will leave an extra newline between the last header
277 # block and the boundary. Sigh.
279 for part
in msg
.get_payload():
282 g
.flatten(part
, unixfrom
=False)
284 lines
= text
.split('\n')
285 # Strip off the unnecessary trailing empty line
286 if lines
and lines
[-1] == '':
287 blocks
.append(NL
.join(lines
[:-1]))
290 # Now join all the blocks with an empty line. This has the lovely
291 # effect of separating each block with an empty line, but not adding
292 # an extra one after the last one.
293 self
._fp
.write(NL
.join(blocks
))
295 def _handle_message(self
, msg
):
298 # The payload of a message/rfc822 part should be a multipart sequence
299 # of length 1. The zeroth element of the list should be the Message
300 # object for the subpart. Extract that object, stringify it, and
302 g
.flatten(msg
.get_payload(0), unixfrom
=False)
303 self
._fp
.write(s
.getvalue())
307 class DecodedGenerator(Generator
):
308 """Generator a text representation of a message.
310 Like the Generator base class, except that non-text parts are substituted
311 with a format string representing the part.
313 def __init__(self
, outfp
, mangle_from_
=True, maxheaderlen
=78, fmt
=None):
314 """Like Generator.__init__() except that an additional optional
317 Walks through all subparts of a message. If the subpart is of main
318 type `text', then it prints the decoded payload of the subpart.
320 Otherwise, fmt is a format string that is used instead of the message
321 payload. fmt is expanded with the following keywords (in
324 type : Full MIME type of the non-text part
325 maintype : Main MIME type of the non-text part
326 subtype : Sub-MIME type of the non-text part
327 filename : Filename of the non-text part
328 description: Description associated with the non-text part
329 encoding : Content transfer encoding of the non-text part
331 The default value for fmt is None, meaning
333 [Non-text (%(type)s) part of message omitted, filename %(filename)s]
335 Generator
.__init
__(self
, outfp
, mangle_from_
, maxheaderlen
)
337 fmt
= ('[Non-text (%(type)s) part of message omitted, '
338 'filename %(filename)s]')
341 def _dispatch(self
, msg
):
342 for part
in msg
.walk():
343 maintype
= part
.get_main_type('text')
344 if maintype
== 'text':
345 print >> self
, part
.get_payload(decode
=True)
346 elif maintype
== 'multipart':
350 print >> self
, self
._fmt
% {
351 'type' : part
.get_type('[no MIME type]'),
352 'maintype' : part
.get_main_type('[no main MIME type]'),
353 'subtype' : part
.get_subtype('[no sub-MIME type]'),
354 'filename' : part
.get_filename('[no filename]'),
355 'description': part
.get('Content-Description',
357 'encoding' : part
.get('Content-Transfer-Encoding',
364 def _make_boundary(text
=None):
365 # Craft a random boundary. If text is given, ensure that the chosen
366 # boundary doesn't appear in the text.
367 boundary
= ('=' * 15) + repr(random
.random()).split('.')[1] + '=='
373 cre
= re
.compile('^--' + re
.escape(b
) + '(--)?$', re
.MULTILINE
)
374 if not cre
.search(text
):
376 b
= boundary
+ '.' + str(counter
)