Dump message contents to target file.
(self, message, target, mangle_from_=False)
| 215 | _append_newline = False |
| 216 | |
| 217 | def _dump_message(self, message, target, mangle_from_=False): |
| 218 | # This assumes the target file is open in binary mode. |
| 219 | """Dump message contents to target file.""" |
| 220 | if isinstance(message, email.message.Message): |
| 221 | buffer = io.BytesIO() |
| 222 | gen = email.generator.BytesGenerator(buffer, mangle_from_, 0) |
| 223 | gen.flatten(message) |
| 224 | buffer.seek(0) |
| 225 | data = buffer.read() |
| 226 | data = data.replace(b'\n', linesep) |
| 227 | target.write(data) |
| 228 | if self._append_newline and not data.endswith(linesep): |
| 229 | # Make sure the message ends with a newline |
| 230 | target.write(linesep) |
| 231 | elif isinstance(message, (str, bytes, io.StringIO)): |
| 232 | if isinstance(message, io.StringIO): |
| 233 | warnings.warn("Use of StringIO input is deprecated, " |
| 234 | "use BytesIO instead", DeprecationWarning, 3) |
| 235 | message = message.getvalue() |
| 236 | if isinstance(message, str): |
| 237 | message = self._string_to_bytes(message) |
| 238 | if mangle_from_: |
| 239 | message = message.replace(b'\nFrom ', b'\n>From ') |
| 240 | message = message.replace(b'\n', linesep) |
| 241 | target.write(message) |
| 242 | if self._append_newline and not message.endswith(linesep): |
| 243 | # Make sure the message ends with a newline |
| 244 | target.write(linesep) |
| 245 | elif hasattr(message, 'read'): |
| 246 | if hasattr(message, 'buffer'): |
| 247 | warnings.warn("Use of text mode files is deprecated, " |
| 248 | "use a binary mode file instead", DeprecationWarning, 3) |
| 249 | message = message.buffer |
| 250 | lastline = None |
| 251 | while True: |
| 252 | line = message.readline() |
| 253 | # Universal newline support. |
| 254 | if line.endswith(b'\r\n'): |
| 255 | line = line[:-2] + b'\n' |
| 256 | elif line.endswith(b'\r'): |
| 257 | line = line[:-1] + b'\n' |
| 258 | if not line: |
| 259 | break |
| 260 | if mangle_from_ and line.startswith(b'From '): |
| 261 | line = b'>From ' + line[5:] |
| 262 | line = line.replace(b'\n', linesep) |
| 263 | target.write(line) |
| 264 | lastline = line |
| 265 | if self._append_newline and lastline and not lastline.endswith(linesep): |
| 266 | # Make sure the message ends with a newline |
| 267 | target.write(linesep) |
| 268 | else: |
| 269 | raise TypeError('Invalid message type: %s' % type(message)) |
| 270 | |
| 271 | __class_getitem__ = classmethod(GenericAlias) |
| 272 |