我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用email.generator()。
def test_mime_attachments_in_constructor(self): eq = self.assertEqual text1 = MIMEText('') text2 = MIMEText('') msg = MIMEMultipart(_subparts=(text1, text2)) eq(len(msg.get_payload()), 2) eq(msg.get_payload(0), text1) eq(msg.get_payload(1), text2) # A general test of parser->model->generator idempotency. IOW, read a message # in, parse it into a message object tree, then without touching the tree, # regenerate the plain text. The original text and the transformed text # should be identical. Note: that we ignore the Unix-From since that may # contain a changed date.
def test__all__(self): module = __import__('email') # Can't use sorted() here due to Python 2.3 compatibility all = module.__all__[:] all.sort() self.assertEqual(all, [ # Old names 'Charset', 'Encoders', 'Errors', 'Generator', 'Header', 'Iterators', 'MIMEAudio', 'MIMEBase', 'MIMEImage', 'MIMEMessage', 'MIMEMultipart', 'MIMENonMultipart', 'MIMEText', 'Message', 'Parser', 'Utils', 'base64MIME', # new names 'base64mime', 'charset', 'encoders', 'errors', 'generator', 'header', 'iterators', 'message', 'message_from_file', 'message_from_string', 'mime', 'parser', 'quopriMIME', 'quoprimime', 'utils', ])
def test_as_string(self): eq = self.assertEqual msg = self._msgobj('msg_01.txt') fp = openfile('msg_01.txt') try: # BAW 30-Mar-2009 Evil be here. So, the generator is broken with # respect to long line breaking. It's also not idempotent when a # header from a parsed message is continued with tabs rather than # spaces. Before we fixed bug 1974 it was reversedly broken, # i.e. headers that were continued with spaces got continued with # tabs. For Python 2.x there's really no good fix and in Python # 3.x all this stuff is re-written to be right(er). Chris Withers # convinced me that using space as the default continuation # character is less bad for more applications. text = fp.read().replace('\t', ' ') finally: fp.close() self.ndiffAssertEqual(text, msg.as_string()) fullrepr = str(msg) lines = fullrepr.split('\n') self.assertTrue(lines[0].startswith('From ')) eq(text, NL.join(lines[1:]))
def _dump_message(self, message, target, mangle_from_=False): # Most files are opened in binary mode to allow predictable seeking. # To get native line endings on disk, the user-friendly \n line endings # used in strings and by email.Message are translated here. """Dump message contents to target file.""" if isinstance(message, email.message.Message): buffer = StringIO.StringIO() gen = email.generator.Generator(buffer, mangle_from_, 0) gen.flatten(message) buffer.seek(0) target.write(buffer.read().replace('\n', os.linesep)) elif isinstance(message, str): if mangle_from_: message = message.replace('\nFrom ', '\n>From ') message = message.replace('\n', os.linesep) target.write(message) elif hasattr(message, 'read'): while True: line = message.readline() if line == '': break if mangle_from_ and line.startswith('From '): line = '>From ' + line[5:] line = line.replace('\n', os.linesep) target.write(line) else: raise TypeError('Invalid message type: %s' % type(message))
def _dump_message(self, message, target, mangle_from_=False): # Most files are opened in binary mode to allow predictable seeking. # To get native line endings on disk, the user-friendly \n line endings # used in strings and by email.Message are translated here. """Dump message contents to target file.""" if isinstance(message, email.message.Message): buffer = StringIO.StringIO() gen = email.generator.Generator(buffer, mangle_from_, 0) gen.flatten(message) buffer.seek(0) data = buffer.read().replace('\n', os.linesep) target.write(data) if self._append_newline and not data.endswith(os.linesep): # Make sure the message ends with a newline target.write(os.linesep) elif isinstance(message, str): if mangle_from_: message = message.replace('\nFrom ', '\n>From ') message = message.replace('\n', os.linesep) target.write(message) if self._append_newline and not message.endswith(os.linesep): # Make sure the message ends with a newline target.write(os.linesep) elif hasattr(message, 'read'): lastline = None while True: line = message.readline() if line == '': break if mangle_from_ and line.startswith('From '): line = '>From ' + line[5:] line = line.replace('\n', os.linesep) target.write(line) lastline = line if self._append_newline and lastline and not lastline.endswith(os.linesep): # Make sure the message ends with a newline target.write(os.linesep) else: raise TypeError('Invalid message type: %s' % type(message))
def test_default_multipart_constructor(self): msg = MIMEMultipart() self.assertTrue(msg.is_multipart()) # A general test of parser->model->generator idempotency. IOW, read a message # in, parse it into a message object tree, then without touching the tree, # regenerate the plain text. The original text and the transformed text # should be identical. Note: that we ignore the Unix-From since that may # contain a changed date.
def test__all__(self): module = __import__('email') # Can't use sorted() here due to Python 2.3 compatibility all = module.__all__[:] all.sort() self.assertEqual(all, [ 'base64mime', 'charset', 'encoders', 'errors', 'generator', 'header', 'iterators', 'message', 'message_from_binary_file', 'message_from_bytes', 'message_from_file', 'message_from_string', 'mime', 'parser', 'quoprimime', 'utils', ])
def test_bytes_generator(self): msg = email.message_from_bytes(self.non_latin_bin_msg) out = BytesIO() email.generator.BytesGenerator(out).flatten(msg) self.assertEqual(out.getvalue(), self.non_latin_bin_msg)
def test_bytes_generator_handles_None_body(self): #Issue 11019 msg = email.message.Message() out = BytesIO() email.generator.BytesGenerator(out).flatten(msg) self.assertEqual(out.getvalue(), b"\n")
def test_generator_handles_8bit(self): msg = email.message_from_bytes(self.non_latin_bin_msg) out = StringIO() email.generator.Generator(out).flatten(msg) self.assertEqual(out.getvalue(), self.non_latin_bin_msg_as7bit_wrapped)
def test_decoded_generator_emits_unicode_body(self): m = email.message_from_bytes(self.latin_bin_msg) out = StringIO() email.generator.DecodedGenerator(out).flatten(m) #DecodedHeader output contains an extra blank line compared #to the input message. RDM: not sure if this is a bug or not, #but it is not specific to the 8bit->7bit conversion. self.assertEqual(out.getvalue(), self.latin_bin_msg.decode('latin-1')+'\n')
def test_crlf_flatten(self): with openfile('msg_26.txt', 'rb') as fp: text = fp.read() msg = email.message_from_bytes(text) s = BytesIO() g = email.generator.BytesGenerator(s) g.flatten(msg, linesep='\r\n') self.assertEqual(s.getvalue(), text)
def _idempotent(self, msg, data, unixfrom=False): b = BytesIO() g = email.generator.BytesGenerator(b, maxheaderlen=0) g.flatten(msg, unixfrom=unixfrom, linesep=self.linesep) self.assertByteStringsEqual(data, b.getvalue())
def test_byte_message_rfc822_only(self): # Make sure new bytes header parser also passes this. with openfile('msg_46.txt') as fp: msgdata = fp.read().encode('ascii') parser = email.parser.BytesHeaderParser() msg = parser.parsebytes(msgdata) out = BytesIO() gen = email.generator.BytesGenerator(out) gen.flatten(msg) self.assertEqual(out.getvalue(), msgdata)
def test__all__(self): module = __import__('email') self.assertEqual(sorted(module.__all__), [ 'base64mime', 'charset', 'encoders', 'errors', 'feedparser', 'generator', 'header', 'iterators', 'message', 'message_from_binary_file', 'message_from_bytes', 'message_from_file', 'message_from_string', 'mime', 'parser', 'quoprimime', 'utils', ])
def test_Generator_linend(self): # Issue 14645. with openfile('msg_26.txt', newline='\n') as f: msgtxt = f.read() msgtxt_nl = msgtxt.replace('\r\n', '\n') msg = email.message_from_string(msgtxt) s = StringIO() g = email.generator.Generator(s) g.flatten(msg) self.assertEqual(s.getvalue(), msgtxt_nl)
def test_BytesGenerator_linend(self): # Issue 14645. with openfile('msg_26.txt', newline='\n') as f: msgtxt = f.read() msgtxt_nl = msgtxt.replace('\r\n', '\n') msg = email.message_from_string(msgtxt_nl) s = BytesIO() g = email.generator.BytesGenerator(s) g.flatten(msg, linesep='\r\n') self.assertEqual(s.getvalue().decode('ascii'), msgtxt)