Benjamin Peterson | 46a9900 | 2010-01-09 18:45:30 +0000 | [diff] [blame] | 1 | # Copyright (C) 2001-2010 Python Software Foundation |
Guido van Rossum | 8b3febe | 2007-08-30 01:15:14 +0000 | [diff] [blame] | 2 | # Author: Barry Warsaw |
| 3 | # Contact: email-sig@python.org |
| 4 | |
| 5 | """Classes to generate plain text from a message object tree.""" |
| 6 | |
R David Murray | 1b6c724 | 2012-03-16 22:43:05 -0400 | [diff] [blame] | 7 | __all__ = ['Generator', 'DecodedGenerator', 'BytesGenerator'] |
Guido van Rossum | 8b3febe | 2007-08-30 01:15:14 +0000 | [diff] [blame] | 8 | |
| 9 | import re |
| 10 | import sys |
| 11 | import time |
| 12 | import random |
| 13 | import warnings |
| 14 | |
R. David Murray | 96fd54e | 2010-10-08 15:55:28 +0000 | [diff] [blame] | 15 | from io import StringIO, BytesIO |
Guido van Rossum | 8b3febe | 2007-08-30 01:15:14 +0000 | [diff] [blame] | 16 | from email.header import Header |
R. David Murray | 96fd54e | 2010-10-08 15:55:28 +0000 | [diff] [blame] | 17 | from email.message import _has_surrogates |
Guido van Rossum | 8b3febe | 2007-08-30 01:15:14 +0000 | [diff] [blame] | 18 | |
| 19 | UNDERSCORE = '_' |
R. David Murray | 8451c4b | 2010-10-23 22:19:56 +0000 | [diff] [blame] | 20 | NL = '\n' # XXX: no longer used by the code below. |
Guido van Rossum | 8b3febe | 2007-08-30 01:15:14 +0000 | [diff] [blame] | 21 | |
| 22 | fcre = re.compile(r'^From ', re.MULTILINE) |
| 23 | |
| 24 | |
| 25 | |
| 26 | class Generator: |
| 27 | """Generates output from a Message object tree. |
| 28 | |
| 29 | This basic generator writes the message to the given file object as plain |
| 30 | text. |
| 31 | """ |
| 32 | # |
| 33 | # Public interface |
| 34 | # |
| 35 | |
| 36 | def __init__(self, outfp, mangle_from_=True, maxheaderlen=78): |
| 37 | """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 | |
| 42 | Optional mangle_from_ is a flag that, when True (the default), escapes |
| 43 | From_ lines in the body of the message by putting a `>' in front of |
| 44 | them. |
| 45 | |
| 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. |
| 52 | """ |
| 53 | self._fp = outfp |
| 54 | self._mangle_from_ = mangle_from_ |
| 55 | self._maxheaderlen = maxheaderlen |
| 56 | |
| 57 | def write(self, s): |
| 58 | # Just delegate to the file object |
| 59 | self._fp.write(s) |
| 60 | |
R. David Murray | 8451c4b | 2010-10-23 22:19:56 +0000 | [diff] [blame] | 61 | def flatten(self, msg, unixfrom=False, linesep='\n'): |
R David Murray | cd37dfc | 2011-03-14 18:35:56 -0400 | [diff] [blame] | 62 | r"""Print the message object tree rooted at msg to the output file |
Guido van Rossum | 8b3febe | 2007-08-30 01:15:14 +0000 | [diff] [blame] | 63 | specified when the Generator instance was created. |
| 64 | |
| 65 | unixfrom is a flag that forces the printing of a Unix From_ delimiter |
| 66 | before the first object in the message tree. If the original message |
| 67 | has no From_ delimiter, a `standard' one is crafted. By default, this |
| 68 | is False to inhibit the printing of any From_ delimiter. |
| 69 | |
| 70 | Note that for subobjects, no From_ line is printed. |
R. David Murray | 8451c4b | 2010-10-23 22:19:56 +0000 | [diff] [blame] | 71 | |
| 72 | linesep specifies the characters used to indicate a new line in |
R David Murray | cd37dfc | 2011-03-14 18:35:56 -0400 | [diff] [blame] | 73 | the output. The default value is the most useful for typical |
| 74 | Python applications, but it can be set to \r\n to produce RFC-compliant |
| 75 | line separators when needed. |
| 76 | |
Guido van Rossum | 8b3febe | 2007-08-30 01:15:14 +0000 | [diff] [blame] | 77 | """ |
R. David Murray | 8451c4b | 2010-10-23 22:19:56 +0000 | [diff] [blame] | 78 | # We use the _XXX constants for operating on data that comes directly |
| 79 | # from the msg, and _encoded_XXX constants for operating on data that |
| 80 | # has already been converted (to bytes in the BytesGenerator) and |
| 81 | # inserted into a temporary buffer. |
| 82 | self._NL = linesep |
| 83 | self._encoded_NL = self._encode(linesep) |
| 84 | self._EMPTY = '' |
| 85 | self._encoded_EMTPY = self._encode('') |
Guido van Rossum | 8b3febe | 2007-08-30 01:15:14 +0000 | [diff] [blame] | 86 | if unixfrom: |
| 87 | ufrom = msg.get_unixfrom() |
| 88 | if not ufrom: |
| 89 | ufrom = 'From nobody ' + time.ctime(time.time()) |
R. David Murray | 8451c4b | 2010-10-23 22:19:56 +0000 | [diff] [blame] | 90 | self.write(ufrom + self._NL) |
Guido van Rossum | 8b3febe | 2007-08-30 01:15:14 +0000 | [diff] [blame] | 91 | self._write(msg) |
| 92 | |
| 93 | def clone(self, fp): |
| 94 | """Clone this generator with the exact same options.""" |
| 95 | return self.__class__(fp, self._mangle_from_, self._maxheaderlen) |
| 96 | |
| 97 | # |
| 98 | # Protected interface - undocumented ;/ |
| 99 | # |
| 100 | |
R. David Murray | 96fd54e | 2010-10-08 15:55:28 +0000 | [diff] [blame] | 101 | # Note that we use 'self.write' when what we are writing is coming from |
| 102 | # the source, and self._fp.write when what we are writing is coming from a |
| 103 | # buffer (because the Bytes subclass has already had a chance to transform |
| 104 | # the data in its write method in that case). This is an entirely |
| 105 | # pragmatic split determined by experiment; we could be more general by |
| 106 | # always using write and having the Bytes subclass write method detect when |
| 107 | # it has already transformed the input; but, since this whole thing is a |
| 108 | # hack anyway this seems good enough. |
| 109 | |
R. David Murray | 8451c4b | 2010-10-23 22:19:56 +0000 | [diff] [blame] | 110 | # Similarly, we have _XXX and _encoded_XXX attributes that are used on |
| 111 | # source and buffer data, respectively. |
| 112 | _encoded_EMPTY = '' |
R. David Murray | 96fd54e | 2010-10-08 15:55:28 +0000 | [diff] [blame] | 113 | |
| 114 | def _new_buffer(self): |
| 115 | # BytesGenerator overrides this to return BytesIO. |
| 116 | return StringIO() |
| 117 | |
R. David Murray | 8451c4b | 2010-10-23 22:19:56 +0000 | [diff] [blame] | 118 | def _encode(self, s): |
| 119 | # BytesGenerator overrides this to encode strings to bytes. |
| 120 | return s |
| 121 | |
Guido van Rossum | 8b3febe | 2007-08-30 01:15:14 +0000 | [diff] [blame] | 122 | def _write(self, msg): |
| 123 | # We can't write the headers yet because of the following scenario: |
| 124 | # say a multipart message includes the boundary string somewhere in |
| 125 | # its body. We'd have to calculate the new boundary /before/ we write |
| 126 | # the headers so that we can write the correct Content-Type: |
| 127 | # parameter. |
| 128 | # |
| 129 | # The way we do this, so as to make the _handle_*() methods simpler, |
R. David Murray | 96fd54e | 2010-10-08 15:55:28 +0000 | [diff] [blame] | 130 | # is to cache any subpart writes into a buffer. The we write the |
| 131 | # headers and the buffer contents. That way, subpart handlers can |
Guido van Rossum | 8b3febe | 2007-08-30 01:15:14 +0000 | [diff] [blame] | 132 | # Do The Right Thing, and can still modify the Content-Type: header if |
| 133 | # necessary. |
| 134 | oldfp = self._fp |
| 135 | try: |
R. David Murray | 96fd54e | 2010-10-08 15:55:28 +0000 | [diff] [blame] | 136 | self._fp = sfp = self._new_buffer() |
Guido van Rossum | 8b3febe | 2007-08-30 01:15:14 +0000 | [diff] [blame] | 137 | self._dispatch(msg) |
| 138 | finally: |
| 139 | self._fp = oldfp |
| 140 | # Write the headers. First we see if the message object wants to |
| 141 | # handle that itself. If not, we'll do it generically. |
| 142 | meth = getattr(msg, '_write_headers', None) |
| 143 | if meth is None: |
| 144 | self._write_headers(msg) |
| 145 | else: |
| 146 | meth(self) |
| 147 | self._fp.write(sfp.getvalue()) |
| 148 | |
| 149 | def _dispatch(self, msg): |
| 150 | # Get the Content-Type: for the message, then try to dispatch to |
| 151 | # self._handle_<maintype>_<subtype>(). If there's no handler for the |
| 152 | # full MIME type, then dispatch to self._handle_<maintype>(). If |
| 153 | # that's missing too, then dispatch to self._writeBody(). |
| 154 | main = msg.get_content_maintype() |
| 155 | sub = msg.get_content_subtype() |
| 156 | specific = UNDERSCORE.join((main, sub)).replace('-', '_') |
| 157 | meth = getattr(self, '_handle_' + specific, None) |
| 158 | if meth is None: |
| 159 | generic = main.replace('-', '_') |
| 160 | meth = getattr(self, '_handle_' + generic, None) |
| 161 | if meth is None: |
| 162 | meth = self._writeBody |
| 163 | meth(msg) |
| 164 | |
| 165 | # |
| 166 | # Default handlers |
| 167 | # |
| 168 | |
| 169 | def _write_headers(self, msg): |
| 170 | for h, v in msg.items(): |
R. David Murray | 96fd54e | 2010-10-08 15:55:28 +0000 | [diff] [blame] | 171 | self.write('%s: ' % h) |
Guido van Rossum | 9604e66 | 2007-08-30 03:46:43 +0000 | [diff] [blame] | 172 | if isinstance(v, Header): |
R. David Murray | 8451c4b | 2010-10-23 22:19:56 +0000 | [diff] [blame] | 173 | self.write(v.encode( |
| 174 | maxlinelen=self._maxheaderlen, linesep=self._NL)+self._NL) |
Guido van Rossum | 8b3febe | 2007-08-30 01:15:14 +0000 | [diff] [blame] | 175 | else: |
| 176 | # Header's got lots of smarts, so use it. |
| 177 | header = Header(v, maxlinelen=self._maxheaderlen, |
Barry Warsaw | 70d61ce | 2009-03-30 23:12:30 +0000 | [diff] [blame] | 178 | header_name=h) |
R. David Murray | 8451c4b | 2010-10-23 22:19:56 +0000 | [diff] [blame] | 179 | self.write(header.encode(linesep=self._NL)+self._NL) |
Guido van Rossum | 8b3febe | 2007-08-30 01:15:14 +0000 | [diff] [blame] | 180 | # A blank line always separates headers from body |
R. David Murray | 8451c4b | 2010-10-23 22:19:56 +0000 | [diff] [blame] | 181 | self.write(self._NL) |
Guido van Rossum | 8b3febe | 2007-08-30 01:15:14 +0000 | [diff] [blame] | 182 | |
| 183 | # |
| 184 | # Handlers for writing types and subtypes |
| 185 | # |
| 186 | |
| 187 | def _handle_text(self, msg): |
| 188 | payload = msg.get_payload() |
| 189 | if payload is None: |
| 190 | return |
Guido van Rossum | 3172c5d | 2007-10-16 18:12:55 +0000 | [diff] [blame] | 191 | if not isinstance(payload, str): |
Guido van Rossum | 8b3febe | 2007-08-30 01:15:14 +0000 | [diff] [blame] | 192 | raise TypeError('string payload expected: %s' % type(payload)) |
R. David Murray | 96fd54e | 2010-10-08 15:55:28 +0000 | [diff] [blame] | 193 | if _has_surrogates(msg._payload): |
| 194 | charset = msg.get_param('charset') |
| 195 | if charset is not None: |
| 196 | del msg['content-transfer-encoding'] |
| 197 | msg.set_payload(payload, charset) |
| 198 | payload = msg.get_payload() |
Guido van Rossum | 8b3febe | 2007-08-30 01:15:14 +0000 | [diff] [blame] | 199 | if self._mangle_from_: |
| 200 | payload = fcre.sub('>From ', payload) |
R. David Murray | 96fd54e | 2010-10-08 15:55:28 +0000 | [diff] [blame] | 201 | self.write(payload) |
Guido van Rossum | 8b3febe | 2007-08-30 01:15:14 +0000 | [diff] [blame] | 202 | |
| 203 | # Default body handler |
| 204 | _writeBody = _handle_text |
| 205 | |
| 206 | def _handle_multipart(self, msg): |
| 207 | # The trick here is to write out each part separately, merge them all |
| 208 | # together, and then make sure that the boundary we've chosen isn't |
| 209 | # present in the payload. |
| 210 | msgtexts = [] |
| 211 | subparts = msg.get_payload() |
| 212 | if subparts is None: |
| 213 | subparts = [] |
Guido van Rossum | 3172c5d | 2007-10-16 18:12:55 +0000 | [diff] [blame] | 214 | elif isinstance(subparts, str): |
Guido van Rossum | 8b3febe | 2007-08-30 01:15:14 +0000 | [diff] [blame] | 215 | # e.g. a non-strict parse of a message with no starting boundary. |
R. David Murray | 96fd54e | 2010-10-08 15:55:28 +0000 | [diff] [blame] | 216 | self.write(subparts) |
Guido van Rossum | 8b3febe | 2007-08-30 01:15:14 +0000 | [diff] [blame] | 217 | return |
| 218 | elif not isinstance(subparts, list): |
| 219 | # Scalar payload |
| 220 | subparts = [subparts] |
| 221 | for part in subparts: |
R. David Murray | 96fd54e | 2010-10-08 15:55:28 +0000 | [diff] [blame] | 222 | s = self._new_buffer() |
Guido van Rossum | 8b3febe | 2007-08-30 01:15:14 +0000 | [diff] [blame] | 223 | g = self.clone(s) |
R. David Murray | 8451c4b | 2010-10-23 22:19:56 +0000 | [diff] [blame] | 224 | g.flatten(part, unixfrom=False, linesep=self._NL) |
Guido van Rossum | 8b3febe | 2007-08-30 01:15:14 +0000 | [diff] [blame] | 225 | msgtexts.append(s.getvalue()) |
Guido van Rossum | 8b3febe | 2007-08-30 01:15:14 +0000 | [diff] [blame] | 226 | # BAW: What about boundaries that are wrapped in double-quotes? |
R. David Murray | 5260a9b | 2010-12-12 20:06:19 +0000 | [diff] [blame] | 227 | boundary = msg.get_boundary() |
| 228 | if not boundary: |
| 229 | # Create a boundary that doesn't appear in any of the |
| 230 | # message texts. |
| 231 | alltext = self._encoded_NL.join(msgtexts) |
R. David Murray | 73a559d | 2010-12-21 18:07:59 +0000 | [diff] [blame] | 232 | boundary = self._make_boundary(alltext) |
| 233 | msg.set_boundary(boundary) |
Guido van Rossum | 8b3febe | 2007-08-30 01:15:14 +0000 | [diff] [blame] | 234 | # If there's a preamble, write it out, with a trailing CRLF |
| 235 | if msg.preamble is not None: |
R David Murray | 6a31bc6 | 2012-07-22 21:47:53 -0400 | [diff] [blame] | 236 | if self._mangle_from_: |
| 237 | preamble = fcre.sub('>From ', msg.preamble) |
| 238 | else: |
| 239 | preamble = msg.preamble |
| 240 | self.write(preamble + self._NL) |
Guido van Rossum | 8b3febe | 2007-08-30 01:15:14 +0000 | [diff] [blame] | 241 | # dash-boundary transport-padding CRLF |
R. David Murray | 8451c4b | 2010-10-23 22:19:56 +0000 | [diff] [blame] | 242 | self.write('--' + boundary + self._NL) |
Guido van Rossum | 8b3febe | 2007-08-30 01:15:14 +0000 | [diff] [blame] | 243 | # body-part |
| 244 | if msgtexts: |
| 245 | self._fp.write(msgtexts.pop(0)) |
| 246 | # *encapsulation |
| 247 | # --> delimiter transport-padding |
| 248 | # --> CRLF body-part |
| 249 | for body_part in msgtexts: |
| 250 | # delimiter transport-padding CRLF |
R. David Murray | 8451c4b | 2010-10-23 22:19:56 +0000 | [diff] [blame] | 251 | self.write(self._NL + '--' + boundary + self._NL) |
Guido van Rossum | 8b3febe | 2007-08-30 01:15:14 +0000 | [diff] [blame] | 252 | # body-part |
| 253 | self._fp.write(body_part) |
| 254 | # close-delimiter transport-padding |
R. David Murray | 8451c4b | 2010-10-23 22:19:56 +0000 | [diff] [blame] | 255 | self.write(self._NL + '--' + boundary + '--') |
Guido van Rossum | 8b3febe | 2007-08-30 01:15:14 +0000 | [diff] [blame] | 256 | if msg.epilogue is not None: |
R. David Murray | 8451c4b | 2010-10-23 22:19:56 +0000 | [diff] [blame] | 257 | self.write(self._NL) |
R David Murray | 6a31bc6 | 2012-07-22 21:47:53 -0400 | [diff] [blame] | 258 | if self._mangle_from_: |
| 259 | epilogue = fcre.sub('>From ', msg.epilogue) |
| 260 | else: |
| 261 | epilogue = msg.epilogue |
| 262 | self.write(epilogue) |
Guido van Rossum | 8b3febe | 2007-08-30 01:15:14 +0000 | [diff] [blame] | 263 | |
R. David Murray | a8f480f | 2010-01-16 18:30:03 +0000 | [diff] [blame] | 264 | def _handle_multipart_signed(self, msg): |
| 265 | # The contents of signed parts has to stay unmodified in order to keep |
| 266 | # the signature intact per RFC1847 2.1, so we disable header wrapping. |
| 267 | # RDM: This isn't enough to completely preserve the part, but it helps. |
| 268 | old_maxheaderlen = self._maxheaderlen |
| 269 | try: |
| 270 | self._maxheaderlen = 0 |
| 271 | self._handle_multipart(msg) |
| 272 | finally: |
| 273 | self._maxheaderlen = old_maxheaderlen |
| 274 | |
Guido van Rossum | 8b3febe | 2007-08-30 01:15:14 +0000 | [diff] [blame] | 275 | def _handle_message_delivery_status(self, msg): |
| 276 | # We can't just write the headers directly to self's file object |
| 277 | # because this will leave an extra newline between the last header |
| 278 | # block and the boundary. Sigh. |
| 279 | blocks = [] |
| 280 | for part in msg.get_payload(): |
R. David Murray | 96fd54e | 2010-10-08 15:55:28 +0000 | [diff] [blame] | 281 | s = self._new_buffer() |
Guido van Rossum | 8b3febe | 2007-08-30 01:15:14 +0000 | [diff] [blame] | 282 | g = self.clone(s) |
R. David Murray | 719a449 | 2010-11-21 16:53:48 +0000 | [diff] [blame] | 283 | g.flatten(part, unixfrom=False, linesep=self._NL) |
Guido van Rossum | 8b3febe | 2007-08-30 01:15:14 +0000 | [diff] [blame] | 284 | text = s.getvalue() |
R. David Murray | 8451c4b | 2010-10-23 22:19:56 +0000 | [diff] [blame] | 285 | lines = text.split(self._encoded_NL) |
Guido van Rossum | 8b3febe | 2007-08-30 01:15:14 +0000 | [diff] [blame] | 286 | # Strip off the unnecessary trailing empty line |
R. David Murray | 8451c4b | 2010-10-23 22:19:56 +0000 | [diff] [blame] | 287 | if lines and lines[-1] == self._encoded_EMPTY: |
| 288 | blocks.append(self._encoded_NL.join(lines[:-1])) |
Guido van Rossum | 8b3febe | 2007-08-30 01:15:14 +0000 | [diff] [blame] | 289 | else: |
| 290 | blocks.append(text) |
| 291 | # Now join all the blocks with an empty line. This has the lovely |
| 292 | # effect of separating each block with an empty line, but not adding |
| 293 | # an extra one after the last one. |
R. David Murray | 8451c4b | 2010-10-23 22:19:56 +0000 | [diff] [blame] | 294 | self._fp.write(self._encoded_NL.join(blocks)) |
Guido van Rossum | 8b3febe | 2007-08-30 01:15:14 +0000 | [diff] [blame] | 295 | |
| 296 | def _handle_message(self, msg): |
R. David Murray | 96fd54e | 2010-10-08 15:55:28 +0000 | [diff] [blame] | 297 | s = self._new_buffer() |
Guido van Rossum | 8b3febe | 2007-08-30 01:15:14 +0000 | [diff] [blame] | 298 | g = self.clone(s) |
| 299 | # The payload of a message/rfc822 part should be a multipart sequence |
| 300 | # of length 1. The zeroth element of the list should be the Message |
| 301 | # object for the subpart. Extract that object, stringify it, and |
| 302 | # write it out. |
R. David Murray | 57c45ac | 2010-02-21 04:39:40 +0000 | [diff] [blame] | 303 | # Except, it turns out, when it's a string instead, which happens when |
| 304 | # and only when HeaderParser is used on a message of mime type |
| 305 | # message/rfc822. Such messages are generated by, for example, |
| 306 | # Groupwise when forwarding unadorned messages. (Issue 7970.) So |
| 307 | # in that case we just emit the string body. |
| 308 | payload = msg.get_payload() |
| 309 | if isinstance(payload, list): |
R. David Murray | 719a449 | 2010-11-21 16:53:48 +0000 | [diff] [blame] | 310 | g.flatten(msg.get_payload(0), unixfrom=False, linesep=self._NL) |
R. David Murray | 57c45ac | 2010-02-21 04:39:40 +0000 | [diff] [blame] | 311 | payload = s.getvalue() |
| 312 | self._fp.write(payload) |
Guido van Rossum | 8b3febe | 2007-08-30 01:15:14 +0000 | [diff] [blame] | 313 | |
R. David Murray | 96fd54e | 2010-10-08 15:55:28 +0000 | [diff] [blame] | 314 | # This used to be a module level function; we use a classmethod for this |
| 315 | # and _compile_re so we can continue to provide the module level function |
| 316 | # for backward compatibility by doing |
| 317 | # _make_boudary = Generator._make_boundary |
| 318 | # at the end of the module. It *is* internal, so we could drop that... |
| 319 | @classmethod |
| 320 | def _make_boundary(cls, text=None): |
| 321 | # Craft a random boundary. If text is given, ensure that the chosen |
| 322 | # boundary doesn't appear in the text. |
| 323 | token = random.randrange(sys.maxsize) |
| 324 | boundary = ('=' * 15) + (_fmt % token) + '==' |
| 325 | if text is None: |
| 326 | return boundary |
| 327 | b = boundary |
| 328 | counter = 0 |
| 329 | while True: |
| 330 | cre = cls._compile_re('^--' + re.escape(b) + '(--)?$', re.MULTILINE) |
| 331 | if not cre.search(text): |
| 332 | break |
| 333 | b = boundary + '.' + str(counter) |
| 334 | counter += 1 |
| 335 | return b |
| 336 | |
| 337 | @classmethod |
| 338 | def _compile_re(cls, s, flags): |
| 339 | return re.compile(s, flags) |
| 340 | |
| 341 | |
| 342 | class BytesGenerator(Generator): |
| 343 | """Generates a bytes version of a Message object tree. |
| 344 | |
| 345 | Functionally identical to the base Generator except that the output is |
| 346 | bytes and not string. When surrogates were used in the input to encode |
| 347 | bytes, these are decoded back to bytes for output. |
| 348 | |
| 349 | The outfp object must accept bytes in its write method. |
| 350 | """ |
| 351 | |
R. David Murray | 8451c4b | 2010-10-23 22:19:56 +0000 | [diff] [blame] | 352 | # Bytes versions of this constant for use in manipulating data from |
R. David Murray | 96fd54e | 2010-10-08 15:55:28 +0000 | [diff] [blame] | 353 | # the BytesIO buffer. |
R. David Murray | 8451c4b | 2010-10-23 22:19:56 +0000 | [diff] [blame] | 354 | _encoded_EMPTY = b'' |
R. David Murray | 96fd54e | 2010-10-08 15:55:28 +0000 | [diff] [blame] | 355 | |
| 356 | def write(self, s): |
| 357 | self._fp.write(s.encode('ascii', 'surrogateescape')) |
| 358 | |
| 359 | def _new_buffer(self): |
| 360 | return BytesIO() |
| 361 | |
R. David Murray | 8451c4b | 2010-10-23 22:19:56 +0000 | [diff] [blame] | 362 | def _encode(self, s): |
| 363 | return s.encode('ascii') |
| 364 | |
R. David Murray | 96fd54e | 2010-10-08 15:55:28 +0000 | [diff] [blame] | 365 | def _write_headers(self, msg): |
| 366 | # This is almost the same as the string version, except for handling |
| 367 | # strings with 8bit bytes. |
| 368 | for h, v in msg._headers: |
| 369 | self.write('%s: ' % h) |
| 370 | if isinstance(v, Header): |
R David Murray | 9fd170e | 2012-03-14 14:05:03 -0400 | [diff] [blame] | 371 | self.write(v.encode(maxlinelen=self._maxheaderlen)+self._NL) |
R. David Murray | 96fd54e | 2010-10-08 15:55:28 +0000 | [diff] [blame] | 372 | elif _has_surrogates(v): |
| 373 | # If we have raw 8bit data in a byte string, we have no idea |
| 374 | # what the encoding is. There is no safe way to split this |
| 375 | # string. If it's ascii-subset, then we could do a normal |
| 376 | # ascii split, but if it's multibyte then we could break the |
| 377 | # string. There's no way to know so the least harm seems to |
| 378 | # be to not split the string and risk it being too long. |
| 379 | self.write(v+NL) |
| 380 | else: |
| 381 | # Header's got lots of smarts and this string is safe... |
| 382 | header = Header(v, maxlinelen=self._maxheaderlen, |
| 383 | header_name=h) |
R. David Murray | 8451c4b | 2010-10-23 22:19:56 +0000 | [diff] [blame] | 384 | self.write(header.encode(linesep=self._NL)+self._NL) |
R. David Murray | 96fd54e | 2010-10-08 15:55:28 +0000 | [diff] [blame] | 385 | # A blank line always separates headers from body |
R. David Murray | 8451c4b | 2010-10-23 22:19:56 +0000 | [diff] [blame] | 386 | self.write(self._NL) |
R. David Murray | 96fd54e | 2010-10-08 15:55:28 +0000 | [diff] [blame] | 387 | |
| 388 | def _handle_text(self, msg): |
| 389 | # If the string has surrogates the original source was bytes, so |
| 390 | # just write it back out. |
R. David Murray | 7372a07 | 2011-01-26 21:21:32 +0000 | [diff] [blame] | 391 | if msg._payload is None: |
| 392 | return |
R. David Murray | bdd2d93 | 2011-01-26 02:31:37 +0000 | [diff] [blame] | 393 | if _has_surrogates(msg._payload): |
R David Murray | 638d40b | 2012-08-24 11:14:13 -0400 | [diff] [blame^] | 394 | if self._mangle_from_: |
| 395 | msg._payload = fcre.sub(">From ", msg._payload) |
R. David Murray | bdd2d93 | 2011-01-26 02:31:37 +0000 | [diff] [blame] | 396 | self.write(msg._payload) |
R. David Murray | 96fd54e | 2010-10-08 15:55:28 +0000 | [diff] [blame] | 397 | else: |
| 398 | super(BytesGenerator,self)._handle_text(msg) |
| 399 | |
| 400 | @classmethod |
| 401 | def _compile_re(cls, s, flags): |
| 402 | return re.compile(s.encode('ascii'), flags) |
| 403 | |
Guido van Rossum | 8b3febe | 2007-08-30 01:15:14 +0000 | [diff] [blame] | 404 | |
| 405 | |
| 406 | _FMT = '[Non-text (%(type)s) part of message omitted, filename %(filename)s]' |
| 407 | |
| 408 | class DecodedGenerator(Generator): |
R. David Murray | 70a9993 | 2010-10-01 20:38:33 +0000 | [diff] [blame] | 409 | """Generates a text representation of a message. |
Guido van Rossum | 8b3febe | 2007-08-30 01:15:14 +0000 | [diff] [blame] | 410 | |
| 411 | Like the Generator base class, except that non-text parts are substituted |
| 412 | with a format string representing the part. |
| 413 | """ |
| 414 | def __init__(self, outfp, mangle_from_=True, maxheaderlen=78, fmt=None): |
| 415 | """Like Generator.__init__() except that an additional optional |
| 416 | argument is allowed. |
| 417 | |
| 418 | Walks through all subparts of a message. If the subpart is of main |
| 419 | type `text', then it prints the decoded payload of the subpart. |
| 420 | |
| 421 | Otherwise, fmt is a format string that is used instead of the message |
| 422 | payload. fmt is expanded with the following keywords (in |
| 423 | %(keyword)s format): |
| 424 | |
| 425 | type : Full MIME type of the non-text part |
| 426 | maintype : Main MIME type of the non-text part |
| 427 | subtype : Sub-MIME type of the non-text part |
| 428 | filename : Filename of the non-text part |
| 429 | description: Description associated with the non-text part |
| 430 | encoding : Content transfer encoding of the non-text part |
| 431 | |
| 432 | The default value for fmt is None, meaning |
| 433 | |
| 434 | [Non-text (%(type)s) part of message omitted, filename %(filename)s] |
| 435 | """ |
| 436 | Generator.__init__(self, outfp, mangle_from_, maxheaderlen) |
| 437 | if fmt is None: |
| 438 | self._fmt = _FMT |
| 439 | else: |
| 440 | self._fmt = fmt |
| 441 | |
| 442 | def _dispatch(self, msg): |
| 443 | for part in msg.walk(): |
| 444 | maintype = part.get_content_maintype() |
| 445 | if maintype == 'text': |
Guido van Rossum | 3172c5d | 2007-10-16 18:12:55 +0000 | [diff] [blame] | 446 | print(part.get_payload(decode=False), file=self) |
Guido van Rossum | 8b3febe | 2007-08-30 01:15:14 +0000 | [diff] [blame] | 447 | elif maintype == 'multipart': |
| 448 | # Just skip this |
| 449 | pass |
| 450 | else: |
| 451 | print(self._fmt % { |
| 452 | 'type' : part.get_content_type(), |
| 453 | 'maintype' : part.get_content_maintype(), |
| 454 | 'subtype' : part.get_content_subtype(), |
| 455 | 'filename' : part.get_filename('[no filename]'), |
| 456 | 'description': part.get('Content-Description', |
| 457 | '[no description]'), |
| 458 | 'encoding' : part.get('Content-Transfer-Encoding', |
| 459 | '[no encoding]'), |
| 460 | }, file=self) |
| 461 | |
| 462 | |
| 463 | |
R. David Murray | 96fd54e | 2010-10-08 15:55:28 +0000 | [diff] [blame] | 464 | # Helper used by Generator._make_boundary |
Christian Heimes | a37d4c6 | 2007-12-04 23:02:19 +0000 | [diff] [blame] | 465 | _width = len(repr(sys.maxsize-1)) |
Guido van Rossum | 8b3febe | 2007-08-30 01:15:14 +0000 | [diff] [blame] | 466 | _fmt = '%%0%dd' % _width |
| 467 | |
R. David Murray | 96fd54e | 2010-10-08 15:55:28 +0000 | [diff] [blame] | 468 | # Backward compatibility |
| 469 | _make_boundary = Generator._make_boundary |