blob: 51109f91316c154a529ac6b339d33db4fd42fff8 [file] [log] [blame]
Benjamin Peterson46a99002010-01-09 18:45:30 +00001# Copyright (C) 2001-2010 Python Software Foundation
Guido van Rossum8b3febe2007-08-30 01:15:14 +00002# Author: Barry Warsaw
3# Contact: email-sig@python.org
4
5"""Classes to generate plain text from a message object tree."""
6
R David Murray1b6c7242012-03-16 22:43:05 -04007__all__ = ['Generator', 'DecodedGenerator', 'BytesGenerator']
Guido van Rossum8b3febe2007-08-30 01:15:14 +00008
9import re
10import sys
11import time
12import random
Guido van Rossum8b3febe2007-08-30 01:15:14 +000013
R David Murray905c8c32014-02-08 11:48:20 -050014from copy import deepcopy
R. David Murray96fd54e2010-10-08 15:55:28 +000015from io import StringIO, BytesIO
R David Murrayc27e5222012-05-25 15:01:48 -040016from email.utils import _has_surrogates
Guido van Rossum8b3febe2007-08-30 01:15:14 +000017
18UNDERSCORE = '_'
R. David Murray8451c4b2010-10-23 22:19:56 +000019NL = '\n' # XXX: no longer used by the code below.
Guido van Rossum8b3febe2007-08-30 01:15:14 +000020
21fcre = re.compile(r'^From ', re.MULTILINE)
22
23
24
25class Generator:
26 """Generates output from a Message object tree.
27
28 This basic generator writes the message to the given file object as plain
29 text.
30 """
31 #
32 # Public interface
33 #
34
R David Murrayfdb23c22015-05-17 14:24:33 -040035 def __init__(self, outfp, mangle_from_=None, maxheaderlen=None, *,
R David Murrayc27e5222012-05-25 15:01:48 -040036 policy=None):
Guido van Rossum8b3febe2007-08-30 01:15:14 +000037 """Create the generator for message flattening.
38
39 outfp is the output file-like object for writing the message to. It
40 must have a write() method.
41
R David Murrayfdb23c22015-05-17 14:24:33 -040042 Optional mangle_from_ is a flag that, when True (the default if policy
43 is not set), escapes From_ lines in the body of the message by putting
44 a `>' in front of them.
Guido van Rossum8b3febe2007-08-30 01:15:14 +000045
46 Optional maxheaderlen specifies the longest length for a non-continued
47 header. When a header line is longer (in characters, with tabs
48 expanded to 8 spaces) than maxheaderlen, the header will split as
49 defined in the Header class. Set maxheaderlen to zero to disable
50 header wrapping. The default is 78, as recommended (but not required)
51 by RFC 2822.
R David Murray3edd22a2011-04-18 13:59:37 -040052
53 The policy keyword specifies a policy object that controls a number of
R David Murraye2524462014-05-06 21:33:18 -040054 aspects of the generator's operation. If no policy is specified,
55 the policy associated with the Message object passed to the
56 flatten method is used.
R David Murray3edd22a2011-04-18 13:59:37 -040057
Guido van Rossum8b3febe2007-08-30 01:15:14 +000058 """
R David Murrayfdb23c22015-05-17 14:24:33 -040059
60 if mangle_from_ is None:
61 mangle_from_ = True if policy is None else policy.mangle_from_
Guido van Rossum8b3febe2007-08-30 01:15:14 +000062 self._fp = outfp
63 self._mangle_from_ = mangle_from_
R David Murrayc27e5222012-05-25 15:01:48 -040064 self.maxheaderlen = maxheaderlen
R David Murray3edd22a2011-04-18 13:59:37 -040065 self.policy = policy
Guido van Rossum8b3febe2007-08-30 01:15:14 +000066
67 def write(self, s):
68 # Just delegate to the file object
69 self._fp.write(s)
70
R David Murray3edd22a2011-04-18 13:59:37 -040071 def flatten(self, msg, unixfrom=False, linesep=None):
R David Murraycd37dfc2011-03-14 18:35:56 -040072 r"""Print the message object tree rooted at msg to the output file
Guido van Rossum8b3febe2007-08-30 01:15:14 +000073 specified when the Generator instance was created.
74
75 unixfrom is a flag that forces the printing of a Unix From_ delimiter
76 before the first object in the message tree. If the original message
77 has no From_ delimiter, a `standard' one is crafted. By default, this
78 is False to inhibit the printing of any From_ delimiter.
79
80 Note that for subobjects, no From_ line is printed.
R. David Murray8451c4b2010-10-23 22:19:56 +000081
82 linesep specifies the characters used to indicate a new line in
R David Murraye2524462014-05-06 21:33:18 -040083 the output. The default value is determined by the policy specified
84 when the Generator instance was created or, if none was specified,
85 from the policy associated with the msg.
R David Murraycd37dfc2011-03-14 18:35:56 -040086
Guido van Rossum8b3febe2007-08-30 01:15:14 +000087 """
R. David Murray8451c4b2010-10-23 22:19:56 +000088 # We use the _XXX constants for operating on data that comes directly
89 # from the msg, and _encoded_XXX constants for operating on data that
90 # has already been converted (to bytes in the BytesGenerator) and
91 # inserted into a temporary buffer.
R David Murrayc27e5222012-05-25 15:01:48 -040092 policy = msg.policy if self.policy is None else self.policy
93 if linesep is not None:
94 policy = policy.clone(linesep=linesep)
95 if self.maxheaderlen is not None:
96 policy = policy.clone(max_line_length=self.maxheaderlen)
97 self._NL = policy.linesep
R David Murray3edd22a2011-04-18 13:59:37 -040098 self._encoded_NL = self._encode(self._NL)
R. David Murray8451c4b2010-10-23 22:19:56 +000099 self._EMPTY = ''
R David Murrayeaab1ca2016-09-08 22:21:27 -0400100 self._encoded_EMPTY = self._encode(self._EMPTY)
R David Murray0b6f6c82012-05-25 18:42:14 -0400101 # Because we use clone (below) when we recursively process message
102 # subparts, and because clone uses the computed policy (not None),
103 # submessages will automatically get set to the computed policy when
104 # they are processed by this code.
105 old_gen_policy = self.policy
106 old_msg_policy = msg.policy
R David Murrayc27e5222012-05-25 15:01:48 -0400107 try:
108 self.policy = policy
R David Murray0b6f6c82012-05-25 18:42:14 -0400109 msg.policy = policy
R David Murrayc27e5222012-05-25 15:01:48 -0400110 if unixfrom:
111 ufrom = msg.get_unixfrom()
112 if not ufrom:
113 ufrom = 'From nobody ' + time.ctime(time.time())
114 self.write(ufrom + self._NL)
115 self._write(msg)
116 finally:
R David Murray0b6f6c82012-05-25 18:42:14 -0400117 self.policy = old_gen_policy
118 msg.policy = old_msg_policy
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000119
120 def clone(self, fp):
121 """Clone this generator with the exact same options."""
R David Murrayc27e5222012-05-25 15:01:48 -0400122 return self.__class__(fp,
123 self._mangle_from_,
124 None, # Use policy setting, which we've adjusted
125 policy=self.policy)
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000126
127 #
128 # Protected interface - undocumented ;/
129 #
130
R. David Murray96fd54e2010-10-08 15:55:28 +0000131 # Note that we use 'self.write' when what we are writing is coming from
132 # the source, and self._fp.write when what we are writing is coming from a
133 # buffer (because the Bytes subclass has already had a chance to transform
134 # the data in its write method in that case). This is an entirely
135 # pragmatic split determined by experiment; we could be more general by
136 # always using write and having the Bytes subclass write method detect when
137 # it has already transformed the input; but, since this whole thing is a
138 # hack anyway this seems good enough.
139
R. David Murray96fd54e2010-10-08 15:55:28 +0000140 def _new_buffer(self):
141 # BytesGenerator overrides this to return BytesIO.
142 return StringIO()
143
R. David Murray8451c4b2010-10-23 22:19:56 +0000144 def _encode(self, s):
145 # BytesGenerator overrides this to encode strings to bytes.
146 return s
147
R David Murraye67c6c52013-03-07 16:38:03 -0500148 def _write_lines(self, lines):
149 # We have to transform the line endings.
150 if not lines:
151 return
152 lines = lines.splitlines(True)
153 for line in lines[:-1]:
154 self.write(line.rstrip('\r\n'))
155 self.write(self._NL)
156 laststripped = lines[-1].rstrip('\r\n')
157 self.write(laststripped)
R David Murrayb9534f42013-03-07 18:15:13 -0500158 if len(lines[-1]) != len(laststripped):
R David Murraye67c6c52013-03-07 16:38:03 -0500159 self.write(self._NL)
160
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000161 def _write(self, msg):
162 # We can't write the headers yet because of the following scenario:
163 # say a multipart message includes the boundary string somewhere in
164 # its body. We'd have to calculate the new boundary /before/ we write
165 # the headers so that we can write the correct Content-Type:
166 # parameter.
167 #
168 # The way we do this, so as to make the _handle_*() methods simpler,
R. David Murray96fd54e2010-10-08 15:55:28 +0000169 # is to cache any subpart writes into a buffer. The we write the
170 # headers and the buffer contents. That way, subpart handlers can
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000171 # Do The Right Thing, and can still modify the Content-Type: header if
172 # necessary.
173 oldfp = self._fp
174 try:
R David Murray905c8c32014-02-08 11:48:20 -0500175 self._munge_cte = None
R. David Murray96fd54e2010-10-08 15:55:28 +0000176 self._fp = sfp = self._new_buffer()
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000177 self._dispatch(msg)
178 finally:
179 self._fp = oldfp
R David Murray905c8c32014-02-08 11:48:20 -0500180 munge_cte = self._munge_cte
181 del self._munge_cte
182 # If we munged the cte, copy the message again and re-fix the CTE.
183 if munge_cte:
184 msg = deepcopy(msg)
185 msg.replace_header('content-transfer-encoding', munge_cte[0])
186 msg.replace_header('content-type', munge_cte[1])
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000187 # Write the headers. First we see if the message object wants to
188 # handle that itself. If not, we'll do it generically.
189 meth = getattr(msg, '_write_headers', None)
190 if meth is None:
191 self._write_headers(msg)
192 else:
193 meth(self)
194 self._fp.write(sfp.getvalue())
195
196 def _dispatch(self, msg):
197 # Get the Content-Type: for the message, then try to dispatch to
198 # self._handle_<maintype>_<subtype>(). If there's no handler for the
199 # full MIME type, then dispatch to self._handle_<maintype>(). If
200 # that's missing too, then dispatch to self._writeBody().
201 main = msg.get_content_maintype()
202 sub = msg.get_content_subtype()
203 specific = UNDERSCORE.join((main, sub)).replace('-', '_')
204 meth = getattr(self, '_handle_' + specific, None)
205 if meth is None:
206 generic = main.replace('-', '_')
207 meth = getattr(self, '_handle_' + generic, None)
208 if meth is None:
209 meth = self._writeBody
210 meth(msg)
211
212 #
213 # Default handlers
214 #
215
216 def _write_headers(self, msg):
R David Murrayc27e5222012-05-25 15:01:48 -0400217 for h, v in msg.raw_items():
218 self.write(self.policy.fold(h, v))
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000219 # A blank line always separates headers from body
R. David Murray8451c4b2010-10-23 22:19:56 +0000220 self.write(self._NL)
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000221
222 #
223 # Handlers for writing types and subtypes
224 #
225
226 def _handle_text(self, msg):
227 payload = msg.get_payload()
228 if payload is None:
229 return
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000230 if not isinstance(payload, str):
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000231 raise TypeError('string payload expected: %s' % type(payload))
R. David Murray96fd54e2010-10-08 15:55:28 +0000232 if _has_surrogates(msg._payload):
233 charset = msg.get_param('charset')
234 if charset is not None:
R David Murray905c8c32014-02-08 11:48:20 -0500235 # XXX: This copy stuff is an ugly hack to avoid modifying the
236 # existing message.
237 msg = deepcopy(msg)
R. David Murray96fd54e2010-10-08 15:55:28 +0000238 del msg['content-transfer-encoding']
239 msg.set_payload(payload, charset)
240 payload = msg.get_payload()
R David Murray905c8c32014-02-08 11:48:20 -0500241 self._munge_cte = (msg['content-transfer-encoding'],
242 msg['content-type'])
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000243 if self._mangle_from_:
244 payload = fcre.sub('>From ', payload)
R David Murraye67c6c52013-03-07 16:38:03 -0500245 self._write_lines(payload)
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000246
247 # Default body handler
248 _writeBody = _handle_text
249
250 def _handle_multipart(self, msg):
251 # The trick here is to write out each part separately, merge them all
252 # together, and then make sure that the boundary we've chosen isn't
253 # present in the payload.
254 msgtexts = []
255 subparts = msg.get_payload()
256 if subparts is None:
257 subparts = []
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000258 elif isinstance(subparts, str):
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000259 # e.g. a non-strict parse of a message with no starting boundary.
R. David Murray96fd54e2010-10-08 15:55:28 +0000260 self.write(subparts)
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000261 return
262 elif not isinstance(subparts, list):
263 # Scalar payload
264 subparts = [subparts]
265 for part in subparts:
R. David Murray96fd54e2010-10-08 15:55:28 +0000266 s = self._new_buffer()
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000267 g = self.clone(s)
R. David Murray8451c4b2010-10-23 22:19:56 +0000268 g.flatten(part, unixfrom=False, linesep=self._NL)
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000269 msgtexts.append(s.getvalue())
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000270 # BAW: What about boundaries that are wrapped in double-quotes?
R. David Murray5260a9b2010-12-12 20:06:19 +0000271 boundary = msg.get_boundary()
272 if not boundary:
273 # Create a boundary that doesn't appear in any of the
274 # message texts.
275 alltext = self._encoded_NL.join(msgtexts)
R. David Murray73a559d2010-12-21 18:07:59 +0000276 boundary = self._make_boundary(alltext)
277 msg.set_boundary(boundary)
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000278 # If there's a preamble, write it out, with a trailing CRLF
279 if msg.preamble is not None:
R David Murray6a31bc62012-07-22 21:47:53 -0400280 if self._mangle_from_:
281 preamble = fcre.sub('>From ', msg.preamble)
282 else:
283 preamble = msg.preamble
R David Murraye67c6c52013-03-07 16:38:03 -0500284 self._write_lines(preamble)
285 self.write(self._NL)
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000286 # dash-boundary transport-padding CRLF
R. David Murray8451c4b2010-10-23 22:19:56 +0000287 self.write('--' + boundary + self._NL)
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000288 # body-part
289 if msgtexts:
290 self._fp.write(msgtexts.pop(0))
291 # *encapsulation
292 # --> delimiter transport-padding
293 # --> CRLF body-part
294 for body_part in msgtexts:
295 # delimiter transport-padding CRLF
R. David Murray8451c4b2010-10-23 22:19:56 +0000296 self.write(self._NL + '--' + boundary + self._NL)
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000297 # body-part
298 self._fp.write(body_part)
299 # close-delimiter transport-padding
R David Murraye9c31472014-02-08 17:54:56 -0500300 self.write(self._NL + '--' + boundary + '--' + self._NL)
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000301 if msg.epilogue is not None:
R David Murray6a31bc62012-07-22 21:47:53 -0400302 if self._mangle_from_:
303 epilogue = fcre.sub('>From ', msg.epilogue)
304 else:
305 epilogue = msg.epilogue
R David Murraye67c6c52013-03-07 16:38:03 -0500306 self._write_lines(epilogue)
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000307
R. David Murraya8f480f2010-01-16 18:30:03 +0000308 def _handle_multipart_signed(self, msg):
309 # The contents of signed parts has to stay unmodified in order to keep
310 # the signature intact per RFC1847 2.1, so we disable header wrapping.
311 # RDM: This isn't enough to completely preserve the part, but it helps.
R David Murrayc27e5222012-05-25 15:01:48 -0400312 p = self.policy
313 self.policy = p.clone(max_line_length=0)
R. David Murraya8f480f2010-01-16 18:30:03 +0000314 try:
R. David Murraya8f480f2010-01-16 18:30:03 +0000315 self._handle_multipart(msg)
316 finally:
R David Murrayc27e5222012-05-25 15:01:48 -0400317 self.policy = p
R. David Murraya8f480f2010-01-16 18:30:03 +0000318
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000319 def _handle_message_delivery_status(self, msg):
320 # We can't just write the headers directly to self's file object
321 # because this will leave an extra newline between the last header
322 # block and the boundary. Sigh.
323 blocks = []
324 for part in msg.get_payload():
R. David Murray96fd54e2010-10-08 15:55:28 +0000325 s = self._new_buffer()
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000326 g = self.clone(s)
R. David Murray719a4492010-11-21 16:53:48 +0000327 g.flatten(part, unixfrom=False, linesep=self._NL)
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000328 text = s.getvalue()
R. David Murray8451c4b2010-10-23 22:19:56 +0000329 lines = text.split(self._encoded_NL)
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000330 # Strip off the unnecessary trailing empty line
R. David Murray8451c4b2010-10-23 22:19:56 +0000331 if lines and lines[-1] == self._encoded_EMPTY:
332 blocks.append(self._encoded_NL.join(lines[:-1]))
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000333 else:
334 blocks.append(text)
335 # Now join all the blocks with an empty line. This has the lovely
336 # effect of separating each block with an empty line, but not adding
337 # an extra one after the last one.
R. David Murray8451c4b2010-10-23 22:19:56 +0000338 self._fp.write(self._encoded_NL.join(blocks))
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000339
340 def _handle_message(self, msg):
R. David Murray96fd54e2010-10-08 15:55:28 +0000341 s = self._new_buffer()
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000342 g = self.clone(s)
343 # The payload of a message/rfc822 part should be a multipart sequence
344 # of length 1. The zeroth element of the list should be the Message
345 # object for the subpart. Extract that object, stringify it, and
346 # write it out.
R. David Murray57c45ac2010-02-21 04:39:40 +0000347 # Except, it turns out, when it's a string instead, which happens when
348 # and only when HeaderParser is used on a message of mime type
349 # message/rfc822. Such messages are generated by, for example,
350 # Groupwise when forwarding unadorned messages. (Issue 7970.) So
351 # in that case we just emit the string body.
R David Murrayb35c8502011-04-13 16:46:05 -0400352 payload = msg._payload
R. David Murray57c45ac2010-02-21 04:39:40 +0000353 if isinstance(payload, list):
R. David Murray719a4492010-11-21 16:53:48 +0000354 g.flatten(msg.get_payload(0), unixfrom=False, linesep=self._NL)
R. David Murray57c45ac2010-02-21 04:39:40 +0000355 payload = s.getvalue()
R David Murrayb35c8502011-04-13 16:46:05 -0400356 else:
357 payload = self._encode(payload)
R. David Murray57c45ac2010-02-21 04:39:40 +0000358 self._fp.write(payload)
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000359
R. David Murray96fd54e2010-10-08 15:55:28 +0000360 # This used to be a module level function; we use a classmethod for this
361 # and _compile_re so we can continue to provide the module level function
362 # for backward compatibility by doing
Ezio Melotti2af76da2013-08-10 18:47:07 +0300363 # _make_boundary = Generator._make_boundary
R. David Murray96fd54e2010-10-08 15:55:28 +0000364 # at the end of the module. It *is* internal, so we could drop that...
365 @classmethod
366 def _make_boundary(cls, text=None):
367 # Craft a random boundary. If text is given, ensure that the chosen
368 # boundary doesn't appear in the text.
369 token = random.randrange(sys.maxsize)
370 boundary = ('=' * 15) + (_fmt % token) + '=='
371 if text is None:
372 return boundary
373 b = boundary
374 counter = 0
375 while True:
376 cre = cls._compile_re('^--' + re.escape(b) + '(--)?$', re.MULTILINE)
377 if not cre.search(text):
378 break
379 b = boundary + '.' + str(counter)
380 counter += 1
381 return b
382
383 @classmethod
384 def _compile_re(cls, s, flags):
385 return re.compile(s, flags)
386
387
388class BytesGenerator(Generator):
389 """Generates a bytes version of a Message object tree.
390
391 Functionally identical to the base Generator except that the output is
392 bytes and not string. When surrogates were used in the input to encode
R David Murray3edd22a2011-04-18 13:59:37 -0400393 bytes, these are decoded back to bytes for output. If the policy has
R David Murrayc27e5222012-05-25 15:01:48 -0400394 cte_type set to 7bit, then the message is transformed such that the
395 non-ASCII bytes are properly content transfer encoded, using the charset
396 unknown-8bit.
R. David Murray96fd54e2010-10-08 15:55:28 +0000397
398 The outfp object must accept bytes in its write method.
399 """
400
R. David Murray96fd54e2010-10-08 15:55:28 +0000401 def write(self, s):
402 self._fp.write(s.encode('ascii', 'surrogateescape'))
403
404 def _new_buffer(self):
405 return BytesIO()
406
R. David Murray8451c4b2010-10-23 22:19:56 +0000407 def _encode(self, s):
408 return s.encode('ascii')
409
R. David Murray96fd54e2010-10-08 15:55:28 +0000410 def _write_headers(self, msg):
411 # This is almost the same as the string version, except for handling
412 # strings with 8bit bytes.
R David Murrayc27e5222012-05-25 15:01:48 -0400413 for h, v in msg.raw_items():
414 self._fp.write(self.policy.fold_binary(h, v))
R. David Murray96fd54e2010-10-08 15:55:28 +0000415 # A blank line always separates headers from body
R. David Murray8451c4b2010-10-23 22:19:56 +0000416 self.write(self._NL)
R. David Murray96fd54e2010-10-08 15:55:28 +0000417
418 def _handle_text(self, msg):
419 # If the string has surrogates the original source was bytes, so
420 # just write it back out.
R. David Murray7372a072011-01-26 21:21:32 +0000421 if msg._payload is None:
422 return
R David Murrayc27e5222012-05-25 15:01:48 -0400423 if _has_surrogates(msg._payload) and not self.policy.cte_type=='7bit':
R David Murray638d40b2012-08-24 11:14:13 -0400424 if self._mangle_from_:
425 msg._payload = fcre.sub(">From ", msg._payload)
R David Murraye67c6c52013-03-07 16:38:03 -0500426 self._write_lines(msg._payload)
R. David Murray96fd54e2010-10-08 15:55:28 +0000427 else:
428 super(BytesGenerator,self)._handle_text(msg)
429
R David Murrayceaa8b12013-02-09 13:02:58 -0500430 # Default body handler
431 _writeBody = _handle_text
432
R. David Murray96fd54e2010-10-08 15:55:28 +0000433 @classmethod
434 def _compile_re(cls, s, flags):
435 return re.compile(s.encode('ascii'), flags)
436
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000437
438
439_FMT = '[Non-text (%(type)s) part of message omitted, filename %(filename)s]'
440
441class DecodedGenerator(Generator):
R. David Murray70a99932010-10-01 20:38:33 +0000442 """Generates a text representation of a message.
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000443
444 Like the Generator base class, except that non-text parts are substituted
445 with a format string representing the part.
446 """
R David Murray301edfa2016-09-08 17:57:06 -0400447 def __init__(self, outfp, mangle_from_=None, maxheaderlen=None, fmt=None, *,
448 policy=None):
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000449 """Like Generator.__init__() except that an additional optional
450 argument is allowed.
451
452 Walks through all subparts of a message. If the subpart is of main
453 type `text', then it prints the decoded payload of the subpart.
454
455 Otherwise, fmt is a format string that is used instead of the message
456 payload. fmt is expanded with the following keywords (in
457 %(keyword)s format):
458
459 type : Full MIME type of the non-text part
460 maintype : Main MIME type of the non-text part
461 subtype : Sub-MIME type of the non-text part
462 filename : Filename of the non-text part
463 description: Description associated with the non-text part
464 encoding : Content transfer encoding of the non-text part
465
466 The default value for fmt is None, meaning
467
468 [Non-text (%(type)s) part of message omitted, filename %(filename)s]
469 """
R David Murray301edfa2016-09-08 17:57:06 -0400470 Generator.__init__(self, outfp, mangle_from_, maxheaderlen,
471 policy=policy)
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000472 if fmt is None:
473 self._fmt = _FMT
474 else:
475 self._fmt = fmt
476
477 def _dispatch(self, msg):
478 for part in msg.walk():
479 maintype = part.get_content_maintype()
480 if maintype == 'text':
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000481 print(part.get_payload(decode=False), file=self)
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000482 elif maintype == 'multipart':
483 # Just skip this
484 pass
485 else:
486 print(self._fmt % {
487 'type' : part.get_content_type(),
488 'maintype' : part.get_content_maintype(),
489 'subtype' : part.get_content_subtype(),
490 'filename' : part.get_filename('[no filename]'),
491 'description': part.get('Content-Description',
492 '[no description]'),
493 'encoding' : part.get('Content-Transfer-Encoding',
494 '[no encoding]'),
495 }, file=self)
496
497
498
R. David Murray96fd54e2010-10-08 15:55:28 +0000499# Helper used by Generator._make_boundary
Christian Heimesa37d4c62007-12-04 23:02:19 +0000500_width = len(repr(sys.maxsize-1))
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000501_fmt = '%%0%dd' % _width
502
R. David Murray96fd54e2010-10-08 15:55:28 +0000503# Backward compatibility
504_make_boundary = Generator._make_boundary