Debian Codegraph @

lib-python/3/test/test_email/test_email.py

raw symbols SCIP
1 # Copyright (C) 2001-2010 Python Software Foundation
2 # Contact: [email protected]
3 # email package unit tests
4
5 import re
6 import time
7 import base64
8 import unittest
9 import textwrap
10 import warnings
11
12 from io import StringIO, BytesIO
13 from itertools import chain
14 from random import choice
15 from threading import Thread
16 from unittest.mock import patch
17
18 import email
19 import email.policy
20 import email.utils
21
22 from email.charset import Charset
23 from email.generator import Generator, DecodedGenerator, BytesGenerator
24 from email.header import Header, decode_header, make_header
25 from email.headerregistry import HeaderRegistry
26 from email.message import Message
27 from email.mime.application import MIMEApplication
28 from email.mime.audio import MIMEAudio
29 from email.mime.base import MIMEBase
30 from email.mime.image import MIMEImage
31 from email.mime.message import MIMEMessage
32 from email.mime.multipart import MIMEMultipart
33 from email.mime.nonmultipart import MIMENonMultipart
34 from email.mime.text import MIMEText
35 from email.parser import Parser, HeaderParser
36 from email import base64mime
37 from email import encoders
38 from email import errors
39 from email import iterators
40 from email import quoprimime
41 from email import utils
42
43 from test import support
44 from test.support import threading_helper
45 from test.support.os_helper import unlink
46 from test.test_email import openfile, TestEmailBase
47
48 # These imports are documented to work, but we are testing them using a
49 # different path, so we import them here just to make sure they are importable.
50 from email.parser import FeedParser, BytesFeedParser
51
52 NL = '\n'
53 EMPTYSTRING = ''
54 SPACE = ' '
55
56
57 # Test various aspects of the Message class's API
58 class TestMessageAPI(TestEmailBase):
59 def test_get_all(self):
60 eq = self.assertEqual
61 msg = self._msgobj('msg_20.txt')
62 eq(msg.get_all('cc'), ['[email protected]', '[email protected]', '[email protected]'])
63 eq(msg.get_all('xx', 'n/a'), 'n/a')
64
65 def test_getset_charset(self):
66 eq = self.assertEqual
67 msg = Message()
68 eq(msg.get_charset(), None)
69 charset = Charset('iso-8859-1')
70 msg.set_charset(charset)
71 eq(msg['mime-version'], '1.0')
72 eq(msg.get_content_type(), 'text/plain')
73 eq(msg['content-type'], 'text/plain; charset="iso-8859-1"')
74 eq(msg.get_param('charset'), 'iso-8859-1')
75 eq(msg['content-transfer-encoding'], 'quoted-printable')
76 eq(msg.get_charset().input_charset, 'iso-8859-1')
77 # Remove the charset
78 msg.set_charset(None)
79 eq(msg.get_charset(), None)
80 eq(msg['content-type'], 'text/plain')
81 # Try adding a charset when there's already MIME headers present
82 msg = Message()
83 msg['MIME-Version'] = '2.0'
84 msg['Content-Type'] = 'text/x-weird'
85 msg['Content-Transfer-Encoding'] = 'quinted-puntable'
86 msg.set_charset(charset)
87 eq(msg['mime-version'], '2.0')
88 eq(msg['content-type'], 'text/x-weird; charset="iso-8859-1"')
89 eq(msg['content-transfer-encoding'], 'quinted-puntable')
90
91 def test_set_charset_from_string(self):
92 eq = self.assertEqual
93 msg = Message()
94 msg.set_charset('us-ascii')
95 eq(msg.get_charset().input_charset, 'us-ascii')
96 eq(msg['content-type'], 'text/plain; charset="us-ascii"')
97
98 def test_set_payload_with_charset(self):
99 msg = Message()
100 charset = Charset('iso-8859-1')
101 msg.set_payload('This is a string payload', charset)
102 self.assertEqual(msg.get_charset().input_charset, 'iso-8859-1')
103
104 def test_set_payload_with_8bit_data_and_charset(self):
105 data = b'\xd0\x90\xd0\x91\xd0\x92'
106 charset = Charset('utf-8')
107 msg = Message()
108 msg.set_payload(data, charset)
109 self.assertEqual(msg['content-transfer-encoding'], 'base64')
110 self.assertEqual(msg.get_payload(decode=True), data)
111 self.assertEqual(msg.get_payload(), '0JDQkdCS\n')
112
113 def test_set_payload_with_non_ascii_and_charset_body_encoding_none(self):
114 data = b'\xd0\x90\xd0\x91\xd0\x92'
115 charset = Charset('utf-8')
116 charset.body_encoding = None # Disable base64 encoding
117 msg = Message()
118 msg.set_payload(data.decode('utf-8'), charset)
119 self.assertEqual(msg['content-transfer-encoding'], '8bit')
120 self.assertEqual(msg.get_payload(decode=True), data)
121
122 def test_set_payload_with_8bit_data_and_charset_body_encoding_none(self):
123 data = b'\xd0\x90\xd0\x91\xd0\x92'
124 charset = Charset('utf-8')
125 charset.body_encoding = None # Disable base64 encoding
126 msg = Message()
127 msg.set_payload(data, charset)
128 self.assertEqual(msg['content-transfer-encoding'], '8bit')
129 self.assertEqual(msg.get_payload(decode=True), data)
130
131 def test_set_payload_to_list(self):
132 msg = Message()
133 msg.set_payload([])
134 self.assertEqual(msg.get_payload(), [])
135
136 def test_attach_when_payload_is_string(self):
137 msg = Message()
138 msg['Content-Type'] = 'multipart/mixed'
139 msg.set_payload('string payload')
140 sub_msg = MIMEMessage(Message())
141 self.assertRaisesRegex(TypeError, "[Aa]ttach.*non-multipart",
142 msg.attach, sub_msg)
143
144 def test_get_charsets(self):
145 eq = self.assertEqual
146
147 msg = self._msgobj('msg_08.txt')
148 charsets = msg.get_charsets()
149 eq(charsets, [None, 'us-ascii', 'iso-8859-1', 'iso-8859-2', 'koi8-r'])
150
151 msg = self._msgobj('msg_09.txt')
152 charsets = msg.get_charsets('dingbat')
153 eq(charsets, ['dingbat', 'us-ascii', 'iso-8859-1', 'dingbat',
154 'koi8-r'])
155
156 msg = self._msgobj('msg_12.txt')
157 charsets = msg.get_charsets()
158 eq(charsets, [None, 'us-ascii', 'iso-8859-1', None, 'iso-8859-2',
159 'iso-8859-3', 'us-ascii', 'koi8-r'])
160
161 def test_get_filename(self):
162 eq = self.assertEqual
163
164 msg = self._msgobj('msg_04.txt')
165 filenames = [p.get_filename() for p in msg.get_payload()]
166 eq(filenames, ['msg.txt', 'msg.txt'])
167
168 msg = self._msgobj('msg_07.txt')
169 subpart = msg.get_payload(1)
170 eq(subpart.get_filename(), 'dingusfish.gif')
171
172 def test_get_filename_with_name_parameter(self):
173 eq = self.assertEqual
174
175 msg = self._msgobj('msg_44.txt')
176 filenames = [p.get_filename() for p in msg.get_payload()]
177 eq(filenames, ['msg.txt', 'msg.txt'])
178
179 def test_get_boundary(self):
180 eq = self.assertEqual
181 msg = self._msgobj('msg_07.txt')
182 # No quotes!
183 eq(msg.get_boundary(), 'BOUNDARY')
184
185 def test_set_boundary(self):
186 eq = self.assertEqual
187 # This one has no existing boundary parameter, but the Content-Type:
188 # header appears fifth.
189 msg = self._msgobj('msg_01.txt')
190 msg.set_boundary('BOUNDARY')
191 header, value = msg.items()[4]
192 eq(header.lower(), 'content-type')
193 eq(value, 'text/plain; charset="us-ascii"; boundary="BOUNDARY"')
194 # This one has a Content-Type: header, with a boundary, stuck in the
195 # middle of its headers. Make sure the order is preserved; it should
196 # be fifth.
197 msg = self._msgobj('msg_04.txt')
198 msg.set_boundary('BOUNDARY')
199 header, value = msg.items()[4]
200 eq(header.lower(), 'content-type')
201 eq(value, 'multipart/mixed; boundary="BOUNDARY"')
202 # And this one has no Content-Type: header at all.
203 msg = self._msgobj('msg_03.txt')
204 self.assertRaises(errors.HeaderParseError,
205 msg.set_boundary, 'BOUNDARY')
206
207 def test_make_boundary(self):
208 msg = MIMEMultipart('form-data')
209 # Note that when the boundary gets created is an implementation
210 # detail and might change.
211 self.assertEqual(msg.items()[0][1], 'multipart/form-data')
212 # Trigger creation of boundary
213 msg.as_string()
214 self.assertEqual(msg.items()[0][1][:33],
215 'multipart/form-data; boundary="==')
216 # XXX: there ought to be tests of the uniqueness of the boundary, too.
217
218 def test_message_rfc822_only(self):
219 # Issue 7970: message/rfc822 not in multipart parsed by
220 # HeaderParser caused an exception when flattened.
221 with openfile('msg_46.txt', encoding="utf-8") as fp:
222 msgdata = fp.read()
223 parser = HeaderParser()
224 msg = parser.parsestr(msgdata)
225 out = StringIO()
226 gen = Generator(out, True, 0)
227 gen.flatten(msg, False)
228 self.assertEqual(out.getvalue(), msgdata)
229
230 def test_byte_message_rfc822_only(self):
231 # Make sure new bytes header parser also passes this.
232 with openfile('msg_46.txt', encoding="utf-8") as fp:
233 msgdata = fp.read().encode('ascii')
234 parser = email.parser.BytesHeaderParser()
235 msg = parser.parsebytes(msgdata)
236 out = BytesIO()
237 gen = email.generator.BytesGenerator(out)
238 gen.flatten(msg)
239 self.assertEqual(out.getvalue(), msgdata)
240
241 def test_get_decoded_payload(self):
242 eq = self.assertEqual
243 msg = self._msgobj('msg_10.txt')
244 # The outer message is a multipart
245 eq(msg.get_payload(decode=True), None)
246 # Subpart 1 is 7bit encoded
247 eq(msg.get_payload(0).get_payload(decode=True),
248 b'This is a 7bit encoded message.\n')
249 # Subpart 2 is quopri
250 eq(msg.get_payload(1).get_payload(decode=True),
251 b'\xa1This is a Quoted Printable encoded message!\n')
252 # Subpart 3 is base64
253 eq(msg.get_payload(2).get_payload(decode=True),
254 b'This is a Base64 encoded message.')
255 # Subpart 4 is base64 with a trailing newline, which
256 # used to be stripped (issue 7143).
257 eq(msg.get_payload(3).get_payload(decode=True),
258 b'This is a Base64 encoded message.\n')
259 # Subpart 5 has no Content-Transfer-Encoding: header.
260 eq(msg.get_payload(4).get_payload(decode=True),
261 b'This has no Content-Transfer-Encoding: header.\n')
262
263 def test_get_decoded_uu_payload(self):
264 eq = self.assertEqual
265 msg = Message()
266 msg.set_payload('begin 666 -\n+:&5L;&\\@=V]R;&0 \n \nend\n')
267 for cte in ('x-uuencode', 'uuencode', 'uue', 'x-uue'):
268 msg['content-transfer-encoding'] = cte
269 eq(msg.get_payload(decode=True), b'hello world')
270 # Now try some bogus data
271 msg.set_payload('foo')
272 eq(msg.get_payload(decode=True), b'foo')
273
274 def test_get_payload_n_raises_on_non_multipart(self):
275 msg = Message()
276 self.assertRaises(TypeError, msg.get_payload, 1)
277
278 def test_decoded_generator(self):
279 eq = self.assertEqual
280 msg = self._msgobj('msg_07.txt')
281 with openfile('msg_17.txt', encoding="utf-8") as fp:
282 text = fp.read()
283 s = StringIO()
284 g = DecodedGenerator(s)
285 g.flatten(msg)
286 eq(s.getvalue(), text)
287
288 def test__contains__(self):
289 msg = Message()
290 msg['From'] = 'Me'
291 msg['to'] = 'You'
292 # Check for case insensitivity
293 self.assertIn('from', msg)
294 self.assertIn('From', msg)
295 self.assertIn('FROM', msg)
296 self.assertIn('to', msg)
297 self.assertIn('To', msg)
298 self.assertIn('TO', msg)
299
300 def test_as_string(self):
301 msg = self._msgobj('msg_01.txt')
302 with openfile('msg_01.txt', encoding="utf-8") as fp:
303 text = fp.read()
304 self.assertEqual(text, str(msg))
305 fullrepr = msg.as_string(unixfrom=True)
306 lines = fullrepr.split('\n')
307 self.assertTrue(lines[0].startswith('From '))
308 self.assertEqual(text, NL.join(lines[1:]))
309
310 def test_as_string_policy(self):
311 msg = self._msgobj('msg_01.txt')
312 newpolicy = msg.policy.clone(linesep='\r\n')
313 fullrepr = msg.as_string(policy=newpolicy)
314 s = StringIO()
315 g = Generator(s, policy=newpolicy)
316 g.flatten(msg)
317 self.assertEqual(fullrepr, s.getvalue())
318
319 def test_nonascii_as_string_without_cte(self):
320 m = textwrap.dedent("""\
321 MIME-Version: 1.0
322 Content-type: text/plain; charset="iso-8859-1"
323
324 Test if non-ascii messages with no Content-Transfer-Encoding set
325 can be as_string'd:
326 Föö bär
327 """)
328 source = m.encode('iso-8859-1')
329 expected = textwrap.dedent("""\
330 MIME-Version: 1.0
331 Content-type: text/plain; charset="iso-8859-1"
332 Content-Transfer-Encoding: quoted-printable
333
334 Test if non-ascii messages with no Content-Transfer-Encoding set
335 can be as_string'd:
336 F=F6=F6 b=E4r
337 """)
338 msg = email.message_from_bytes(source)
339 self.assertEqual(msg.as_string(), expected)
340
341 def test_nonascii_as_string_with_ascii_charset(self):
342 m = textwrap.dedent("""\
343 MIME-Version: 1.0
344 Content-type: text/plain; charset="us-ascii"
345 Content-Transfer-Encoding: 8bit
346
347 Test if non-ascii messages with no Content-Transfer-Encoding set
348 can be as_string'd:
349 Föö bär
350 """)
351 source = m.encode('iso-8859-1')
352 expected = source.decode('ascii', 'replace')
353 msg = email.message_from_bytes(source)
354 self.assertEqual(msg.as_string(), expected)
355
356 def test_nonascii_as_string_without_content_type_and_cte(self):
357 m = textwrap.dedent("""\
358 MIME-Version: 1.0
359
360 Test if non-ascii messages with no Content-Type nor
361 Content-Transfer-Encoding set can be as_string'd:
362 Föö bär
363 """)
364 source = m.encode('iso-8859-1')
365 expected = source.decode('ascii', 'replace')
366 msg = email.message_from_bytes(source)
367 self.assertEqual(msg.as_string(), expected)
368
369 def test_as_bytes(self):
370 msg = self._msgobj('msg_01.txt')
371 with openfile('msg_01.txt', encoding="utf-8") as fp:
372 data = fp.read().encode('ascii')
373 self.assertEqual(data, bytes(msg))
374 fullrepr = msg.as_bytes(unixfrom=True)
375 lines = fullrepr.split(b'\n')
376 self.assertTrue(lines[0].startswith(b'From '))
377 self.assertEqual(data, b'\n'.join(lines[1:]))
378
379 def test_as_bytes_policy(self):
380 msg = self._msgobj('msg_01.txt')
381 newpolicy = msg.policy.clone(linesep='\r\n')
382 fullrepr = msg.as_bytes(policy=newpolicy)
383 s = BytesIO()
384 g = BytesGenerator(s,policy=newpolicy)
385 g.flatten(msg)
386 self.assertEqual(fullrepr, s.getvalue())
387
388 # test_headerregistry.TestContentTypeHeader.bad_params
389 def test_bad_param(self):
390 msg = email.message_from_string("Content-Type: blarg; baz; boo\n")
391 self.assertEqual(msg.get_param('baz'), '')
392
393 def test_missing_filename(self):
394 msg = email.message_from_string("From: foo\n")
395 self.assertEqual(msg.get_filename(), None)
396
397 def test_bogus_filename(self):
398 msg = email.message_from_string(
399 "Content-Disposition: blarg; filename\n")
400 self.assertEqual(msg.get_filename(), '')
401
402 def test_missing_boundary(self):
403 msg = email.message_from_string("From: foo\n")
404 self.assertEqual(msg.get_boundary(), None)
405
406 def test_get_params(self):
407 eq = self.assertEqual
408 msg = email.message_from_string(
409 'X-Header: foo=one; bar=two; baz=three\n')
410 eq(msg.get_params(header='x-header'),
411 [('foo', 'one'), ('bar', 'two'), ('baz', 'three')])
412 msg = email.message_from_string(
413 'X-Header: foo; bar=one; baz=two\n')
414 eq(msg.get_params(header='x-header'),
415 [('foo', ''), ('bar', 'one'), ('baz', 'two')])
416 eq(msg.get_params(), None)
417 msg = email.message_from_string(
418 'X-Header: foo; bar="one"; baz=two\n')
419 eq(msg.get_params(header='x-header'),
420 [('foo', ''), ('bar', 'one'), ('baz', 'two')])
421
422 # test_headerregistry.TestContentTypeHeader.spaces_around_param_equals
423 def test_get_param_liberal(self):
424 msg = Message()
425 msg['Content-Type'] = 'Content-Type: Multipart/mixed; boundary = "CPIMSSMTPC06p5f3tG"'
426 self.assertEqual(msg.get_param('boundary'), 'CPIMSSMTPC06p5f3tG')
427
428 def test_get_param(self):
429 eq = self.assertEqual
430 msg = email.message_from_string(
431 "X-Header: foo=one; bar=two; baz=three\n")
432 eq(msg.get_param('bar', header='x-header'), 'two')
433 eq(msg.get_param('quuz', header='x-header'), None)
434 eq(msg.get_param('quuz'), None)
435 msg = email.message_from_string(
436 'X-Header: foo; bar="one"; baz=two\n')
437 eq(msg.get_param('foo', header='x-header'), '')
438 eq(msg.get_param('bar', header='x-header'), 'one')
439 eq(msg.get_param('baz', header='x-header'), 'two')
440 # XXX: We are not RFC-2045 compliant! We cannot parse:
441 # msg["Content-Type"] = 'text/plain; weird="hey; dolly? [you] @ <\\"home\\">?"'
442 # msg.get_param("weird")
443 # yet.
444
445 # test_headerregistry.TestContentTypeHeader.spaces_around_semis
446 def test_get_param_funky_continuation_lines(self):
447 msg = self._msgobj('msg_22.txt')
448 self.assertEqual(msg.get_payload(1).get_param('name'), 'wibble.JPG')
449
450 # test_headerregistry.TestContentTypeHeader.semis_inside_quotes
451 def test_get_param_with_semis_in_quotes(self):
452 msg = email.message_from_string(
453 'Content-Type: image/pjpeg; name="Jim&amp;&amp;Jill"\n')
454 self.assertEqual(msg.get_param('name'), 'Jim&amp;&amp;Jill')
455 self.assertEqual(msg.get_param('name', unquote=False),
456 '"Jim&amp;&amp;Jill"')
457
458 # test_headerregistry.TestContentTypeHeader.quotes_inside_rfc2231_value
459 def test_get_param_with_quotes(self):
460 msg = email.message_from_string(
461 'Content-Type: foo; bar*0="baz\\"foobar"; bar*1="\\"baz"')
462 self.assertEqual(msg.get_param('bar'), 'baz"foobar"baz')
463 msg = email.message_from_string(
464 "Content-Type: foo; bar*0=\"baz\\\"foobar\"; bar*1=\"\\\"baz\"")
465 self.assertEqual(msg.get_param('bar'), 'baz"foobar"baz')
466
467 def test_get_param_linear_complexity(self):
468 # Ensure that email.message._parseparam() is fast.
469 # See https://github.com/python/cpython/issues/136063.
470 N = 100_000
471 for s, r in [
472 ("", ""),
473 ("foo=bar", "foo=bar"),
474 (" FOO = bar ", "foo=bar"),
475 ]:
476 with self.subTest(s=s, r=r, N=N):
477 src = f'{s};' * (N - 1) + s
478 res = email.message._parseparam(src)
479 self.assertEqual(len(res), N)
480 self.assertEqual(len(set(res)), 1)
481 self.assertEqual(res[0], r)
482
483 # This will be considered as a single parameter.
484 malformed = 's="' + ';' * (N - 1)
485 res = email.message._parseparam(malformed)
486 self.assertEqual(res, [malformed])
487
488 def test_field_containment(self):
489 msg = email.message_from_string('Header: exists')
490 self.assertIn('header', msg)
491 self.assertIn('Header', msg)
492 self.assertIn('HEADER', msg)
493 self.assertNotIn('headerx', msg)
494
495 def test_set_param(self):
496 eq = self.assertEqual
497 msg = Message()
498 msg.set_param('charset', 'iso-2022-jp')
499 eq(msg.get_param('charset'), 'iso-2022-jp')
500 msg.set_param('importance', 'high value')
501 eq(msg.get_param('importance'), 'high value')
502 eq(msg.get_param('importance', unquote=False), '"high value"')
503 eq(msg.get_params(), [('text/plain', ''),
504 ('charset', 'iso-2022-jp'),
505 ('importance', 'high value')])
506 eq(msg.get_params(unquote=False), [('text/plain', ''),
507 ('charset', '"iso-2022-jp"'),
508 ('importance', '"high value"')])
509 msg.set_param('charset', 'iso-9999-xx', header='X-Jimmy')
510 eq(msg.get_param('charset', header='X-Jimmy'), 'iso-9999-xx')
511
512 def test_del_param(self):
513 eq = self.assertEqual
514 msg = self._msgobj('msg_05.txt')
515 eq(msg.get_params(),
516 [('multipart/report', ''), ('report-type', 'delivery-status'),
517 ('boundary', 'D1690A7AC1.996856090/mail.example.com')])
518 old_val = msg.get_param("report-type")
519 msg.del_param("report-type")
520 eq(msg.get_params(),
521 [('multipart/report', ''),
522 ('boundary', 'D1690A7AC1.996856090/mail.example.com')])
523 msg.set_param("report-type", old_val)
524 eq(msg.get_params(),
525 [('multipart/report', ''),
526 ('boundary', 'D1690A7AC1.996856090/mail.example.com'),
527 ('report-type', old_val)])
528
529 def test_del_param_on_other_header(self):
530 msg = Message()
531 msg.add_header('Content-Disposition', 'attachment', filename='bud.gif')
532 msg.del_param('filename', 'content-disposition')
533 self.assertEqual(msg['content-disposition'], 'attachment')
534
535 def test_del_param_on_nonexistent_header(self):
536 msg = Message()
537 # Deleting param on empty msg should not raise exception.
538 msg.del_param('filename', 'content-disposition')
539
540 def test_del_nonexistent_param(self):
541 msg = Message()
542 msg.add_header('Content-Type', 'text/plain', charset='utf-8')
543 existing_header = msg['Content-Type']
544 msg.del_param('foobar', header='Content-Type')
545 self.assertEqual(msg['Content-Type'], existing_header)
546
547 def test_set_type(self):
548 eq = self.assertEqual
549 msg = Message()
550 self.assertRaises(ValueError, msg.set_type, 'text')
551 msg.set_type('text/plain')
552 eq(msg['content-type'], 'text/plain')
553 msg.set_param('charset', 'us-ascii')
554 eq(msg['content-type'], 'text/plain; charset="us-ascii"')
555 msg.set_type('text/html')
556 eq(msg['content-type'], 'text/html; charset="us-ascii"')
557
558 def test_set_type_on_other_header(self):
559 msg = Message()
560 msg['X-Content-Type'] = 'text/plain'
561 msg.set_type('application/octet-stream', 'X-Content-Type')
562 self.assertEqual(msg['x-content-type'], 'application/octet-stream')
563
564 def test_get_content_type_missing(self):
565 msg = Message()
566 self.assertEqual(msg.get_content_type(), 'text/plain')
567
568 def test_get_content_type_missing_with_default_type(self):
569 msg = Message()
570 msg.set_default_type('message/rfc822')
571 self.assertEqual(msg.get_content_type(), 'message/rfc822')
572
573 def test_get_content_type_from_message_implicit(self):
574 msg = self._msgobj('msg_30.txt')
575 self.assertEqual(msg.get_payload(0).get_content_type(),
576 'message/rfc822')
577
578 def test_get_content_type_from_message_explicit(self):
579 msg = self._msgobj('msg_28.txt')
580 self.assertEqual(msg.get_payload(0).get_content_type(),
581 'message/rfc822')
582
583 def test_get_content_type_from_message_text_plain_implicit(self):
584 msg = self._msgobj('msg_03.txt')
585 self.assertEqual(msg.get_content_type(), 'text/plain')
586
587 def test_get_content_type_from_message_text_plain_explicit(self):
588 msg = self._msgobj('msg_01.txt')
589 self.assertEqual(msg.get_content_type(), 'text/plain')
590
591 def test_get_content_maintype_missing(self):
592 msg = Message()
593 self.assertEqual(msg.get_content_maintype(), 'text')
594
595 def test_get_content_maintype_missing_with_default_type(self):
596 msg = Message()
597 msg.set_default_type('message/rfc822')
598 self.assertEqual(msg.get_content_maintype(), 'message')
599
600 def test_get_content_maintype_from_message_implicit(self):
601 msg = self._msgobj('msg_30.txt')
602 self.assertEqual(msg.get_payload(0).get_content_maintype(), 'message')
603
604 def test_get_content_maintype_from_message_explicit(self):
605 msg = self._msgobj('msg_28.txt')
606 self.assertEqual(msg.get_payload(0).get_content_maintype(), 'message')
607
608 def test_get_content_maintype_from_message_text_plain_implicit(self):
609 msg = self._msgobj('msg_03.txt')
610 self.assertEqual(msg.get_content_maintype(), 'text')
611
612 def test_get_content_maintype_from_message_text_plain_explicit(self):
613 msg = self._msgobj('msg_01.txt')
614 self.assertEqual(msg.get_content_maintype(), 'text')
615
616 def test_get_content_subtype_missing(self):
617 msg = Message()
618 self.assertEqual(msg.get_content_subtype(), 'plain')
619
620 def test_get_content_subtype_missing_with_default_type(self):
621 msg = Message()
622 msg.set_default_type('message/rfc822')
623 self.assertEqual(msg.get_content_subtype(), 'rfc822')
624
625 def test_get_content_subtype_from_message_implicit(self):
626 msg = self._msgobj('msg_30.txt')
627 self.assertEqual(msg.get_payload(0).get_content_subtype(), 'rfc822')
628
629 def test_get_content_subtype_from_message_explicit(self):
630 msg = self._msgobj('msg_28.txt')
631 self.assertEqual(msg.get_payload(0).get_content_subtype(), 'rfc822')
632
633 def test_get_content_subtype_from_message_text_plain_implicit(self):
634 msg = self._msgobj('msg_03.txt')
635 self.assertEqual(msg.get_content_subtype(), 'plain')
636
637 def test_get_content_subtype_from_message_text_plain_explicit(self):
638 msg = self._msgobj('msg_01.txt')
639 self.assertEqual(msg.get_content_subtype(), 'plain')
640
641 def test_get_content_maintype_error(self):
642 msg = Message()
643 msg['Content-Type'] = 'no-slash-in-this-string'
644 self.assertEqual(msg.get_content_maintype(), 'text')
645
646 def test_get_content_subtype_error(self):
647 msg = Message()
648 msg['Content-Type'] = 'no-slash-in-this-string'
649 self.assertEqual(msg.get_content_subtype(), 'plain')
650
651 def test_replace_header(self):
652 eq = self.assertEqual
653 msg = Message()
654 msg.add_header('First', 'One')
655 msg.add_header('Second', 'Two')
656 msg.add_header('Third', 'Three')
657 eq(msg.keys(), ['First', 'Second', 'Third'])
658 eq(msg.values(), ['One', 'Two', 'Three'])
659 msg.replace_header('Second', 'Twenty')
660 eq(msg.keys(), ['First', 'Second', 'Third'])
661 eq(msg.values(), ['One', 'Twenty', 'Three'])
662 msg.add_header('First', 'Eleven')
663 msg.replace_header('First', 'One Hundred')
664 eq(msg.keys(), ['First', 'Second', 'Third', 'First'])
665 eq(msg.values(), ['One Hundred', 'Twenty', 'Three', 'Eleven'])
666 self.assertRaises(KeyError, msg.replace_header, 'Fourth', 'Missing')
667
668 def test_get_content_disposition(self):
669 msg = Message()
670 self.assertIsNone(msg.get_content_disposition())
671 msg.add_header('Content-Disposition', 'attachment',
672 filename='random.avi')
673 self.assertEqual(msg.get_content_disposition(), 'attachment')
674 msg.replace_header('Content-Disposition', 'inline')
675 self.assertEqual(msg.get_content_disposition(), 'inline')
676 msg.replace_header('Content-Disposition', 'InlinE')
677 self.assertEqual(msg.get_content_disposition(), 'inline')
678
679 # test_defect_handling:test_invalid_chars_in_base64_payload
680 def test_broken_base64_payload(self):
681 x = 'AwDp0P7//y6LwKEAcPa/6Q=9'
682 msg = Message()
683 msg['content-type'] = 'audio/x-midi'
684 msg['content-transfer-encoding'] = 'base64'
685 msg.set_payload(x)
686 self.assertEqual(msg.get_payload(decode=True),
687 (b'\x03\x00\xe9\xd0\xfe\xff\xff.\x8b\xc0'
688 b'\xa1\x00p\xf6\xbf\xe9\x0f'))
689 self.assertIsInstance(msg.defects[0],
690 errors.InvalidBase64CharactersDefect)
691
692 def test_broken_unicode_payload(self):
693 # This test improves coverage but is not a compliance test.
694 # The behavior in this situation is currently undefined by the API.
695 x = 'this is a br\xf6ken thing to do'
696 msg = Message()
697 msg['content-type'] = 'text/plain'
698 msg['content-transfer-encoding'] = '8bit'
699 msg.set_payload(x)
700 self.assertEqual(msg.get_payload(decode=True),
701 bytes(x, 'raw-unicode-escape'))
702
703 def test_questionable_bytes_payload(self):
704 # This test improves coverage but is not a compliance test,
705 # since it involves poking inside the black box.
706 x = 'this is a quéstionable thing to do'.encode('utf-8')
707 msg = Message()
708 msg['content-type'] = 'text/plain; charset="utf-8"'
709 msg['content-transfer-encoding'] = '8bit'
710 msg._payload = x
711 self.assertEqual(msg.get_payload(decode=True), x)
712
713 # Issue 1078919
714 def test_ascii_add_header(self):
715 msg = Message()
716 msg.add_header('Content-Disposition', 'attachment',
717 filename='bud.gif')
718 self.assertEqual('attachment; filename="bud.gif"',
719 msg['Content-Disposition'])
720
721 def test_noascii_add_header(self):
722 msg = Message()
723 msg.add_header('Content-Disposition', 'attachment',
724 filename="Fußballer.ppt")
725 self.assertEqual(
726 'attachment; filename*=utf-8\'\'Fu%C3%9Fballer.ppt',
727 msg['Content-Disposition'])
728
729 def test_nonascii_add_header_via_triple(self):
730 msg = Message()
731 msg.add_header('Content-Disposition', 'attachment',
732 filename=('iso-8859-1', '', 'Fußballer.ppt'))
733 self.assertEqual(
734 'attachment; filename*=iso-8859-1\'\'Fu%DFballer.ppt',
735 msg['Content-Disposition'])
736
737 def test_ascii_add_header_with_tspecial(self):
738 msg = Message()
739 msg.add_header('Content-Disposition', 'attachment',
740 filename="windows [filename].ppt")
741 self.assertEqual(
742 'attachment; filename="windows [filename].ppt"',
743 msg['Content-Disposition'])
744
745 def test_nonascii_add_header_with_tspecial(self):
746 msg = Message()
747 msg.add_header('Content-Disposition', 'attachment',
748 filename="Fußballer [filename].ppt")
749 self.assertEqual(
750 "attachment; filename*=utf-8''Fu%C3%9Fballer%20%5Bfilename%5D.ppt",
751 msg['Content-Disposition'])
752
753 def test_binary_quopri_payload(self):
754 for charset in ('latin-1', 'ascii'):
755 msg = Message()
756 msg['content-type'] = 'text/plain; charset=%s' % charset
757 msg['content-transfer-encoding'] = 'quoted-printable'
758 msg.set_payload(b'foo=e6=96=87bar')
759 self.assertEqual(
760 msg.get_payload(decode=True),
761 b'foo\xe6\x96\x87bar',
762 'get_payload returns wrong result with charset %s.' % charset)
763
764 def test_binary_base64_payload(self):
765 for charset in ('latin-1', 'ascii'):
766 msg = Message()
767 msg['content-type'] = 'text/plain; charset=%s' % charset
768 msg['content-transfer-encoding'] = 'base64'
769 msg.set_payload(b'Zm9v5paHYmFy')
770 self.assertEqual(
771 msg.get_payload(decode=True),
772 b'foo\xe6\x96\x87bar',
773 'get_payload returns wrong result with charset %s.' % charset)
774
775 def test_binary_uuencode_payload(self):
776 for charset in ('latin-1', 'ascii'):
777 for encoding in ('x-uuencode', 'uuencode', 'uue', 'x-uue'):
778 msg = Message()
779 msg['content-type'] = 'text/plain; charset=%s' % charset
780 msg['content-transfer-encoding'] = encoding
781 msg.set_payload(b"begin 666 -\n)9F]OYI:'8F%R\n \nend\n")
782 self.assertEqual(
783 msg.get_payload(decode=True),
784 b'foo\xe6\x96\x87bar',
785 str(('get_payload returns wrong result ',
786 'with charset {0} and encoding {1}.')).\
787 format(charset, encoding))
788
789 def test_add_header_with_name_only_param(self):
790 msg = Message()
791 msg.add_header('Content-Disposition', 'inline', foo_bar=None)
792 self.assertEqual("inline; foo-bar", msg['Content-Disposition'])
793
794 def test_add_header_with_no_value(self):
795 msg = Message()
796 msg.add_header('X-Status', None)
797 self.assertEqual('', msg['X-Status'])
798
799 # Issue 5871: reject an attempt to embed a header inside a header value
800 # (header injection attack).
801 def test_embedded_header_via_Header_rejected(self):
802 msg = Message()
803 msg['Dummy'] = Header('dummy\nX-Injected-Header: test')
804 self.assertRaises(errors.HeaderParseError, msg.as_string)
805
806 def test_embedded_header_via_string_rejected(self):
807 msg = Message()
808 msg['Dummy'] = 'dummy\nX-Injected-Header: test'
809 self.assertRaises(errors.HeaderParseError, msg.as_string)
810
811 def test_unicode_header_defaults_to_utf8_encoding(self):
812 # Issue 14291
813 m = MIMEText('abc\n')
814 m['Subject'] = 'É test'
815 self.assertEqual(str(m),textwrap.dedent("""\
816 Content-Type: text/plain; charset="us-ascii"
817 MIME-Version: 1.0
818 Content-Transfer-Encoding: 7bit
819 Subject: =?utf-8?q?=C3=89_test?=
820
821 abc
822 """))
823
824 def test_unicode_body_defaults_to_utf8_encoding(self):
825 # Issue 14291
826 m = MIMEText('É testabc\n')
827 self.assertEqual(str(m),textwrap.dedent("""\
828 Content-Type: text/plain; charset="utf-8"
829 MIME-Version: 1.0
830 Content-Transfer-Encoding: base64
831
832 w4kgdGVzdGFiYwo=
833 """))
834
835
836 # Test the email.encoders module
837 class TestEncoders(unittest.TestCase):
838
839 def test_EncodersEncode_base64(self):
840 with openfile('python.gif', 'rb') as fp:
841 bindata = fp.read()
842 mimed = email.mime.image.MIMEImage(bindata)
843 base64ed = mimed.get_payload()
844 # the transfer-encoded body lines should all be <=76 characters
845 lines = base64ed.split('\n')
846 self.assertLessEqual(max([ len(x) for x in lines ]), 76)
847
848 def test_encode_empty_payload(self):
849 eq = self.assertEqual
850 msg = Message()
851 msg.set_charset('us-ascii')
852 eq(msg['content-transfer-encoding'], '7bit')
853
854 def test_default_cte(self):
855 eq = self.assertEqual
856 # 7bit data and the default us-ascii _charset
857 msg = MIMEText('hello world')
858 eq(msg['content-transfer-encoding'], '7bit')
859 # Similar, but with 8bit data
860 msg = MIMEText('hello \xf8 world')
861 eq(msg['content-transfer-encoding'], 'base64')
862 # And now with a different charset
863 msg = MIMEText('hello \xf8 world', _charset='iso-8859-1')
864 eq(msg['content-transfer-encoding'], 'quoted-printable')
865
866 def test_encode7or8bit(self):
867 # Make sure a charset whose input character set is 8bit but
868 # whose output character set is 7bit gets a transfer-encoding
869 # of 7bit.
870 eq = self.assertEqual
871 msg = MIMEText('文\n', _charset='euc-jp')
872 eq(msg['content-transfer-encoding'], '7bit')
873 eq(msg.as_string(), textwrap.dedent("""\
874 MIME-Version: 1.0
875 Content-Type: text/plain; charset="iso-2022-jp"
876 Content-Transfer-Encoding: 7bit
877
878 \x1b$BJ8\x1b(B
879 """))
880
881 def test_qp_encode_latin1(self):
882 msg = MIMEText('\xe1\xf6\n', 'text', 'ISO-8859-1')
883 self.assertEqual(str(msg), textwrap.dedent("""\
884 MIME-Version: 1.0
885 Content-Type: text/text; charset="iso-8859-1"
886 Content-Transfer-Encoding: quoted-printable
887
888 =E1=F6
889 """))
890
891 def test_qp_encode_non_latin1(self):
892 # Issue 16948
893 msg = MIMEText('\u017c\n', 'text', 'ISO-8859-2')
894 self.assertEqual(str(msg), textwrap.dedent("""\
895 MIME-Version: 1.0
896 Content-Type: text/text; charset="iso-8859-2"
897 Content-Transfer-Encoding: quoted-printable
898
899 =BF
900 """))
901
902
903 # Test long header wrapping
904 class TestLongHeaders(TestEmailBase):
905
906 maxDiff = None
907
908 def test_split_long_continuation(self):
909 eq = self.ndiffAssertEqual
910 msg = email.message_from_string("""\
911 Subject: bug demonstration
912 \t12345678911234567892123456789312345678941234567895123456789612345678971234567898112345678911234567892123456789112345678911234567892123456789
913 \tmore text
914
915 test
916 """)
917 sfp = StringIO()
918 g = Generator(sfp)
919 g.flatten(msg)
920 eq(sfp.getvalue(), """\
921 Subject: bug demonstration
922 \t12345678911234567892123456789312345678941234567895123456789612345678971234567898112345678911234567892123456789112345678911234567892123456789
923 \tmore text
924
925 test
926 """)
927
928 def test_another_long_almost_unsplittable_header(self):
929 eq = self.ndiffAssertEqual
930 hstr = """\
931 bug demonstration
932 \t12345678911234567892123456789312345678941234567895123456789612345678971234567898112345678911234567892123456789112345678911234567892123456789
933 \tmore text"""
934 h = Header(hstr, continuation_ws='\t')
935 eq(h.encode(), """\
936 bug demonstration
937 \t12345678911234567892123456789312345678941234567895123456789612345678971234567898112345678911234567892123456789112345678911234567892123456789
938 \tmore text""")
939 h = Header(hstr.replace('\t', ' '))
940 eq(h.encode(), """\
941 bug demonstration
942 12345678911234567892123456789312345678941234567895123456789612345678971234567898112345678911234567892123456789112345678911234567892123456789
943 more text""")
944
945 def test_long_nonstring(self):
946 eq = self.ndiffAssertEqual
947 g = Charset("iso-8859-1")
948 cz = Charset("iso-8859-2")
949 utf8 = Charset("utf-8")
950 g_head = (b'Die Mieter treten hier ein werden mit einem Foerderband '
951 b'komfortabel den Korridor entlang, an s\xfcdl\xfcndischen '
952 b'Wandgem\xe4lden vorbei, gegen die rotierenden Klingen '
953 b'bef\xf6rdert. ')
954 cz_head = (b'Finan\xe8ni metropole se hroutily pod tlakem jejich '
955 b'd\xf9vtipu.. ')
956 utf8_head = ('\u6b63\u78ba\u306b\u8a00\u3046\u3068\u7ffb\u8a33\u306f'
957 '\u3055\u308c\u3066\u3044\u307e\u305b\u3093\u3002\u4e00'
958 '\u90e8\u306f\u30c9\u30a4\u30c4\u8a9e\u3067\u3059\u304c'
959 '\u3001\u3042\u3068\u306f\u3067\u305f\u3089\u3081\u3067'
960 '\u3059\u3002\u5b9f\u969b\u306b\u306f\u300cWenn ist das '
961 'Nunstuck git und Slotermeyer? Ja! Beiherhund das Oder '
962 'die Flipperwaldt gersput.\u300d\u3068\u8a00\u3063\u3066'
963 '\u3044\u307e\u3059\u3002')
964 h = Header(g_head, g, header_name='Subject')
965 h.append(cz_head, cz)
966 h.append(utf8_head, utf8)
967 msg = Message()
968 msg['Subject'] = h
969 sfp = StringIO()
970 g = Generator(sfp)
971 g.flatten(msg)
972 eq(sfp.getvalue(), """\
973 Subject: =?iso-8859-1?q?Die_Mieter_treten_hier_ein_werden_mit_einem_Foerderb?=
974 =?iso-8859-1?q?and_komfortabel_den_Korridor_entlang=2C_an_s=FCdl=FCndischen?=
975 =?iso-8859-1?q?_Wandgem=E4lden_vorbei=2C_gegen_die_rotierenden_Klingen_bef?=
976 =?iso-8859-1?q?=F6rdert=2E_?= =?iso-8859-2?q?Finan=E8ni_metropole_se_hrouti?=
977 =?iso-8859-2?q?ly_pod_tlakem_jejich_d=F9vtipu=2E=2E_?= =?utf-8?b?5q2j56K6?=
978 =?utf-8?b?44Gr6KiA44GG44Go57+76Kiz44Gv44GV44KM44Gm44GE44G+44Gb44KT44CC5LiA?=
979 =?utf-8?b?6YOo44Gv44OJ44Kk44OE6Kqe44Gn44GZ44GM44CB44GC44Go44Gv44Gn44Gf44KJ?=
980 =?utf-8?b?44KB44Gn44GZ44CC5a6f6Zqb44Gr44Gv44CMV2VubiBpc3QgZGFzIE51bnN0dWNr?=
981 =?utf-8?b?IGdpdCB1bmQgU2xvdGVybWV5ZXI/IEphISBCZWloZXJodW5kIGRhcyBPZGVyIGRp?=
982 =?utf-8?b?ZSBGbGlwcGVyd2FsZHQgZ2Vyc3B1dC7jgI3jgajoqIDjgaPjgabjgYTjgb7jgZk=?=
983 =?utf-8?b?44CC?=
984
985 """)
986 eq(h.encode(maxlinelen=76), """\
987 =?iso-8859-1?q?Die_Mieter_treten_hier_ein_werden_mit_einem_Foerde?=
988 =?iso-8859-1?q?rband_komfortabel_den_Korridor_entlang=2C_an_s=FCdl=FCndis?=
989 =?iso-8859-1?q?chen_Wandgem=E4lden_vorbei=2C_gegen_die_rotierenden_Klinge?=
990 =?iso-8859-1?q?n_bef=F6rdert=2E_?= =?iso-8859-2?q?Finan=E8ni_metropole_se?=
991 =?iso-8859-2?q?_hroutily_pod_tlakem_jejich_d=F9vtipu=2E=2E_?=
992 =?utf-8?b?5q2j56K644Gr6KiA44GG44Go57+76Kiz44Gv44GV44KM44Gm44GE44G+44Gb?=
993 =?utf-8?b?44KT44CC5LiA6YOo44Gv44OJ44Kk44OE6Kqe44Gn44GZ44GM44CB44GC44Go?=
994 =?utf-8?b?44Gv44Gn44Gf44KJ44KB44Gn44GZ44CC5a6f6Zqb44Gr44Gv44CMV2VubiBp?=
995 =?utf-8?b?c3QgZGFzIE51bnN0dWNrIGdpdCB1bmQgU2xvdGVybWV5ZXI/IEphISBCZWlo?=
996 =?utf-8?b?ZXJodW5kIGRhcyBPZGVyIGRpZSBGbGlwcGVyd2FsZHQgZ2Vyc3B1dC7jgI0=?=
997 =?utf-8?b?44Go6KiA44Gj44Gm44GE44G+44GZ44CC?=""")
998
999 def test_long_header_encode(self):
1000 eq = self.ndiffAssertEqual
1001 h = Header('wasnipoop; giraffes="very-long-necked-animals"; '
1002 'spooge="yummy"; hippos="gargantuan"; marshmallows="gooey"',
1003 header_name='X-Foobar-Spoink-Defrobnit')
1004 eq(h.encode(), '''\
1005 wasnipoop; giraffes="very-long-necked-animals";
1006 spooge="yummy"; hippos="gargantuan"; marshmallows="gooey"''')
1007
1008 def test_long_header_encode_with_tab_continuation_is_just_a_hint(self):
1009 eq = self.ndiffAssertEqual
1010 h = Header('wasnipoop; giraffes="very-long-necked-animals"; '
1011 'spooge="yummy"; hippos="gargantuan"; marshmallows="gooey"',
1012 header_name='X-Foobar-Spoink-Defrobnit',
1013 continuation_ws='\t')
1014 eq(h.encode(), '''\
1015 wasnipoop; giraffes="very-long-necked-animals";
1016 spooge="yummy"; hippos="gargantuan"; marshmallows="gooey"''')
1017
1018 def test_long_header_encode_with_tab_continuation(self):
1019 eq = self.ndiffAssertEqual
1020 h = Header('wasnipoop; giraffes="very-long-necked-animals";\t'
1021 'spooge="yummy"; hippos="gargantuan"; marshmallows="gooey"',
1022 header_name='X-Foobar-Spoink-Defrobnit',
1023 continuation_ws='\t')
1024 eq(h.encode(), '''\
1025 wasnipoop; giraffes="very-long-necked-animals";
1026 \tspooge="yummy"; hippos="gargantuan"; marshmallows="gooey"''')
1027
1028 def test_header_encode_with_different_output_charset(self):
1029 h = Header('文', 'euc-jp')
1030 self.assertEqual(h.encode(), "=?iso-2022-jp?b?GyRCSjgbKEI=?=")
1031
1032 def test_long_header_encode_with_different_output_charset(self):
1033 h = Header(b'test-ja \xa4\xd8\xc5\xea\xb9\xc6\xa4\xb5\xa4\xec\xa4'
1034 b'\xbf\xa5\xe1\xa1\xbc\xa5\xeb\xa4\xcf\xbb\xca\xb2\xf1\xbc\xd4'
1035 b'\xa4\xce\xbe\xb5\xc7\xa7\xa4\xf2\xc2\xd4\xa4\xc3\xa4\xc6\xa4'
1036 b'\xa4\xa4\xde\xa4\xb9'.decode('euc-jp'), 'euc-jp')
1037 res = """\
1038 =?iso-2022-jp?b?dGVzdC1qYSAbJEIkWEVqOUYkNSRsJD8lYSE8JWskTztKMnE8VCROPjUbKEI=?=
1039 =?iso-2022-jp?b?GyRCRyckckJUJEMkRiQkJF4kORsoQg==?="""
1040 self.assertEqual(h.encode(), res)
1041
1042 def test_header_splitter(self):
1043 eq = self.ndiffAssertEqual
1044 msg = MIMEText('')
1045 # It'd be great if we could use add_header() here, but that doesn't
1046 # guarantee an order of the parameters.
1047 msg['X-Foobar-Spoink-Defrobnit'] = (
1048 'wasnipoop; giraffes="very-long-necked-animals"; '
1049 'spooge="yummy"; hippos="gargantuan"; marshmallows="gooey"')
1050 sfp = StringIO()
1051 g = Generator(sfp)
1052 g.flatten(msg)
1053 eq(sfp.getvalue(), '''\
1054 Content-Type: text/plain; charset="us-ascii"
1055 MIME-Version: 1.0
1056 Content-Transfer-Encoding: 7bit
1057 X-Foobar-Spoink-Defrobnit: wasnipoop; giraffes="very-long-necked-animals";
1058 spooge="yummy"; hippos="gargantuan"; marshmallows="gooey"
1059
1060 ''')
1061
1062 def test_no_semis_header_splitter(self):
1063 eq = self.ndiffAssertEqual
1064 msg = Message()
1065 msg['From'] = '[email protected]'
1066 msg['References'] = SPACE.join('<%[email protected]>' % i for i in range(10))
1067 msg.set_payload('Test')
1068 sfp = StringIO()
1069 g = Generator(sfp)
1070 g.flatten(msg)
1071 eq(sfp.getvalue(), """\
1072 From: [email protected]
1073 References: <[email protected]> <[email protected]> <[email protected]> <[email protected]> <[email protected]>
1074 <[email protected]> <[email protected]> <[email protected]> <[email protected]> <[email protected]>
1075
1076 Test""")
1077
1078 def test_last_split_chunk_does_not_fit(self):
1079 eq = self.ndiffAssertEqual
1080 h = Header('Subject: the first part of this is short, but_the_second'
1081 '_part_does_not_fit_within_maxlinelen_and_thus_should_be_on_a_line'
1082 '_all_by_itself')
1083 eq(h.encode(), """\
1084 Subject: the first part of this is short,
1085 but_the_second_part_does_not_fit_within_maxlinelen_and_thus_should_be_on_a_line_all_by_itself""")
1086
1087 def test_splittable_leading_char_followed_by_overlong_unsplittable(self):
1088 eq = self.ndiffAssertEqual
1089 h = Header(', but_the_second'
1090 '_part_does_not_fit_within_maxlinelen_and_thus_should_be_on_a_line'
1091 '_all_by_itself')
1092 eq(h.encode(), """\
1093 ,
1094 but_the_second_part_does_not_fit_within_maxlinelen_and_thus_should_be_on_a_line_all_by_itself""")
1095
1096 def test_multiple_splittable_leading_char_followed_by_overlong_unsplittable(self):
1097 eq = self.ndiffAssertEqual
1098 h = Header(', , but_the_second'
1099 '_part_does_not_fit_within_maxlinelen_and_thus_should_be_on_a_line'
1100 '_all_by_itself')
1101 eq(h.encode(), """\
1102 , ,
1103 but_the_second_part_does_not_fit_within_maxlinelen_and_thus_should_be_on_a_line_all_by_itself""")
1104
1105 def test_trailing_splittable_on_overlong_unsplittable(self):
1106 eq = self.ndiffAssertEqual
1107 h = Header('this_part_does_not_fit_within_maxlinelen_and_thus_should_'
1108 'be_on_a_line_all_by_itself;')
1109 eq(h.encode(), "this_part_does_not_fit_within_maxlinelen_and_thus_should_"
1110 "be_on_a_line_all_by_itself;")
1111
1112 def test_trailing_splittable_on_overlong_unsplittable_with_leading_splittable(self):
1113 eq = self.ndiffAssertEqual
1114 h = Header('; '
1115 'this_part_does_not_fit_within_maxlinelen_and_thus_should_'
1116 'be_on_a_line_all_by_itself; ')
1117 eq(h.encode(), """\
1118 ;
1119 this_part_does_not_fit_within_maxlinelen_and_thus_should_be_on_a_line_all_by_itself; """)
1120
1121 def test_long_header_with_multiple_sequential_split_chars(self):
1122 eq = self.ndiffAssertEqual
1123 h = Header('This is a long line that has two whitespaces in a row. '
1124 'This used to cause truncation of the header when folded')
1125 eq(h.encode(), """\
1126 This is a long line that has two whitespaces in a row. This used to cause
1127 truncation of the header when folded""")
1128
1129 def test_splitter_split_on_punctuation_only_if_fws_with_header(self):
1130 eq = self.ndiffAssertEqual
1131 h = Header('thisverylongheaderhas;semicolons;and,commas,but'
1132 'they;arenotlegal;fold,points')
1133 eq(h.encode(), "thisverylongheaderhas;semicolons;and,commas,butthey;"
1134 "arenotlegal;fold,points")
1135
1136 def test_leading_splittable_in_the_middle_just_before_overlong_last_part(self):
1137 eq = self.ndiffAssertEqual
1138 h = Header('this is a test where we need to have more than one line '
1139 'before; our final line that is just too big to fit;; '
1140 'this_part_does_not_fit_within_maxlinelen_and_thus_should_'
1141 'be_on_a_line_all_by_itself;')
1142 eq(h.encode(), """\
1143 this is a test where we need to have more than one line before;
1144 our final line that is just too big to fit;;
1145 this_part_does_not_fit_within_maxlinelen_and_thus_should_be_on_a_line_all_by_itself;""")
1146
1147 def test_overlong_last_part_followed_by_split_point(self):
1148 eq = self.ndiffAssertEqual
1149 h = Header('this_part_does_not_fit_within_maxlinelen_and_thus_should_'
1150 'be_on_a_line_all_by_itself ')
1151 eq(h.encode(), "this_part_does_not_fit_within_maxlinelen_and_thus_"
1152 "should_be_on_a_line_all_by_itself ")
1153
1154 def test_multiline_with_overlong_parts_separated_by_two_split_points(self):
1155 eq = self.ndiffAssertEqual
1156 h = Header('this_is_a__test_where_we_need_to_have_more_than_one_line_'
1157 'before_our_final_line_; ; '
1158 'this_part_does_not_fit_within_maxlinelen_and_thus_should_'
1159 'be_on_a_line_all_by_itself; ')
1160 eq(h.encode(), """\
1161 this_is_a__test_where_we_need_to_have_more_than_one_line_before_our_final_line_;
1162 ;
1163 this_part_does_not_fit_within_maxlinelen_and_thus_should_be_on_a_line_all_by_itself; """)
1164
1165 def test_multiline_with_overlong_last_part_followed_by_split_point(self):
1166 eq = self.ndiffAssertEqual
1167 h = Header('this is a test where we need to have more than one line '
1168 'before our final line; ; '
1169 'this_part_does_not_fit_within_maxlinelen_and_thus_should_'
1170 'be_on_a_line_all_by_itself; ')
1171 eq(h.encode(), """\
1172 this is a test where we need to have more than one line before our final line;
1173 ;
1174 this_part_does_not_fit_within_maxlinelen_and_thus_should_be_on_a_line_all_by_itself; """)
1175
1176 def test_long_header_with_whitespace_runs(self):
1177 eq = self.ndiffAssertEqual
1178 msg = Message()
1179 msg['From'] = '[email protected]'
1180 msg['References'] = SPACE.join(['<[email protected]> '] * 10)
1181 msg.set_payload('Test')
1182 sfp = StringIO()
1183 g = Generator(sfp)
1184 g.flatten(msg)
1185 eq(sfp.getvalue(), """\
1186 From: [email protected]
1187 References: <[email protected]> <[email protected]> <[email protected]> <[email protected]>
1188 <[email protected]> <[email protected]> <[email protected]> <[email protected]>
1189 <[email protected]> <[email protected]>\x20\x20
1190
1191 Test""")
1192
1193 def test_long_run_with_semi_header_splitter(self):
1194 eq = self.ndiffAssertEqual
1195 msg = Message()
1196 msg['From'] = '[email protected]'
1197 msg['References'] = SPACE.join(['<[email protected]>'] * 10) + '; abc'
1198 msg.set_payload('Test')
1199 sfp = StringIO()
1200 g = Generator(sfp)
1201 g.flatten(msg)
1202 eq(sfp.getvalue(), """\
1203 From: [email protected]
1204 References: <[email protected]> <[email protected]> <[email protected]> <[email protected]>
1205 <[email protected]> <[email protected]> <[email protected]> <[email protected]> <[email protected]>
1206 <[email protected]>; abc
1207
1208 Test""")
1209
1210 def test_splitter_split_on_punctuation_only_if_fws(self):
1211 eq = self.ndiffAssertEqual
1212 msg = Message()
1213 msg['From'] = '[email protected]'
1214 msg['References'] = ('thisverylongheaderhas;semicolons;and,commas,but'
1215 'they;arenotlegal;fold,points')
1216 msg.set_payload('Test')
1217 sfp = StringIO()
1218 g = Generator(sfp)
1219 g.flatten(msg)
1220 # XXX the space after the header should not be there.
1221 eq(sfp.getvalue(), """\
1222 From: [email protected]
1223 References:\x20
1224 thisverylongheaderhas;semicolons;and,commas,butthey;arenotlegal;fold,points
1225
1226 Test""")
1227
1228 def test_no_split_long_header(self):
1229 eq = self.ndiffAssertEqual
1230 hstr = 'References: ' + 'x' * 80
1231 h = Header(hstr)
1232 # These come on two lines because Headers are really field value
1233 # classes and don't really know about their field names.
1234 eq(h.encode(), """\
1235 References:
1236 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx""")
1237 h = Header('x' * 80)
1238 eq(h.encode(), 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')
1239
1240 def test_splitting_multiple_long_lines(self):
1241 eq = self.ndiffAssertEqual
1242 hstr = """\
1243 from babylon.socal-raves.org (localhost [127.0.0.1]); by babylon.socal-raves.org (Postfix) with ESMTP id B570E51B81; for <[email protected]>; Sat, 2 Feb 2002 17:00:06 -0800 (PST)
1244 \tfrom babylon.socal-raves.org (localhost [127.0.0.1]); by babylon.socal-raves.org (Postfix) with ESMTP id B570E51B81; for <[email protected]>; Sat, 2 Feb 2002 17:00:06 -0800 (PST)
1245 \tfrom babylon.socal-raves.org (localhost [127.0.0.1]); by babylon.socal-raves.org (Postfix) with ESMTP id B570E51B81; for <[email protected]>; Sat, 2 Feb 2002 17:00:06 -0800 (PST)
1246 """
1247 h = Header(hstr, continuation_ws='\t')
1248 eq(h.encode(), """\
1249 from babylon.socal-raves.org (localhost [127.0.0.1]);
1250 by babylon.socal-raves.org (Postfix) with ESMTP id B570E51B81;
1251 for <[email protected]>;
1252 Sat, 2 Feb 2002 17:00:06 -0800 (PST)
1253 \tfrom babylon.socal-raves.org (localhost [127.0.0.1]);
1254 by babylon.socal-raves.org (Postfix) with ESMTP id B570E51B81;
1255 for <[email protected]>;
1256 Sat, 2 Feb 2002 17:00:06 -0800 (PST)
1257 \tfrom babylon.socal-raves.org (localhost [127.0.0.1]);
1258 by babylon.socal-raves.org (Postfix) with ESMTP id B570E51B81;
1259 for <[email protected]>;
1260 Sat, 2 Feb 2002 17:00:06 -0800 (PST)""")
1261
1262 def test_splitting_first_line_only_is_long(self):
1263 eq = self.ndiffAssertEqual
1264 hstr = """\
1265 from modemcable093.139-201-24.que.mc.videotron.ca ([24.201.139.93] helo=cthulhu.gerg.ca)
1266 \tby kronos.mems-exchange.org with esmtp (Exim 4.05)
1267 \tid 17k4h5-00034i-00
1268 \tfor [email protected]; Wed, 28 Aug 2002 11:25:20 -0400"""
1269 h = Header(hstr, maxlinelen=78, header_name='Received',
1270 continuation_ws='\t')
1271 eq(h.encode(), """\
1272 from modemcable093.139-201-24.que.mc.videotron.ca ([24.201.139.93]
1273 helo=cthulhu.gerg.ca)
1274 \tby kronos.mems-exchange.org with esmtp (Exim 4.05)
1275 \tid 17k4h5-00034i-00
1276 \tfor [email protected]; Wed, 28 Aug 2002 11:25:20 -0400""")
1277
1278 def test_long_8bit_header(self):
1279 eq = self.ndiffAssertEqual
1280 msg = Message()
1281 h = Header('Britische Regierung gibt', 'iso-8859-1',
1282 header_name='Subject')
1283 h.append('gr\xfcnes Licht f\xfcr Offshore-Windkraftprojekte')
1284 eq(h.encode(maxlinelen=76), """\
1285 =?iso-8859-1?q?Britische_Regierung_gibt_gr=FCnes_Licht_f=FCr_Offs?=
1286 =?iso-8859-1?q?hore-Windkraftprojekte?=""")
1287 msg['Subject'] = h
1288 eq(msg.as_string(maxheaderlen=76), """\
1289 Subject: =?iso-8859-1?q?Britische_Regierung_gibt_gr=FCnes_Licht_f=FCr_Offs?=
1290 =?iso-8859-1?q?hore-Windkraftprojekte?=
1291
1292 """)
1293 eq(msg.as_string(maxheaderlen=0), """\
1294 Subject: =?iso-8859-1?q?Britische_Regierung_gibt_gr=FCnes_Licht_f=FCr_Offshore-Windkraftprojekte?=
1295
1296 """)
1297
1298 def test_long_8bit_header_no_charset(self):
1299 eq = self.ndiffAssertEqual
1300 msg = Message()
1301 header_string = ('Britische Regierung gibt gr\xfcnes Licht '
1302 'f\xfcr Offshore-Windkraftprojekte '
1303 '<[email protected]>')
1304 msg['Reply-To'] = header_string
1305 eq(msg.as_string(maxheaderlen=78), """\
1306 Reply-To: =?utf-8?q?Britische_Regierung_gibt_gr=C3=BCnes_Licht_f=C3=BCr_Offs?=
1307 =?utf-8?q?hore-Windkraftprojekte_=3Ca-very-long-address=40example=2Ecom=3E?=
1308
1309 """)
1310 msg = Message()
1311 msg['Reply-To'] = Header(header_string,
1312 header_name='Reply-To')
1313 eq(msg.as_string(maxheaderlen=78), """\
1314 Reply-To: =?utf-8?q?Britische_Regierung_gibt_gr=C3=BCnes_Licht_f=C3=BCr_Offs?=
1315 =?utf-8?q?hore-Windkraftprojekte_=3Ca-very-long-address=40example=2Ecom=3E?=
1316
1317 """)
1318
1319 def test_long_to_header(self):
1320 eq = self.ndiffAssertEqual
1321 to = ('"Someone Test #A" <[email protected]>,'
1322 '<[email protected]>, '
1323 '"Someone Test #B" <[email protected]>, '
1324 '"Someone Test #C" <[email protected]>, '
1325 '"Someone Test #D" <[email protected]>')
1326 msg = Message()
1327 msg['To'] = to
1328 eq(msg.as_string(maxheaderlen=78), '''\
1329 To: "Someone Test #A" <[email protected]>,<[email protected]>,
1330 "Someone Test #B" <[email protected]>,
1331 "Someone Test #C" <[email protected]>,
1332 "Someone Test #D" <[email protected]>
1333
1334 ''')
1335
1336 def test_long_line_after_append(self):
1337 eq = self.ndiffAssertEqual
1338 s = 'This is an example of string which has almost the limit of header length.'
1339 h = Header(s)
1340 h.append('Add another line.')
1341 eq(h.encode(maxlinelen=76), """\
1342 This is an example of string which has almost the limit of header length.
1343 Add another line.""")
1344
1345 def test_shorter_line_with_append(self):
1346 eq = self.ndiffAssertEqual
1347 s = 'This is a shorter line.'
1348 h = Header(s)
1349 h.append('Add another sentence. (Surprise?)')
1350 eq(h.encode(),
1351 'This is a shorter line. Add another sentence. (Surprise?)')
1352
1353 def test_long_field_name(self):
1354 eq = self.ndiffAssertEqual
1355 fn = 'X-Very-Very-Very-Long-Header-Name'
1356 gs = ('Die Mieter treten hier ein werden mit einem Foerderband '
1357 'komfortabel den Korridor entlang, an s\xfcdl\xfcndischen '
1358 'Wandgem\xe4lden vorbei, gegen die rotierenden Klingen '
1359 'bef\xf6rdert. ')
1360 h = Header(gs, 'iso-8859-1', header_name=fn)
1361 # BAW: this seems broken because the first line is too long
1362 eq(h.encode(maxlinelen=76), """\
1363 =?iso-8859-1?q?Die_Mieter_treten_hier_e?=
1364 =?iso-8859-1?q?in_werden_mit_einem_Foerderband_komfortabel_den_Korridor_e?=
1365 =?iso-8859-1?q?ntlang=2C_an_s=FCdl=FCndischen_Wandgem=E4lden_vorbei=2C_ge?=
1366 =?iso-8859-1?q?gen_die_rotierenden_Klingen_bef=F6rdert=2E_?=""")
1367
1368 def test_long_received_header(self):
1369 h = ('from FOO.TLD (vizworld.acl.foo.tld [123.452.678.9]) '
1370 'by hrothgar.la.mastaler.com (tmda-ofmipd) with ESMTP; '
1371 'Wed, 05 Mar 2003 18:10:18 -0700')
1372 msg = Message()
1373 msg['Received-1'] = Header(h, continuation_ws='\t')
1374 msg['Received-2'] = h
1375 # This should be splitting on spaces not semicolons.
1376 self.ndiffAssertEqual(msg.as_string(maxheaderlen=78), """\
1377 Received-1: from FOO.TLD (vizworld.acl.foo.tld [123.452.678.9]) by
1378 hrothgar.la.mastaler.com (tmda-ofmipd) with ESMTP;
1379 Wed, 05 Mar 2003 18:10:18 -0700
1380 Received-2: from FOO.TLD (vizworld.acl.foo.tld [123.452.678.9]) by
1381 hrothgar.la.mastaler.com (tmda-ofmipd) with ESMTP;
1382 Wed, 05 Mar 2003 18:10:18 -0700
1383
1384 """)
1385
1386 def test_string_headerinst_eq(self):
1387 h = ('<[email protected].'
1388 'tu-muenchen.de> (David Bremner\'s message of '
1389 '"Thu, 6 Mar 2003 13:58:21 +0100")')
1390 msg = Message()
1391 msg['Received-1'] = Header(h, header_name='Received-1',
1392 continuation_ws='\t')
1393 msg['Received-2'] = h
1394 # XXX The space after the ':' should not be there.
1395 self.ndiffAssertEqual(msg.as_string(maxheaderlen=78), """\
1396 Received-1:\x20
1397 <15975.17901.207240.414604@sgigritzmann1.mathematik.tu-muenchen.de> (David
1398 Bremner's message of \"Thu, 6 Mar 2003 13:58:21 +0100\")
1399 Received-2:\x20
1400 <15975.17901.207240.414604@sgigritzmann1.mathematik.tu-muenchen.de> (David
1401 Bremner's message of \"Thu, 6 Mar 2003 13:58:21 +0100\")
1402
1403 """)
1404
1405 def test_long_unbreakable_lines_with_continuation(self):
1406 eq = self.ndiffAssertEqual
1407 msg = Message()
1408 t = """\
1409 iVBORw0KGgoAAAANSUhEUgAAADAAAAAwBAMAAAClLOS0AAAAGFBMVEUAAAAkHiJeRUIcGBi9
1410 locQDQ4zJykFBAXJfWDjAAACYUlEQVR4nF2TQY/jIAyFc6lydlG5x8Nyp1Y69wj1PN2I5gzp"""
1411 msg['Face-1'] = t
1412 msg['Face-2'] = Header(t, header_name='Face-2')
1413 msg['Face-3'] = ' ' + t
1414 # XXX This splitting is all wrong. It the first value line should be
1415 # snug against the field name or the space after the header not there.
1416 eq(msg.as_string(maxheaderlen=78), """\
1417 Face-1:\x20
1418 iVBORw0KGgoAAAANSUhEUgAAADAAAAAwBAMAAAClLOS0AAAAGFBMVEUAAAAkHiJeRUIcGBi9
1419 locQDQ4zJykFBAXJfWDjAAACYUlEQVR4nF2TQY/jIAyFc6lydlG5x8Nyp1Y69wj1PN2I5gzp
1420 Face-2:\x20
1421 iVBORw0KGgoAAAANSUhEUgAAADAAAAAwBAMAAAClLOS0AAAAGFBMVEUAAAAkHiJeRUIcGBi9
1422 locQDQ4zJykFBAXJfWDjAAACYUlEQVR4nF2TQY/jIAyFc6lydlG5x8Nyp1Y69wj1PN2I5gzp
1423 Face-3:\x20
1424 iVBORw0KGgoAAAANSUhEUgAAADAAAAAwBAMAAAClLOS0AAAAGFBMVEUAAAAkHiJeRUIcGBi9
1425 locQDQ4zJykFBAXJfWDjAAACYUlEQVR4nF2TQY/jIAyFc6lydlG5x8Nyp1Y69wj1PN2I5gzp
1426
1427 """)
1428
1429 def test_another_long_multiline_header(self):
1430 eq = self.ndiffAssertEqual
1431 m = ('Received: from siimage.com '
1432 '([172.25.1.3]) by zima.siliconimage.com with '
1433 'Microsoft SMTPSVC(5.0.2195.4905); '
1434 'Wed, 16 Oct 2002 07:41:11 -0700')
1435 msg = email.message_from_string(m)
1436 eq(msg.as_string(maxheaderlen=78), '''\
1437 Received: from siimage.com ([172.25.1.3]) by zima.siliconimage.com with
1438 Microsoft SMTPSVC(5.0.2195.4905); Wed, 16 Oct 2002 07:41:11 -0700
1439
1440 ''')
1441
1442 def test_long_lines_with_different_header(self):
1443 eq = self.ndiffAssertEqual
1444 h = ('List-Unsubscribe: '
1445 '<http://lists.sourceforge.net/lists/listinfo/spamassassin-talk>,'
1446 ' <mailto:[email protected]'
1447 '?subject=unsubscribe>')
1448 msg = Message()
1449 msg['List'] = h
1450 msg['List'] = Header(h, header_name='List')
1451 eq(msg.as_string(maxheaderlen=78), """\
1452 List: List-Unsubscribe:
1453 <http://lists.sourceforge.net/lists/listinfo/spamassassin-talk>,
1454 <mailto:[email protected]?subject=unsubscribe>
1455 List: List-Unsubscribe:
1456 <http://lists.sourceforge.net/lists/listinfo/spamassassin-talk>,
1457 <mailto:[email protected]?subject=unsubscribe>
1458
1459 """)
1460
1461 def test_long_rfc2047_header_with_embedded_fws(self):
1462 h = Header(textwrap.dedent("""\
1463 We're going to pretend this header is in a non-ascii character set
1464 \tto see if line wrapping with encoded words and embedded
1465 folding white space works"""),
1466 charset='utf-8',
1467 header_name='Test')
1468 self.assertEqual(h.encode()+'\n', textwrap.dedent("""\
1469 =?utf-8?q?We=27re_going_to_pretend_this_header_is_in_a_non-ascii_chara?=
1470 =?utf-8?q?cter_set?=
1471 =?utf-8?q?_to_see_if_line_wrapping_with_encoded_words_and_embedded?=
1472 =?utf-8?q?_folding_white_space_works?=""")+'\n')
1473
1474
1475
1476 # Test mangling of "From " lines in the body of a message
1477 class TestFromMangling(unittest.TestCase):
1478 def setUp(self):
1479 self.msg = Message()
1480 self.msg['From'] = '[email protected]'
1481 self.msg.set_payload("""\
1482 From the desk of A.A.A.:
1483 Blah blah blah
1484 """)
1485
1486 def test_mangled_from(self):
1487 s = StringIO()
1488 g = Generator(s, mangle_from_=True)
1489 g.flatten(self.msg)
1490 self.assertEqual(s.getvalue(), """\
1491 From: [email protected]
1492
1493 >From the desk of A.A.A.:
1494 Blah blah blah
1495 """)
1496
1497 def test_dont_mangle_from(self):
1498 s = StringIO()
1499 g = Generator(s, mangle_from_=False)
1500 g.flatten(self.msg)
1501 self.assertEqual(s.getvalue(), """\
1502 From: [email protected]
1503
1504 From the desk of A.A.A.:
1505 Blah blah blah
1506 """)
1507
1508 def test_mangle_from_in_preamble_and_epilog(self):
1509 s = StringIO()
1510 g = Generator(s, mangle_from_=True)
1511 msg = email.message_from_string(textwrap.dedent("""\
1512 From: [email protected]
1513 Mime-Version: 1.0
1514 Content-Type: multipart/mixed; boundary=XXX
1515
1516 From somewhere unknown
1517
1518 --XXX
1519 Content-Type: text/plain
1520
1521 foo
1522
1523 --XXX--
1524
1525 From somewhere unknowable
1526 """))
1527 g.flatten(msg)
1528 self.assertEqual(len([1 for x in s.getvalue().split('\n')
1529 if x.startswith('>From ')]), 2)
1530
1531 def test_mangled_from_with_bad_bytes(self):
1532 source = textwrap.dedent("""\
1533 Content-Type: text/plain; charset="utf-8"
1534 MIME-Version: 1.0
1535 Content-Transfer-Encoding: 8bit
1536 From: [email protected]
1537
1538 """).encode('utf-8')
1539 msg = email.message_from_bytes(source + b'From R\xc3\xb6lli\n')
1540 b = BytesIO()
1541 g = BytesGenerator(b, mangle_from_=True)
1542 g.flatten(msg)
1543 self.assertEqual(b.getvalue(), source + b'>From R\xc3\xb6lli\n')
1544
1545 def test_multipart_with_bad_bytes_in_cte(self):
1546 # bpo30835
1547 source = textwrap.dedent("""\
1548 From: [email protected]
1549 Content-Type: multipart/mixed; boundary="1"
1550 Content-Transfer-Encoding: \xc8
1551 """).encode('utf-8')
1552 msg = email.message_from_bytes(source)
1553
1554
1555 # Test the basic MIMEAudio class
1556 class TestMIMEAudio(unittest.TestCase):
1557 def _make_audio(self, ext):
1558 with openfile(f'sndhdr.{ext}', 'rb') as fp:
1559 self._audiodata = fp.read()
1560 self._au = MIMEAudio(self._audiodata)
1561
1562 def test_guess_minor_type(self):
1563 for ext, subtype in {
1564 'aifc': 'x-aiff',
1565 'aiff': 'x-aiff',
1566 'wav': 'x-wav',
1567 'au': 'basic',
1568 }.items():
1569 self._make_audio(ext)
1570 subtype = ext if subtype is None else subtype
1571 self.assertEqual(self._au.get_content_type(), f'audio/{subtype}')
1572
1573 def test_encoding(self):
1574 self._make_audio('au')
1575 payload = self._au.get_payload()
1576 self.assertEqual(base64.decodebytes(bytes(payload, 'ascii')),
1577 self._audiodata)
1578
1579 def test_checkSetMinor(self):
1580 self._make_audio('au')
1581 au = MIMEAudio(self._audiodata, 'fish')
1582 self.assertEqual(au.get_content_type(), 'audio/fish')
1583
1584 def test_add_header(self):
1585 self._make_audio('au')
1586 eq = self.assertEqual
1587 self._au.add_header('Content-Disposition', 'attachment',
1588 filename='sndhdr.au')
1589 eq(self._au['content-disposition'],
1590 'attachment; filename="sndhdr.au"')
1591 eq(self._au.get_params(header='content-disposition'),
1592 [('attachment', ''), ('filename', 'sndhdr.au')])
1593 eq(self._au.get_param('filename', header='content-disposition'),
1594 'sndhdr.au')
1595 missing = []
1596 eq(self._au.get_param('attachment', header='content-disposition'), '')
1597 self.assertIs(self._au.get_param(
1598 'foo', failobj=missing,
1599 header='content-disposition'), missing)
1600 # Try some missing stuff
1601 self.assertIs(self._au.get_param('foobar', missing), missing)
1602 self.assertIs(self._au.get_param('attachment', missing,
1603 header='foobar'), missing)
1604
1605
1606
1607 # Test the basic MIMEImage class
1608 class TestMIMEImage(unittest.TestCase):
1609 def _make_image(self, ext):
1610 with openfile(f'python.{ext}', 'rb') as fp:
1611 self._imgdata = fp.read()
1612 self._im = MIMEImage(self._imgdata)
1613
1614 def test_guess_minor_type(self):
1615 for ext, subtype in {
1616 'bmp': None,
1617 'exr': None,
1618 'gif': None,
1619 'jpg': 'jpeg',
1620 'pbm': None,
1621 'pgm': None,
1622 'png': None,
1623 'ppm': None,
1624 'ras': 'rast',
1625 'sgi': 'rgb',
1626 'tiff': None,
1627 'webp': None,
1628 'xbm': None,
1629 }.items():
1630 self._make_image(ext)
1631 subtype = ext if subtype is None else subtype
1632 self.assertEqual(self._im.get_content_type(), f'image/{subtype}')
1633
1634 def test_encoding(self):
1635 self._make_image('gif')
1636 payload = self._im.get_payload()
1637 self.assertEqual(base64.decodebytes(bytes(payload, 'ascii')),
1638 self._imgdata)
1639
1640 def test_checkSetMinor(self):
1641 self._make_image('gif')
1642 im = MIMEImage(self._imgdata, 'fish')
1643 self.assertEqual(im.get_content_type(), 'image/fish')
1644
1645 def test_add_header(self):
1646 self._make_image('gif')
1647 eq = self.assertEqual
1648 self._im.add_header('Content-Disposition', 'attachment',
1649 filename='dingusfish.gif')
1650 eq(self._im['content-disposition'],
1651 'attachment; filename="dingusfish.gif"')
1652 eq(self._im.get_params(header='content-disposition'),
1653 [('attachment', ''), ('filename', 'dingusfish.gif')])
1654 eq(self._im.get_param('filename', header='content-disposition'),
1655 'dingusfish.gif')
1656 missing = []
1657 eq(self._im.get_param('attachment', header='content-disposition'), '')
1658 self.assertIs(self._im.get_param('foo', failobj=missing,
1659 header='content-disposition'), missing)
1660 # Try some missing stuff
1661 self.assertIs(self._im.get_param('foobar', missing), missing)
1662 self.assertIs(self._im.get_param('attachment', missing,
1663 header='foobar'), missing)
1664
1665
1666 # Test the basic MIMEApplication class
1667 class TestMIMEApplication(unittest.TestCase):
1668 def test_headers(self):
1669 eq = self.assertEqual
1670 msg = MIMEApplication(b'\xfa\xfb\xfc\xfd\xfe\xff')
1671 eq(msg.get_content_type(), 'application/octet-stream')
1672 eq(msg['content-transfer-encoding'], 'base64')
1673
1674 def test_body(self):
1675 eq = self.assertEqual
1676 bytesdata = b'\xfa\xfb\xfc\xfd\xfe\xff'
1677 msg = MIMEApplication(bytesdata)
1678 # whitespace in the cte encoded block is RFC-irrelevant.
1679 eq(msg.get_payload().strip(), '+vv8/f7/')
1680 eq(msg.get_payload(decode=True), bytesdata)
1681
1682 def test_binary_body_with_encode_7or8bit(self):
1683 # Issue 17171.
1684 bytesdata = b'\xfa\xfb\xfc\xfd\xfe\xff'
1685 msg = MIMEApplication(bytesdata, _encoder=encoders.encode_7or8bit)
1686 # Treated as a string, this will be invalid code points.
1687 self.assertEqual(msg.get_payload(), '\uFFFD' * len(bytesdata))
1688 self.assertEqual(msg.get_payload(decode=True), bytesdata)
1689 self.assertEqual(msg['Content-Transfer-Encoding'], '8bit')
1690 s = BytesIO()
1691 g = BytesGenerator(s)
1692 g.flatten(msg)
1693 wireform = s.getvalue()
1694 msg2 = email.message_from_bytes(wireform)
1695 self.assertEqual(msg.get_payload(), '\uFFFD' * len(bytesdata))
1696 self.assertEqual(msg2.get_payload(decode=True), bytesdata)
1697 self.assertEqual(msg2['Content-Transfer-Encoding'], '8bit')
1698
1699 def test_binary_body_with_encode_noop(self):
1700 # Issue 16564: This does not produce an RFC valid message, since to be
1701 # valid it should have a CTE of binary. But the below works in
1702 # Python2, and is documented as working this way.
1703 bytesdata = b'\xfa\xfb\xfc\xfd\xfe\xff'
1704 msg = MIMEApplication(bytesdata, _encoder=encoders.encode_noop)
1705 # Treated as a string, this will be invalid code points.
1706 self.assertEqual(msg.get_payload(), '\uFFFD' * len(bytesdata))
1707 self.assertEqual(msg.get_payload(decode=True), bytesdata)
1708 s = BytesIO()
1709 g = BytesGenerator(s)
1710 g.flatten(msg)
1711 wireform = s.getvalue()
1712 msg2 = email.message_from_bytes(wireform)
1713 self.assertEqual(msg.get_payload(), '\uFFFD' * len(bytesdata))
1714 self.assertEqual(msg2.get_payload(decode=True), bytesdata)
1715
1716 def test_binary_body_with_unicode_linend_encode_noop(self):
1717 # Issue 19003: This is a variation on #16564.
1718 bytesdata = b'\x0b\xfa\xfb\xfc\xfd\xfe\xff'
1719 msg = MIMEApplication(bytesdata, _encoder=encoders.encode_noop)
1720 self.assertEqual(msg.get_payload(decode=True), bytesdata)
1721 s = BytesIO()
1722 g = BytesGenerator(s)
1723 g.flatten(msg)
1724 wireform = s.getvalue()
1725 msg2 = email.message_from_bytes(wireform)
1726 self.assertEqual(msg2.get_payload(decode=True), bytesdata)
1727
1728 def test_binary_body_with_encode_quopri(self):
1729 # Issue 14360.
1730 bytesdata = b'\xfa\xfb\xfc\xfd\xfe\xff '
1731 msg = MIMEApplication(bytesdata, _encoder=encoders.encode_quopri)
1732 self.assertEqual(msg.get_payload(), '=FA=FB=FC=FD=FE=FF=20')
1733 self.assertEqual(msg.get_payload(decode=True), bytesdata)
1734 self.assertEqual(msg['Content-Transfer-Encoding'], 'quoted-printable')
1735 s = BytesIO()
1736 g = BytesGenerator(s)
1737 g.flatten(msg)
1738 wireform = s.getvalue()
1739 msg2 = email.message_from_bytes(wireform)
1740 self.assertEqual(msg.get_payload(), '=FA=FB=FC=FD=FE=FF=20')
1741 self.assertEqual(msg2.get_payload(decode=True), bytesdata)
1742 self.assertEqual(msg2['Content-Transfer-Encoding'], 'quoted-printable')
1743
1744 def test_binary_body_with_encode_base64(self):
1745 bytesdata = b'\xfa\xfb\xfc\xfd\xfe\xff'
1746 msg = MIMEApplication(bytesdata, _encoder=encoders.encode_base64)
1747 self.assertEqual(msg.get_payload(), '+vv8/f7/\n')
1748 self.assertEqual(msg.get_payload(decode=True), bytesdata)
1749 s = BytesIO()
1750 g = BytesGenerator(s)
1751 g.flatten(msg)
1752 wireform = s.getvalue()
1753 msg2 = email.message_from_bytes(wireform)
1754 self.assertEqual(msg.get_payload(), '+vv8/f7/\n')
1755 self.assertEqual(msg2.get_payload(decode=True), bytesdata)
1756
1757
1758 # Test the basic MIMEText class
1759 class TestMIMEText(unittest.TestCase):
1760 def setUp(self):
1761 self._msg = MIMEText('hello there')
1762
1763 def test_types(self):
1764 eq = self.assertEqual
1765 eq(self._msg.get_content_type(), 'text/plain')
1766 eq(self._msg.get_param('charset'), 'us-ascii')
1767 missing = []
1768 self.assertIs(self._msg.get_param('foobar', missing), missing)
1769 self.assertIs(self._msg.get_param('charset', missing, header='foobar'),
1770 missing)
1771
1772 def test_payload(self):
1773 self.assertEqual(self._msg.get_payload(), 'hello there')
1774 self.assertFalse(self._msg.is_multipart())
1775
1776 def test_charset(self):
1777 eq = self.assertEqual
1778 msg = MIMEText('hello there', _charset='us-ascii')
1779 eq(msg.get_charset().input_charset, 'us-ascii')
1780 eq(msg['content-type'], 'text/plain; charset="us-ascii"')
1781 # Also accept a Charset instance
1782 charset = Charset('utf-8')
1783 charset.body_encoding = None
1784 msg = MIMEText('hello there', _charset=charset)
1785 eq(msg.get_charset().input_charset, 'utf-8')
1786 eq(msg['content-type'], 'text/plain; charset="utf-8"')
1787 eq(msg.get_payload(), 'hello there')
1788
1789 def test_7bit_input(self):
1790 eq = self.assertEqual
1791 msg = MIMEText('hello there', _charset='us-ascii')
1792 eq(msg.get_charset().input_charset, 'us-ascii')
1793 eq(msg['content-type'], 'text/plain; charset="us-ascii"')
1794
1795 def test_7bit_input_no_charset(self):
1796 eq = self.assertEqual
1797 msg = MIMEText('hello there')
1798 eq(msg.get_charset(), 'us-ascii')
1799 eq(msg['content-type'], 'text/plain; charset="us-ascii"')
1800 self.assertIn('hello there', msg.as_string())
1801
1802 def test_utf8_input(self):
1803 teststr = '\u043a\u0438\u0440\u0438\u043b\u0438\u0446\u0430'
1804 eq = self.assertEqual
1805 msg = MIMEText(teststr, _charset='utf-8')
1806 eq(msg.get_charset().output_charset, 'utf-8')
1807 eq(msg['content-type'], 'text/plain; charset="utf-8"')
1808 eq(msg.get_payload(decode=True), teststr.encode('utf-8'))
1809
1810 @unittest.skip("can't fix because of backward compat in email5, "
1811 "will fix in email6")
1812 def test_utf8_input_no_charset(self):
1813 teststr = '\u043a\u0438\u0440\u0438\u043b\u0438\u0446\u0430'
1814 self.assertRaises(UnicodeEncodeError, MIMEText, teststr)
1815
1816
1817
1818 # Test complicated multipart/* messages
1819 class TestMultipart(TestEmailBase):
1820 def setUp(self):
1821 with openfile('python.gif', 'rb') as fp:
1822 data = fp.read()
1823 container = MIMEBase('multipart', 'mixed', boundary='BOUNDARY')
1824 image = MIMEImage(data, name='dingusfish.gif')
1825 image.add_header('content-disposition', 'attachment',
1826 filename='dingusfish.gif')
1827 intro = MIMEText('''\
1828 Hi there,
1829
1830 This is the dingus fish.
1831 ''')
1832 container.attach(intro)
1833 container.attach(image)
1834 container['From'] = 'Barry <[email protected]>'
1835 container['To'] = 'Dingus Lovers <[email protected]>'
1836 container['Subject'] = 'Here is your dingus fish'
1837
1838 now = 987809702.54848599
1839 timetuple = time.localtime(now)
1840 if timetuple[-1] == 0:
1841 tzsecs = time.timezone
1842 else:
1843 tzsecs = time.altzone
1844 if tzsecs > 0:
1845 sign = '-'
1846 else:
1847 sign = '+'
1848 tzoffset = ' %s%04d' % (sign, tzsecs / 36)
1849 container['Date'] = time.strftime(
1850 '%a, %d %b %Y %H:%M:%S',
1851 time.localtime(now)) + tzoffset
1852 self._msg = container
1853 self._im = image
1854 self._txt = intro
1855
1856 def test_hierarchy(self):
1857 # convenience
1858 eq = self.assertEqual
1859 raises = self.assertRaises
1860 # tests
1861 m = self._msg
1862 self.assertTrue(m.is_multipart())
1863 eq(m.get_content_type(), 'multipart/mixed')
1864 eq(len(m.get_payload()), 2)
1865 raises(IndexError, m.get_payload, 2)
1866 m0 = m.get_payload(0)
1867 m1 = m.get_payload(1)
1868 self.assertIs(m0, self._txt)
1869 self.assertIs(m1, self._im)
1870 eq(m.get_payload(), [m0, m1])
1871 self.assertFalse(m0.is_multipart())
1872 self.assertFalse(m1.is_multipart())
1873
1874 def test_empty_multipart_idempotent(self):
1875 text = """\
1876 Content-Type: multipart/mixed; boundary="BOUNDARY"
1877 MIME-Version: 1.0
1878 Subject: A subject
1879 To: [email protected]
1880 From: [email protected]
1881
1882
1883 --BOUNDARY
1884
1885
1886 --BOUNDARY--
1887 """
1888 msg = Parser().parsestr(text)
1889 self.ndiffAssertEqual(text, msg.as_string())
1890
1891 def test_no_parts_in_a_multipart_with_none_epilogue(self):
1892 outer = MIMEBase('multipart', 'mixed')
1893 outer['Subject'] = 'A subject'
1894 outer['To'] = '[email protected]'
1895 outer['From'] = '[email protected]'
1896 outer.set_boundary('BOUNDARY')
1897 self.ndiffAssertEqual(outer.as_string(), '''\
1898 Content-Type: multipart/mixed; boundary="BOUNDARY"
1899 MIME-Version: 1.0
1900 Subject: A subject
1901 To: [email protected]
1902 From: [email protected]
1903
1904 --BOUNDARY
1905
1906 --BOUNDARY--
1907 ''')
1908
1909 def test_no_parts_in_a_multipart_with_empty_epilogue(self):
1910 outer = MIMEBase('multipart', 'mixed')
1911 outer['Subject'] = 'A subject'
1912 outer['To'] = '[email protected]'
1913 outer['From'] = '[email protected]'
1914 outer.preamble = ''
1915 outer.epilogue = ''
1916 outer.set_boundary('BOUNDARY')
1917 self.ndiffAssertEqual(outer.as_string(), '''\
1918 Content-Type: multipart/mixed; boundary="BOUNDARY"
1919 MIME-Version: 1.0
1920 Subject: A subject
1921 To: [email protected]
1922 From: [email protected]
1923
1924
1925 --BOUNDARY
1926
1927 --BOUNDARY--
1928 ''')
1929
1930 def test_one_part_in_a_multipart(self):
1931 eq = self.ndiffAssertEqual
1932 outer = MIMEBase('multipart', 'mixed')
1933 outer['Subject'] = 'A subject'
1934 outer['To'] = '[email protected]'
1935 outer['From'] = '[email protected]'
1936 outer.set_boundary('BOUNDARY')
1937 msg = MIMEText('hello world')
1938 outer.attach(msg)
1939 eq(outer.as_string(), '''\
1940 Content-Type: multipart/mixed; boundary="BOUNDARY"
1941 MIME-Version: 1.0
1942 Subject: A subject
1943 To: [email protected]
1944 From: [email protected]
1945
1946 --BOUNDARY
1947 Content-Type: text/plain; charset="us-ascii"
1948 MIME-Version: 1.0
1949 Content-Transfer-Encoding: 7bit
1950
1951 hello world
1952 --BOUNDARY--
1953 ''')
1954
1955 def test_seq_parts_in_a_multipart_with_empty_preamble(self):
1956 eq = self.ndiffAssertEqual
1957 outer = MIMEBase('multipart', 'mixed')
1958 outer['Subject'] = 'A subject'
1959 outer['To'] = '[email protected]'
1960 outer['From'] = '[email protected]'
1961 outer.preamble = ''
1962 msg = MIMEText('hello world')
1963 outer.attach(msg)
1964 outer.set_boundary('BOUNDARY')
1965 eq(outer.as_string(), '''\
1966 Content-Type: multipart/mixed; boundary="BOUNDARY"
1967 MIME-Version: 1.0
1968 Subject: A subject
1969 To: [email protected]
1970 From: [email protected]
1971
1972
1973 --BOUNDARY
1974 Content-Type: text/plain; charset="us-ascii"
1975 MIME-Version: 1.0
1976 Content-Transfer-Encoding: 7bit
1977
1978 hello world
1979 --BOUNDARY--
1980 ''')
1981
1982
1983 def test_seq_parts_in_a_multipart_with_none_preamble(self):
1984 eq = self.ndiffAssertEqual
1985 outer = MIMEBase('multipart', 'mixed')
1986 outer['Subject'] = 'A subject'
1987 outer['To'] = '[email protected]'
1988 outer['From'] = '[email protected]'
1989 outer.preamble = None
1990 msg = MIMEText('hello world')
1991 outer.attach(msg)
1992 outer.set_boundary('BOUNDARY')
1993 eq(outer.as_string(), '''\
1994 Content-Type: multipart/mixed; boundary="BOUNDARY"
1995 MIME-Version: 1.0
1996 Subject: A subject
1997 To: [email protected]
1998 From: [email protected]
1999
2000 --BOUNDARY
2001 Content-Type: text/plain; charset="us-ascii"
2002 MIME-Version: 1.0
2003 Content-Transfer-Encoding: 7bit
2004
2005 hello world
2006 --BOUNDARY--
2007 ''')
2008
2009
2010 def test_seq_parts_in_a_multipart_with_none_epilogue(self):
2011 eq = self.ndiffAssertEqual
2012 outer = MIMEBase('multipart', 'mixed')
2013 outer['Subject'] = 'A subject'
2014 outer['To'] = '[email protected]'
2015 outer['From'] = '[email protected]'
2016 outer.epilogue = None
2017 msg = MIMEText('hello world')
2018 outer.attach(msg)
2019 outer.set_boundary('BOUNDARY')
2020 eq(outer.as_string(), '''\
2021 Content-Type: multipart/mixed; boundary="BOUNDARY"
2022 MIME-Version: 1.0
2023 Subject: A subject
2024 To: [email protected]
2025 From: [email protected]
2026
2027 --BOUNDARY
2028 Content-Type: text/plain; charset="us-ascii"
2029 MIME-Version: 1.0
2030 Content-Transfer-Encoding: 7bit
2031
2032 hello world
2033 --BOUNDARY--
2034 ''')
2035
2036
2037 def test_seq_parts_in_a_multipart_with_empty_epilogue(self):
2038 eq = self.ndiffAssertEqual
2039 outer = MIMEBase('multipart', 'mixed')
2040 outer['Subject'] = 'A subject'
2041 outer['To'] = '[email protected]'
2042 outer['From'] = '[email protected]'
2043 outer.epilogue = ''
2044 msg = MIMEText('hello world')
2045 outer.attach(msg)
2046 outer.set_boundary('BOUNDARY')
2047 eq(outer.as_string(), '''\
2048 Content-Type: multipart/mixed; boundary="BOUNDARY"
2049 MIME-Version: 1.0
2050 Subject: A subject
2051 To: [email protected]
2052 From: [email protected]
2053
2054 --BOUNDARY
2055 Content-Type: text/plain; charset="us-ascii"
2056 MIME-Version: 1.0
2057 Content-Transfer-Encoding: 7bit
2058
2059 hello world
2060 --BOUNDARY--
2061 ''')
2062
2063
2064 def test_seq_parts_in_a_multipart_with_nl_epilogue(self):
2065 eq = self.ndiffAssertEqual
2066 outer = MIMEBase('multipart', 'mixed')
2067 outer['Subject'] = 'A subject'
2068 outer['To'] = '[email protected]'
2069 outer['From'] = '[email protected]'
2070 outer.epilogue = '\n'
2071 msg = MIMEText('hello world')
2072 outer.attach(msg)
2073 outer.set_boundary('BOUNDARY')
2074 eq(outer.as_string(), '''\
2075 Content-Type: multipart/mixed; boundary="BOUNDARY"
2076 MIME-Version: 1.0
2077 Subject: A subject
2078 To: [email protected]
2079 From: [email protected]
2080
2081 --BOUNDARY
2082 Content-Type: text/plain; charset="us-ascii"
2083 MIME-Version: 1.0
2084 Content-Transfer-Encoding: 7bit
2085
2086 hello world
2087 --BOUNDARY--
2088
2089 ''')
2090
2091 def test_message_external_body(self):
2092 eq = self.assertEqual
2093 msg = self._msgobj('msg_36.txt')
2094 eq(len(msg.get_payload()), 2)
2095 msg1 = msg.get_payload(1)
2096 eq(msg1.get_content_type(), 'multipart/alternative')
2097 eq(len(msg1.get_payload()), 2)
2098 for subpart in msg1.get_payload():
2099 eq(subpart.get_content_type(), 'message/external-body')
2100 eq(len(subpart.get_payload()), 1)
2101 subsubpart = subpart.get_payload(0)
2102 eq(subsubpart.get_content_type(), 'text/plain')
2103
2104 def test_double_boundary(self):
2105 # msg_37.txt is a multipart that contains two dash-boundary's in a
2106 # row. Our interpretation of RFC 2046 calls for ignoring the second
2107 # and subsequent boundaries.
2108 msg = self._msgobj('msg_37.txt')
2109 self.assertEqual(len(msg.get_payload()), 3)
2110
2111 def test_nested_inner_contains_outer_boundary(self):
2112 eq = self.ndiffAssertEqual
2113 # msg_38.txt has an inner part that contains outer boundaries. My
2114 # interpretation of RFC 2046 (based on sections 5.1 and 5.1.2) say
2115 # these are illegal and should be interpreted as unterminated inner
2116 # parts.
2117 msg = self._msgobj('msg_38.txt')
2118 sfp = StringIO()
2119 iterators._structure(msg, sfp)
2120 eq(sfp.getvalue(), """\
2121 multipart/mixed
2122 multipart/mixed
2123 multipart/alternative
2124 text/plain
2125 text/plain
2126 text/plain
2127 text/plain
2128 """)
2129
2130 def test_nested_with_same_boundary(self):
2131 eq = self.ndiffAssertEqual
2132 # msg 39.txt is similarly evil in that it's got inner parts that use
2133 # the same boundary as outer parts. Again, I believe the way this is
2134 # parsed is closest to the spirit of RFC 2046
2135 msg = self._msgobj('msg_39.txt')
2136 sfp = StringIO()
2137 iterators._structure(msg, sfp)
2138 eq(sfp.getvalue(), """\
2139 multipart/mixed
2140 multipart/mixed
2141 multipart/alternative
2142 application/octet-stream
2143 application/octet-stream
2144 text/plain
2145 """)
2146
2147 def test_boundary_in_non_multipart(self):
2148 msg = self._msgobj('msg_40.txt')
2149 self.assertEqual(msg.as_string(), '''\
2150 MIME-Version: 1.0
2151 Content-Type: text/html; boundary="--961284236552522269"
2152
2153 ----961284236552522269
2154 Content-Type: text/html;
2155 Content-Transfer-Encoding: 7Bit
2156
2157 <html></html>
2158
2159 ----961284236552522269--
2160 ''')
2161
2162 def test_boundary_with_leading_space(self):
2163 eq = self.assertEqual
2164 msg = email.message_from_string('''\
2165 MIME-Version: 1.0
2166 Content-Type: multipart/mixed; boundary=" XXXX"
2167
2168 -- XXXX
2169 Content-Type: text/plain
2170
2171
2172 -- XXXX
2173 Content-Type: text/plain
2174
2175 -- XXXX--
2176 ''')
2177 self.assertTrue(msg.is_multipart())
2178 eq(msg.get_boundary(), ' XXXX')
2179 eq(len(msg.get_payload()), 2)
2180
2181 def test_boundary_without_trailing_newline(self):
2182 m = Parser().parsestr("""\
2183 Content-Type: multipart/mixed; boundary="===============0012394164=="
2184 MIME-Version: 1.0
2185
2186 --===============0012394164==
2187 Content-Type: image/file1.jpg
2188 MIME-Version: 1.0
2189 Content-Transfer-Encoding: base64
2190
2191 YXNkZg==
2192 --===============0012394164==--""")
2193 self.assertEqual(m.get_payload(0).get_payload(), 'YXNkZg==')
2194
2195 def test_mimebase_default_policy(self):
2196 m = MIMEBase('multipart', 'mixed')
2197 self.assertIs(m.policy, email.policy.compat32)
2198
2199 def test_mimebase_custom_policy(self):
2200 m = MIMEBase('multipart', 'mixed', policy=email.policy.default)
2201 self.assertIs(m.policy, email.policy.default)
2202
2203 # Test some badly formatted messages
2204 class TestNonConformant(TestEmailBase):
2205
2206 def test_parse_missing_minor_type(self):
2207 eq = self.assertEqual
2208 msg = self._msgobj('msg_14.txt')
2209 eq(msg.get_content_type(), 'text/plain')
2210 eq(msg.get_content_maintype(), 'text')
2211 eq(msg.get_content_subtype(), 'plain')
2212
2213 # test_defect_handling
2214 def test_same_boundary_inner_outer(self):
2215 msg = self._msgobj('msg_15.txt')
2216 # XXX We can probably eventually do better
2217 inner = msg.get_payload(0)
2218 self.assertTrue(hasattr(inner, 'defects'))
2219 self.assertEqual(len(inner.defects), 1)
2220 self.assertIsInstance(inner.defects[0],
2221 errors.StartBoundaryNotFoundDefect)
2222
2223 # test_defect_handling
2224 def test_multipart_no_boundary(self):
2225 msg = self._msgobj('msg_25.txt')
2226 self.assertIsInstance(msg.get_payload(), str)
2227 self.assertEqual(len(msg.defects), 2)
2228 self.assertIsInstance(msg.defects[0],
2229 errors.NoBoundaryInMultipartDefect)
2230 self.assertIsInstance(msg.defects[1],
2231 errors.MultipartInvariantViolationDefect)
2232
2233 multipart_msg = textwrap.dedent("""\
2234 Date: Wed, 14 Nov 2007 12:56:23 GMT
2235 From: [email protected]
2236 To: [email protected]
2237 Subject: Content-Transfer-Encoding: base64 and multipart
2238 MIME-Version: 1.0
2239 Content-Type: multipart/mixed;
2240 boundary="===============3344438784458119861=="{}
2241
2242 --===============3344438784458119861==
2243 Content-Type: text/plain
2244
2245 Test message
2246
2247 --===============3344438784458119861==
2248 Content-Type: application/octet-stream
2249 Content-Transfer-Encoding: base64
2250
2251 YWJj
2252
2253 --===============3344438784458119861==--
2254 """)
2255
2256 # test_defect_handling
2257 def test_multipart_invalid_cte(self):
2258 msg = self._str_msg(
2259 self.multipart_msg.format("\nContent-Transfer-Encoding: base64"))
2260 self.assertEqual(len(msg.defects), 1)
2261 self.assertIsInstance(msg.defects[0],
2262 errors.InvalidMultipartContentTransferEncodingDefect)
2263
2264 # test_defect_handling
2265 def test_multipart_no_cte_no_defect(self):
2266 msg = self._str_msg(self.multipart_msg.format(''))
2267 self.assertEqual(len(msg.defects), 0)
2268
2269 # test_defect_handling
2270 def test_multipart_valid_cte_no_defect(self):
2271 for cte in ('7bit', '8bit', 'BINary'):
2272 msg = self._str_msg(
2273 self.multipart_msg.format(
2274 "\nContent-Transfer-Encoding: {}".format(cte)))
2275 self.assertEqual(len(msg.defects), 0)
2276
2277 # test_headerregistry.TestContentTyopeHeader invalid_1 and invalid_2.
2278 def test_invalid_content_type(self):
2279 eq = self.assertEqual
2280 neq = self.ndiffAssertEqual
2281 msg = Message()
2282 # RFC 2045, $5.2 says invalid yields text/plain
2283 msg['Content-Type'] = 'text'
2284 eq(msg.get_content_maintype(), 'text')
2285 eq(msg.get_content_subtype(), 'plain')
2286 eq(msg.get_content_type(), 'text/plain')
2287 # Clear the old value and try something /really/ invalid
2288 del msg['content-type']
2289 msg['Content-Type'] = 'foo'
2290 eq(msg.get_content_maintype(), 'text')
2291 eq(msg.get_content_subtype(), 'plain')
2292 eq(msg.get_content_type(), 'text/plain')
2293 # Still, make sure that the message is idempotently generated
2294 s = StringIO()
2295 g = Generator(s)
2296 g.flatten(msg)
2297 neq(s.getvalue(), 'Content-Type: foo\n\n')
2298
2299 def test_no_start_boundary(self):
2300 eq = self.ndiffAssertEqual
2301 msg = self._msgobj('msg_31.txt')
2302 eq(msg.get_payload(), """\
2303 --BOUNDARY
2304 Content-Type: text/plain
2305
2306 message 1
2307
2308 --BOUNDARY
2309 Content-Type: text/plain
2310
2311 message 2
2312
2313 --BOUNDARY--
2314 """)
2315
2316 def test_no_separating_blank_line(self):
2317 eq = self.ndiffAssertEqual
2318 msg = self._msgobj('msg_35.txt')
2319 eq(msg.as_string(), """\
2320 From: [email protected]
2321 To: [email protected]
2322 Subject: here's something interesting
2323
2324 counter to RFC 2822, there's no separating newline here
2325 """)
2326
2327 # test_defect_handling
2328 def test_lying_multipart(self):
2329 msg = self._msgobj('msg_41.txt')
2330 self.assertTrue(hasattr(msg, 'defects'))
2331 self.assertEqual(len(msg.defects), 2)
2332 self.assertIsInstance(msg.defects[0],
2333 errors.NoBoundaryInMultipartDefect)
2334 self.assertIsInstance(msg.defects[1],
2335 errors.MultipartInvariantViolationDefect)
2336
2337 # test_defect_handling
2338 def test_missing_start_boundary(self):
2339 outer = self._msgobj('msg_42.txt')
2340 # The message structure is:
2341 #
2342 # multipart/mixed
2343 # text/plain
2344 # message/rfc822
2345 # multipart/mixed [*]
2346 #
2347 # [*] This message is missing its start boundary
2348 bad = outer.get_payload(1).get_payload(0)
2349 self.assertEqual(len(bad.defects), 1)
2350 self.assertIsInstance(bad.defects[0],
2351 errors.StartBoundaryNotFoundDefect)
2352
2353 # test_defect_handling
2354 def test_first_line_is_continuation_header(self):
2355 eq = self.assertEqual
2356 m = ' Line 1\nSubject: test\n\nbody'
2357 msg = email.message_from_string(m)
2358 eq(msg.keys(), ['Subject'])
2359 eq(msg.get_payload(), 'body')
2360 eq(len(msg.defects), 1)
2361 self.assertDefectsEqual(msg.defects,
2362 [errors.FirstHeaderLineIsContinuationDefect])
2363 eq(msg.defects[0].line, ' Line 1\n')
2364
2365 # test_defect_handling
2366 def test_missing_header_body_separator(self):
2367 # Our heuristic if we see a line that doesn't look like a header (no
2368 # leading whitespace but no ':') is to assume that the blank line that
2369 # separates the header from the body is missing, and to stop parsing
2370 # headers and start parsing the body.
2371 msg = self._str_msg('Subject: test\nnot a header\nTo: abc\n\nb\n')
2372 self.assertEqual(msg.keys(), ['Subject'])
2373 self.assertEqual(msg.get_payload(), 'not a header\nTo: abc\n\nb\n')
2374 self.assertDefectsEqual(msg.defects,
2375 [errors.MissingHeaderBodySeparatorDefect])
2376
2377
2378 # Test RFC 2047 header encoding and decoding
2379 class TestRFC2047(TestEmailBase):
2380 def test_rfc2047_multiline(self):
2381 eq = self.assertEqual
2382 s = """Re: =?mac-iceland?q?r=8Aksm=9Arg=8Cs?= baz
2383 foo bar =?mac-iceland?q?r=8Aksm=9Arg=8Cs?="""
2384 dh = decode_header(s)
2385 eq(dh, [
2386 (b'Re: ', None),
2387 (b'r\x8aksm\x9arg\x8cs', 'mac-iceland'),
2388 (b' baz foo bar ', None),
2389 (b'r\x8aksm\x9arg\x8cs', 'mac-iceland')])
2390 header = make_header(dh)
2391 eq(str(header),
2392 'Re: r\xe4ksm\xf6rg\xe5s baz foo bar r\xe4ksm\xf6rg\xe5s')
2393 self.ndiffAssertEqual(header.encode(maxlinelen=76), """\
2394 Re: =?mac-iceland?q?r=8Aksm=9Arg=8Cs?= baz foo bar =?mac-iceland?q?r=8Aksm?=
2395 =?mac-iceland?q?=9Arg=8Cs?=""")
2396
2397 def test_whitespace_keeper_unicode(self):
2398 eq = self.assertEqual
2399 s = '=?ISO-8859-1?Q?Andr=E9?= Pirard <[email protected]>'
2400 dh = decode_header(s)
2401 eq(dh, [(b'Andr\xe9', 'iso-8859-1'),
2402 (b' Pirard <[email protected]>', None)])
2403 header = str(make_header(dh))
2404 eq(header, 'Andr\xe9 Pirard <[email protected]>')
2405
2406 def test_whitespace_keeper_unicode_2(self):
2407 eq = self.assertEqual
2408 s = 'The =?iso-8859-1?b?cXVpY2sgYnJvd24gZm94?= jumped over the =?iso-8859-1?b?bGF6eSBkb2c=?='
2409 dh = decode_header(s)
2410 eq(dh, [(b'The ', None), (b'quick brown fox', 'iso-8859-1'),
2411 (b' jumped over the ', None), (b'lazy dog', 'iso-8859-1')])
2412 hu = str(make_header(dh))
2413 eq(hu, 'The quick brown fox jumped over the lazy dog')
2414
2415 def test_rfc2047_missing_whitespace(self):
2416 s = 'Sm=?ISO-8859-1?B?9g==?=rg=?ISO-8859-1?B?5Q==?=sbord'
2417 dh = decode_header(s)
2418 self.assertEqual(dh, [(b'Sm', None), (b'\xf6', 'iso-8859-1'),
2419 (b'rg', None), (b'\xe5', 'iso-8859-1'),
2420 (b'sbord', None)])
2421
2422 def test_rfc2047_with_whitespace(self):
2423 s = 'Sm =?ISO-8859-1?B?9g==?= rg =?ISO-8859-1?B?5Q==?= sbord'
2424 dh = decode_header(s)
2425 self.assertEqual(dh, [(b'Sm ', None), (b'\xf6', 'iso-8859-1'),
2426 (b' rg ', None), (b'\xe5', 'iso-8859-1'),
2427 (b' sbord', None)])
2428
2429 def test_rfc2047_B_bad_padding(self):
2430 s = '=?iso-8859-1?B?%s?='
2431 data = [ # only test complete bytes
2432 ('dm==', b'v'), ('dm=', b'v'), ('dm', b'v'),
2433 ('dmk=', b'vi'), ('dmk', b'vi')
2434 ]
2435 for q, a in data:
2436 dh = decode_header(s % q)
2437 self.assertEqual(dh, [(a, 'iso-8859-1')])
2438
2439 def test_rfc2047_Q_invalid_digits(self):
2440 # issue 10004.
2441 s = '=?iso-8859-1?Q?andr=e9=zz?='
2442 self.assertEqual(decode_header(s),
2443 [(b'andr\xe9=zz', 'iso-8859-1')])
2444
2445 def test_rfc2047_rfc2047_1(self):
2446 # 1st testcase at end of rfc2047
2447 s = '(=?ISO-8859-1?Q?a?=)'
2448 self.assertEqual(decode_header(s),
2449 [(b'(', None), (b'a', 'iso-8859-1'), (b')', None)])
2450
2451 def test_rfc2047_rfc2047_2(self):
2452 # 2nd testcase at end of rfc2047
2453 s = '(=?ISO-8859-1?Q?a?= b)'
2454 self.assertEqual(decode_header(s),
2455 [(b'(', None), (b'a', 'iso-8859-1'), (b' b)', None)])
2456
2457 def test_rfc2047_rfc2047_3(self):
2458 # 3rd testcase at end of rfc2047
2459 s = '(=?ISO-8859-1?Q?a?= =?ISO-8859-1?Q?b?=)'
2460 self.assertEqual(decode_header(s),
2461 [(b'(', None), (b'ab', 'iso-8859-1'), (b')', None)])
2462
2463 def test_rfc2047_rfc2047_4(self):
2464 # 4th testcase at end of rfc2047
2465 s = '(=?ISO-8859-1?Q?a?= =?ISO-8859-1?Q?b?=)'
2466 self.assertEqual(decode_header(s),
2467 [(b'(', None), (b'ab', 'iso-8859-1'), (b')', None)])
2468
2469 def test_rfc2047_rfc2047_5a(self):
2470 # 5th testcase at end of rfc2047 newline is \r\n
2471 s = '(=?ISO-8859-1?Q?a?=\r\n =?ISO-8859-1?Q?b?=)'
2472 self.assertEqual(decode_header(s),
2473 [(b'(', None), (b'ab', 'iso-8859-1'), (b')', None)])
2474
2475 def test_rfc2047_rfc2047_5b(self):
2476 # 5th testcase at end of rfc2047 newline is \n
2477 s = '(=?ISO-8859-1?Q?a?=\n =?ISO-8859-1?Q?b?=)'
2478 self.assertEqual(decode_header(s),
2479 [(b'(', None), (b'ab', 'iso-8859-1'), (b')', None)])
2480
2481 def test_rfc2047_rfc2047_6(self):
2482 # 6th testcase at end of rfc2047
2483 s = '(=?ISO-8859-1?Q?a_b?=)'
2484 self.assertEqual(decode_header(s),
2485 [(b'(', None), (b'a b', 'iso-8859-1'), (b')', None)])
2486
2487 def test_rfc2047_rfc2047_7(self):
2488 # 7th testcase at end of rfc2047
2489 s = '(=?ISO-8859-1?Q?a?= =?ISO-8859-2?Q?_b?=)'
2490 self.assertEqual(decode_header(s),
2491 [(b'(', None), (b'a', 'iso-8859-1'), (b' b', 'iso-8859-2'),
2492 (b')', None)])
2493 self.assertEqual(make_header(decode_header(s)).encode(), s.lower())
2494 self.assertEqual(str(make_header(decode_header(s))), '(a b)')
2495
2496 def test_multiline_header(self):
2497 s = '=?windows-1252?q?=22M=FCller_T=22?=\r\n <[email protected]>'
2498 self.assertEqual(decode_header(s),
2499 [(b'"M\xfcller T"', 'windows-1252'),
2500 (b'<[email protected]>', None)])
2501 self.assertEqual(make_header(decode_header(s)).encode(),
2502 ''.join(s.splitlines()))
2503 self.assertEqual(str(make_header(decode_header(s))),
2504 '"Müller T" <[email protected]>')
2505
2506
2507 # Test the MIMEMessage class
2508 class TestMIMEMessage(TestEmailBase):
2509 def setUp(self):
2510 with openfile('msg_11.txt', encoding="utf-8") as fp:
2511 self._text = fp.read()
2512
2513 def test_type_error(self):
2514 self.assertRaises(TypeError, MIMEMessage, 'a plain string')
2515
2516 def test_valid_argument(self):
2517 eq = self.assertEqual
2518 subject = 'A sub-message'
2519 m = Message()
2520 m['Subject'] = subject
2521 r = MIMEMessage(m)
2522 eq(r.get_content_type(), 'message/rfc822')
2523 payload = r.get_payload()
2524 self.assertIsInstance(payload, list)
2525 eq(len(payload), 1)
2526 subpart = payload[0]
2527 self.assertIs(subpart, m)
2528 eq(subpart['subject'], subject)
2529
2530 def test_bad_multipart(self):
2531 msg1 = Message()
2532 msg1['Subject'] = 'subpart 1'
2533 msg2 = Message()
2534 msg2['Subject'] = 'subpart 2'
2535 r = MIMEMessage(msg1)
2536 self.assertRaises(errors.MultipartConversionError, r.attach, msg2)
2537
2538 def test_generate(self):
2539 # First craft the message to be encapsulated
2540 m = Message()
2541 m['Subject'] = 'An enclosed message'
2542 m.set_payload('Here is the body of the message.\n')
2543 r = MIMEMessage(m)
2544 r['Subject'] = 'The enclosing message'
2545 s = StringIO()
2546 g = Generator(s)
2547 g.flatten(r)
2548 self.assertEqual(s.getvalue(), """\
2549 Content-Type: message/rfc822
2550 MIME-Version: 1.0
2551 Subject: The enclosing message
2552
2553 Subject: An enclosed message
2554
2555 Here is the body of the message.
2556 """)
2557
2558 def test_parse_message_rfc822(self):
2559 eq = self.assertEqual
2560 msg = self._msgobj('msg_11.txt')
2561 eq(msg.get_content_type(), 'message/rfc822')
2562 payload = msg.get_payload()
2563 self.assertIsInstance(payload, list)
2564 eq(len(payload), 1)
2565 submsg = payload[0]
2566 self.assertIsInstance(submsg, Message)
2567 eq(submsg['subject'], 'An enclosed message')
2568 eq(submsg.get_payload(), 'Here is the body of the message.\n')
2569
2570 def test_dsn(self):
2571 eq = self.assertEqual
2572 # msg 16 is a Delivery Status Notification, see RFC 1894
2573 msg = self._msgobj('msg_16.txt')
2574 eq(msg.get_content_type(), 'multipart/report')
2575 self.assertTrue(msg.is_multipart())
2576 eq(len(msg.get_payload()), 3)
2577 # Subpart 1 is a text/plain, human readable section
2578 subpart = msg.get_payload(0)
2579 eq(subpart.get_content_type(), 'text/plain')
2580 eq(subpart.get_payload(), """\
2581 This report relates to a message you sent with the following header fields:
2582
2583 Message-id: <[email protected]>
2584 Date: Sun, 23 Sep 2001 20:10:55 -0700
2585 From: "Ian T. Henry" <[email protected]>
2586 To: SoCal Raves <[email protected]>
2587 Subject: [scr] yeah for Ians!!
2588
2589 Your message cannot be delivered to the following recipients:
2590
2591 Recipient address: [email protected]
2592 Reason: recipient reached disk quota
2593
2594 """)
2595 # Subpart 2 contains the machine parsable DSN information. It
2596 # consists of two blocks of headers, represented by two nested Message
2597 # objects.
2598 subpart = msg.get_payload(1)
2599 eq(subpart.get_content_type(), 'message/delivery-status')
2600 eq(len(subpart.get_payload()), 2)
2601 # message/delivery-status should treat each block as a bunch of
2602 # headers, i.e. a bunch of Message objects.
2603 dsn1 = subpart.get_payload(0)
2604 self.assertIsInstance(dsn1, Message)
2605 eq(dsn1['original-envelope-id'], '[email protected]')
2606 eq(dsn1.get_param('dns', header='reporting-mta'), '')
2607 # Try a missing one <wink>
2608 eq(dsn1.get_param('nsd', header='reporting-mta'), None)
2609 dsn2 = subpart.get_payload(1)
2610 self.assertIsInstance(dsn2, Message)
2611 eq(dsn2['action'], 'failed')
2612 eq(dsn2.get_params(header='original-recipient'),
2613 [('rfc822', ''), ('[email protected]', '')])
2614 eq(dsn2.get_param('rfc822', header='final-recipient'), '')
2615 # Subpart 3 is the original message
2616 subpart = msg.get_payload(2)
2617 eq(subpart.get_content_type(), 'message/rfc822')
2618 payload = subpart.get_payload()
2619 self.assertIsInstance(payload, list)
2620 eq(len(payload), 1)
2621 subsubpart = payload[0]
2622 self.assertIsInstance(subsubpart, Message)
2623 eq(subsubpart.get_content_type(), 'text/plain')
2624 eq(subsubpart['message-id'],
2625 '<[email protected]>')
2626
2627 def test_epilogue(self):
2628 eq = self.ndiffAssertEqual
2629 with openfile('msg_21.txt', encoding="utf-8") as fp:
2630 text = fp.read()
2631 msg = Message()
2632 msg['From'] = '[email protected]'
2633 msg['To'] = '[email protected]'
2634 msg['Subject'] = 'Test'
2635 msg.preamble = 'MIME message'
2636 msg.epilogue = 'End of MIME message\n'
2637 msg1 = MIMEText('One')
2638 msg2 = MIMEText('Two')
2639 msg.add_header('Content-Type', 'multipart/mixed', boundary='BOUNDARY')
2640 msg.attach(msg1)
2641 msg.attach(msg2)
2642 sfp = StringIO()
2643 g = Generator(sfp)
2644 g.flatten(msg)
2645 eq(sfp.getvalue(), text)
2646
2647 def test_no_nl_preamble(self):
2648 eq = self.ndiffAssertEqual
2649 msg = Message()
2650 msg['From'] = '[email protected]'
2651 msg['To'] = '[email protected]'
2652 msg['Subject'] = 'Test'
2653 msg.preamble = 'MIME message'
2654 msg.epilogue = ''
2655 msg1 = MIMEText('One')
2656 msg2 = MIMEText('Two')
2657 msg.add_header('Content-Type', 'multipart/mixed', boundary='BOUNDARY')
2658 msg.attach(msg1)
2659 msg.attach(msg2)
2660 eq(msg.as_string(), """\
2661 From: [email protected]
2662 To: [email protected]
2663 Subject: Test
2664 Content-Type: multipart/mixed; boundary="BOUNDARY"
2665
2666 MIME message
2667 --BOUNDARY
2668 Content-Type: text/plain; charset="us-ascii"
2669 MIME-Version: 1.0
2670 Content-Transfer-Encoding: 7bit
2671
2672 One
2673 --BOUNDARY
2674 Content-Type: text/plain; charset="us-ascii"
2675 MIME-Version: 1.0
2676 Content-Transfer-Encoding: 7bit
2677
2678 Two
2679 --BOUNDARY--
2680 """)
2681
2682 def test_default_type(self):
2683 eq = self.assertEqual
2684 with openfile('msg_30.txt', encoding="utf-8") as fp:
2685 msg = email.message_from_file(fp)
2686 container1 = msg.get_payload(0)
2687 eq(container1.get_default_type(), 'message/rfc822')
2688 eq(container1.get_content_type(), 'message/rfc822')
2689 container2 = msg.get_payload(1)
2690 eq(container2.get_default_type(), 'message/rfc822')
2691 eq(container2.get_content_type(), 'message/rfc822')
2692 container1a = container1.get_payload(0)
2693 eq(container1a.get_default_type(), 'text/plain')
2694 eq(container1a.get_content_type(), 'text/plain')
2695 container2a = container2.get_payload(0)
2696 eq(container2a.get_default_type(), 'text/plain')
2697 eq(container2a.get_content_type(), 'text/plain')
2698
2699 def test_default_type_with_explicit_container_type(self):
2700 eq = self.assertEqual
2701 with openfile('msg_28.txt', encoding="utf-8") as fp:
2702 msg = email.message_from_file(fp)
2703 container1 = msg.get_payload(0)
2704 eq(container1.get_default_type(), 'message/rfc822')
2705 eq(container1.get_content_type(), 'message/rfc822')
2706 container2 = msg.get_payload(1)
2707 eq(container2.get_default_type(), 'message/rfc822')
2708 eq(container2.get_content_type(), 'message/rfc822')
2709 container1a = container1.get_payload(0)
2710 eq(container1a.get_default_type(), 'text/plain')
2711 eq(container1a.get_content_type(), 'text/plain')
2712 container2a = container2.get_payload(0)
2713 eq(container2a.get_default_type(), 'text/plain')
2714 eq(container2a.get_content_type(), 'text/plain')
2715
2716 def test_default_type_non_parsed(self):
2717 eq = self.assertEqual
2718 neq = self.ndiffAssertEqual
2719 # Set up container
2720 container = MIMEMultipart('digest', 'BOUNDARY')
2721 container.epilogue = ''
2722 # Set up subparts
2723 subpart1a = MIMEText('message 1\n')
2724 subpart2a = MIMEText('message 2\n')
2725 subpart1 = MIMEMessage(subpart1a)
2726 subpart2 = MIMEMessage(subpart2a)
2727 container.attach(subpart1)
2728 container.attach(subpart2)
2729 eq(subpart1.get_content_type(), 'message/rfc822')
2730 eq(subpart1.get_default_type(), 'message/rfc822')
2731 eq(subpart2.get_content_type(), 'message/rfc822')
2732 eq(subpart2.get_default_type(), 'message/rfc822')
2733 neq(container.as_string(0), '''\
2734 Content-Type: multipart/digest; boundary="BOUNDARY"
2735 MIME-Version: 1.0
2736
2737 --BOUNDARY
2738 Content-Type: message/rfc822
2739 MIME-Version: 1.0
2740
2741 Content-Type: text/plain; charset="us-ascii"
2742 MIME-Version: 1.0
2743 Content-Transfer-Encoding: 7bit
2744
2745 message 1
2746
2747 --BOUNDARY
2748 Content-Type: message/rfc822
2749 MIME-Version: 1.0
2750
2751 Content-Type: text/plain; charset="us-ascii"
2752 MIME-Version: 1.0
2753 Content-Transfer-Encoding: 7bit
2754
2755 message 2
2756
2757 --BOUNDARY--
2758 ''')
2759 del subpart1['content-type']
2760 del subpart1['mime-version']
2761 del subpart2['content-type']
2762 del subpart2['mime-version']
2763 eq(subpart1.get_content_type(), 'message/rfc822')
2764 eq(subpart1.get_default_type(), 'message/rfc822')
2765 eq(subpart2.get_content_type(), 'message/rfc822')
2766 eq(subpart2.get_default_type(), 'message/rfc822')
2767 neq(container.as_string(0), '''\
2768 Content-Type: multipart/digest; boundary="BOUNDARY"
2769 MIME-Version: 1.0
2770
2771 --BOUNDARY
2772
2773 Content-Type: text/plain; charset="us-ascii"
2774 MIME-Version: 1.0
2775 Content-Transfer-Encoding: 7bit
2776
2777 message 1
2778
2779 --BOUNDARY
2780
2781 Content-Type: text/plain; charset="us-ascii"
2782 MIME-Version: 1.0
2783 Content-Transfer-Encoding: 7bit
2784
2785 message 2
2786
2787 --BOUNDARY--
2788 ''')
2789
2790 def test_mime_attachments_in_constructor(self):
2791 eq = self.assertEqual
2792 text1 = MIMEText('')
2793 text2 = MIMEText('')
2794 msg = MIMEMultipart(_subparts=(text1, text2))
2795 eq(len(msg.get_payload()), 2)
2796 eq(msg.get_payload(0), text1)
2797 eq(msg.get_payload(1), text2)
2798
2799 def test_default_multipart_constructor(self):
2800 msg = MIMEMultipart()
2801 self.assertTrue(msg.is_multipart())
2802
2803 def test_multipart_default_policy(self):
2804 msg = MIMEMultipart()
2805 msg['To'] = '[email protected]'
2806 msg['To'] = '[email protected]'
2807 self.assertEqual(msg.get_all('to'), ['[email protected]', '[email protected]'])
2808
2809 def test_multipart_custom_policy(self):
2810 msg = MIMEMultipart(policy=email.policy.default)
2811 msg['To'] = '[email protected]'
2812 with self.assertRaises(ValueError) as cm:
2813 msg['To'] = '[email protected]'
2814 self.assertEqual(str(cm.exception),
2815 'There may be at most 1 To headers in a message')
2816
2817
2818 # Test the NonMultipart class
2819 class TestNonMultipart(TestEmailBase):
2820 def test_nonmultipart_is_not_multipart(self):
2821 msg = MIMENonMultipart('text', 'plain')
2822 self.assertFalse(msg.is_multipart())
2823
2824 def test_attach_raises_exception(self):
2825 msg = Message()
2826 msg['Subject'] = 'subpart 1'
2827 r = MIMENonMultipart('text', 'plain')
2828 self.assertRaises(errors.MultipartConversionError, r.attach, msg)
2829
2830
2831 # A general test of parser->model->generator idempotency. IOW, read a message
2832 # in, parse it into a message object tree, then without touching the tree,
2833 # regenerate the plain text. The original text and the transformed text
2834 # should be identical. Note: that we ignore the Unix-From since that may
2835 # contain a changed date.
2836 class TestIdempotent(TestEmailBase):
2837
2838 linesep = '\n'
2839
2840 def _msgobj(self, filename):
2841 with openfile(filename, encoding="utf-8") as fp:
2842 data = fp.read()
2843 msg = email.message_from_string(data)
2844 return msg, data
2845
2846 def _idempotent(self, msg, text, unixfrom=False):
2847 eq = self.ndiffAssertEqual
2848 s = StringIO()
2849 g = Generator(s, maxheaderlen=0)
2850 g.flatten(msg, unixfrom=unixfrom)
2851 eq(text, s.getvalue())
2852
2853 def test_parse_text_message(self):
2854 eq = self.assertEqual
2855 msg, text = self._msgobj('msg_01.txt')
2856 eq(msg.get_content_type(), 'text/plain')
2857 eq(msg.get_content_maintype(), 'text')
2858 eq(msg.get_content_subtype(), 'plain')
2859 eq(msg.get_params()[1], ('charset', 'us-ascii'))
2860 eq(msg.get_param('charset'), 'us-ascii')
2861 eq(msg.preamble, None)
2862 eq(msg.epilogue, None)
2863 self._idempotent(msg, text)
2864
2865 def test_parse_untyped_message(self):
2866 eq = self.assertEqual
2867 msg, text = self._msgobj('msg_03.txt')
2868 eq(msg.get_content_type(), 'text/plain')
2869 eq(msg.get_params(), None)
2870 eq(msg.get_param('charset'), None)
2871 self._idempotent(msg, text)
2872
2873 def test_simple_multipart(self):
2874 msg, text = self._msgobj('msg_04.txt')
2875 self._idempotent(msg, text)
2876
2877 def test_MIME_digest(self):
2878 msg, text = self._msgobj('msg_02.txt')
2879 self._idempotent(msg, text)
2880
2881 def test_long_header(self):
2882 msg, text = self._msgobj('msg_27.txt')
2883 self._idempotent(msg, text)
2884
2885 def test_MIME_digest_with_part_headers(self):
2886 msg, text = self._msgobj('msg_28.txt')
2887 self._idempotent(msg, text)
2888
2889 def test_mixed_with_image(self):
2890 msg, text = self._msgobj('msg_06.txt')
2891 self._idempotent(msg, text)
2892
2893 def test_multipart_report(self):
2894 msg, text = self._msgobj('msg_05.txt')
2895 self._idempotent(msg, text)
2896
2897 def test_dsn(self):
2898 msg, text = self._msgobj('msg_16.txt')
2899 self._idempotent(msg, text)
2900
2901 def test_preamble_epilogue(self):
2902 msg, text = self._msgobj('msg_21.txt')
2903 self._idempotent(msg, text)
2904
2905 def test_multipart_one_part(self):
2906 msg, text = self._msgobj('msg_23.txt')
2907 self._idempotent(msg, text)
2908
2909 def test_multipart_no_parts(self):
2910 msg, text = self._msgobj('msg_24.txt')
2911 self._idempotent(msg, text)
2912
2913 def test_no_start_boundary(self):
2914 msg, text = self._msgobj('msg_31.txt')
2915 self._idempotent(msg, text)
2916
2917 def test_rfc2231_charset(self):
2918 msg, text = self._msgobj('msg_32.txt')
2919 self._idempotent(msg, text)
2920
2921 def test_more_rfc2231_parameters(self):
2922 msg, text = self._msgobj('msg_33.txt')
2923 self._idempotent(msg, text)
2924
2925 def test_text_plain_in_a_multipart_digest(self):
2926 msg, text = self._msgobj('msg_34.txt')
2927 self._idempotent(msg, text)
2928
2929 def test_nested_multipart_mixeds(self):
2930 msg, text = self._msgobj('msg_12a.txt')
2931 self._idempotent(msg, text)
2932
2933 def test_message_external_body_idempotent(self):
2934 msg, text = self._msgobj('msg_36.txt')
2935 self._idempotent(msg, text)
2936
2937 def test_message_delivery_status(self):
2938 msg, text = self._msgobj('msg_43.txt')
2939 self._idempotent(msg, text, unixfrom=True)
2940
2941 def test_message_signed_idempotent(self):
2942 msg, text = self._msgobj('msg_45.txt')
2943 self._idempotent(msg, text)
2944
2945 def test_content_type(self):
2946 eq = self.assertEqual
2947 # Get a message object and reset the seek pointer for other tests
2948 msg, text = self._msgobj('msg_05.txt')
2949 eq(msg.get_content_type(), 'multipart/report')
2950 # Test the Content-Type: parameters
2951 params = {}
2952 for pk, pv in msg.get_params():
2953 params[pk] = pv
2954 eq(params['report-type'], 'delivery-status')
2955 eq(params['boundary'], 'D1690A7AC1.996856090/mail.example.com')
2956 eq(msg.preamble, 'This is a MIME-encapsulated message.' + self.linesep)
2957 eq(msg.epilogue, self.linesep)
2958 eq(len(msg.get_payload()), 3)
2959 # Make sure the subparts are what we expect
2960 msg1 = msg.get_payload(0)
2961 eq(msg1.get_content_type(), 'text/plain')
2962 eq(msg1.get_payload(), 'Yadda yadda yadda' + self.linesep)
2963 msg2 = msg.get_payload(1)
2964 eq(msg2.get_content_type(), 'text/plain')
2965 eq(msg2.get_payload(), 'Yadda yadda yadda' + self.linesep)
2966 msg3 = msg.get_payload(2)
2967 eq(msg3.get_content_type(), 'message/rfc822')
2968 self.assertIsInstance(msg3, Message)
2969 payload = msg3.get_payload()
2970 self.assertIsInstance(payload, list)
2971 eq(len(payload), 1)
2972 msg4 = payload[0]
2973 self.assertIsInstance(msg4, Message)
2974 eq(msg4.get_payload(), 'Yadda yadda yadda' + self.linesep)
2975
2976 def test_parser(self):
2977 eq = self.assertEqual
2978 msg, text = self._msgobj('msg_06.txt')
2979 # Check some of the outer headers
2980 eq(msg.get_content_type(), 'message/rfc822')
2981 # Make sure the payload is a list of exactly one sub-Message, and that
2982 # that submessage has a type of text/plain
2983 payload = msg.get_payload()
2984 self.assertIsInstance(payload, list)
2985 eq(len(payload), 1)
2986 msg1 = payload[0]
2987 self.assertIsInstance(msg1, Message)
2988 eq(msg1.get_content_type(), 'text/plain')
2989 self.assertIsInstance(msg1.get_payload(), str)
2990 eq(msg1.get_payload(), self.linesep)
2991
2992
2993
2994 # Test various other bits of the package's functionality
2995 class TestMiscellaneous(TestEmailBase):
2996 def test_message_from_string(self):
2997 with openfile('msg_01.txt', encoding="utf-8") as fp:
2998 text = fp.read()
2999 msg = email.message_from_string(text)
3000 s = StringIO()
3001 # Don't wrap/continue long headers since we're trying to test
3002 # idempotency.
3003 g = Generator(s, maxheaderlen=0)
3004 g.flatten(msg)
3005 self.assertEqual(text, s.getvalue())
3006
3007 def test_message_from_file(self):
3008 with openfile('msg_01.txt', encoding="utf-8") as fp:
3009 text = fp.read()
3010 fp.seek(0)
3011 msg = email.message_from_file(fp)
3012 s = StringIO()
3013 # Don't wrap/continue long headers since we're trying to test
3014 # idempotency.
3015 g = Generator(s, maxheaderlen=0)
3016 g.flatten(msg)
3017 self.assertEqual(text, s.getvalue())
3018
3019 def test_message_from_string_with_class(self):
3020 with openfile('msg_01.txt', encoding="utf-8") as fp:
3021 text = fp.read()
3022
3023 # Create a subclass
3024 class MyMessage(Message):
3025 pass
3026
3027 msg = email.message_from_string(text, MyMessage)
3028 self.assertIsInstance(msg, MyMessage)
3029 # Try something more complicated
3030 with openfile('msg_02.txt', encoding="utf-8") as fp:
3031 text = fp.read()
3032 msg = email.message_from_string(text, MyMessage)
3033 for subpart in msg.walk():
3034 self.assertIsInstance(subpart, MyMessage)
3035
3036 def test_message_from_file_with_class(self):
3037 # Create a subclass
3038 class MyMessage(Message):
3039 pass
3040
3041 with openfile('msg_01.txt', encoding="utf-8") as fp:
3042 msg = email.message_from_file(fp, MyMessage)
3043 self.assertIsInstance(msg, MyMessage)
3044 # Try something more complicated
3045 with openfile('msg_02.txt', encoding="utf-8") as fp:
3046 msg = email.message_from_file(fp, MyMessage)
3047 for subpart in msg.walk():
3048 self.assertIsInstance(subpart, MyMessage)
3049
3050 def test_custom_message_does_not_require_arguments(self):
3051 class MyMessage(Message):
3052 def __init__(self):
3053 super().__init__()
3054 msg = self._str_msg("Subject: test\n\ntest", MyMessage)
3055 self.assertIsInstance(msg, MyMessage)
3056
3057 def test__all__(self):
3058 module = __import__('email')
3059 self.assertEqual(sorted(module.__all__), [
3060 'base64mime', 'charset', 'encoders', 'errors', 'feedparser',
3061 'generator', 'header', 'iterators', 'message',
3062 'message_from_binary_file', 'message_from_bytes',
3063 'message_from_file', 'message_from_string', 'mime', 'parser',
3064 'quoprimime', 'utils',
3065 ])
3066
3067 def test_formatdate(self):
3068 now = time.time()
3069 self.assertEqual(utils.parsedate(utils.formatdate(now))[:6],
3070 time.gmtime(now)[:6])
3071
3072 def test_formatdate_localtime(self):
3073 now = time.time()
3074 self.assertEqual(
3075 utils.parsedate(utils.formatdate(now, localtime=True))[:6],
3076 time.localtime(now)[:6])
3077
3078 def test_formatdate_usegmt(self):
3079 now = time.time()
3080 self.assertEqual(
3081 utils.formatdate(now, localtime=False),
3082 time.strftime('%a, %d %b %Y %H:%M:%S -0000', time.gmtime(now)))
3083 self.assertEqual(
3084 utils.formatdate(now, localtime=False, usegmt=True),
3085 time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime(now)))
3086
3087 # parsedate and parsedate_tz will become deprecated interfaces someday
3088 def test_parsedate_returns_None_for_invalid_strings(self):
3089 # See also test_parsedate_to_datetime_with_invalid_raises_valueerror
3090 # in test_utils.
3091 invalid_dates = [
3092 '',
3093 ' ',
3094 '0',
3095 'A Complete Waste of Time',
3096 'Wed, 3 Apr 2002 12.34.56.78+0800',
3097 '17 June , 2022',
3098 'Friday, -Nov-82 16:14:55 EST',
3099 'Friday, Nov--82 16:14:55 EST',
3100 'Friday, 19-Nov- 16:14:55 EST',
3101 ]
3102 for dtstr in invalid_dates:
3103 with self.subTest(dtstr=dtstr):
3104 self.assertIsNone(utils.parsedate(dtstr))
3105 self.assertIsNone(utils.parsedate_tz(dtstr))
3106 # Not a part of the spec but, but this has historically worked:
3107 self.assertIsNone(utils.parsedate(None))
3108 self.assertIsNone(utils.parsedate_tz(None))
3109
3110 def test_parsedate_compact(self):
3111 self.assertEqual(utils.parsedate_tz('Wed, 3 Apr 2002 14:58:26 +0800'),
3112 (2002, 4, 3, 14, 58, 26, 0, 1, -1, 28800))
3113 # The FWS after the comma is optional
3114 self.assertEqual(utils.parsedate_tz('Wed,3 Apr 2002 14:58:26 +0800'),
3115 (2002, 4, 3, 14, 58, 26, 0, 1, -1, 28800))
3116 # The comma is optional
3117 self.assertEqual(utils.parsedate_tz('Wed 3 Apr 2002 14:58:26 +0800'),
3118 (2002, 4, 3, 14, 58, 26, 0, 1, -1, 28800))
3119
3120 def test_parsedate_no_dayofweek(self):
3121 eq = self.assertEqual
3122 eq(utils.parsedate_tz('5 Feb 2003 13:47:26 -0800'),
3123 (2003, 2, 5, 13, 47, 26, 0, 1, -1, -28800))
3124 eq(utils.parsedate_tz('February 5, 2003 13:47:26 -0800'),
3125 (2003, 2, 5, 13, 47, 26, 0, 1, -1, -28800))
3126
3127 def test_parsedate_no_space_before_positive_offset(self):
3128 self.assertEqual(utils.parsedate_tz('Wed, 3 Apr 2002 14:58:26+0800'),
3129 (2002, 4, 3, 14, 58, 26, 0, 1, -1, 28800))
3130
3131 def test_parsedate_no_space_before_negative_offset(self):
3132 # Issue 1155362: we already handled '+' for this case.
3133 self.assertEqual(utils.parsedate_tz('Wed, 3 Apr 2002 14:58:26-0800'),
3134 (2002, 4, 3, 14, 58, 26, 0, 1, -1, -28800))
3135
3136 def test_parsedate_accepts_time_with_dots(self):
3137 eq = self.assertEqual
3138 eq(utils.parsedate_tz('5 Feb 2003 13.47.26 -0800'),
3139 (2003, 2, 5, 13, 47, 26, 0, 1, -1, -28800))
3140 eq(utils.parsedate_tz('5 Feb 2003 13.47 -0800'),
3141 (2003, 2, 5, 13, 47, 0, 0, 1, -1, -28800))
3142
3143 def test_parsedate_rfc_850(self):
3144 self.assertEqual(utils.parsedate_tz('Friday, 19-Nov-82 16:14:55 EST'),
3145 (1982, 11, 19, 16, 14, 55, 0, 1, -1, -18000))
3146
3147 def test_parsedate_no_seconds(self):
3148 self.assertEqual(utils.parsedate_tz('Wed, 3 Apr 2002 14:58 +0800'),
3149 (2002, 4, 3, 14, 58, 0, 0, 1, -1, 28800))
3150
3151 def test_parsedate_dot_time_delimiter(self):
3152 self.assertEqual(utils.parsedate_tz('Wed, 3 Apr 2002 14.58.26 +0800'),
3153 (2002, 4, 3, 14, 58, 26, 0, 1, -1, 28800))
3154 self.assertEqual(utils.parsedate_tz('Wed, 3 Apr 2002 14.58 +0800'),
3155 (2002, 4, 3, 14, 58, 0, 0, 1, -1, 28800))
3156
3157 def test_parsedate_acceptable_to_time_functions(self):
3158 eq = self.assertEqual
3159 timetup = utils.parsedate('5 Feb 2003 13:47:26 -0800')
3160 t = int(time.mktime(timetup))
3161 eq(time.localtime(t)[:6], timetup[:6])
3162 eq(int(time.strftime('%Y', timetup)), 2003)
3163 timetup = utils.parsedate_tz('5 Feb 2003 13:47:26 -0800')
3164 t = int(time.mktime(timetup[:9]))
3165 eq(time.localtime(t)[:6], timetup[:6])
3166 eq(int(time.strftime('%Y', timetup[:9])), 2003)
3167
3168 def test_mktime_tz(self):
3169 self.assertEqual(utils.mktime_tz((1970, 1, 1, 0, 0, 0,
3170 -1, -1, -1, 0)), 0)
3171 self.assertEqual(utils.mktime_tz((1970, 1, 1, 0, 0, 0,
3172 -1, -1, -1, 1234)), -1234)
3173
3174 def test_parsedate_y2k(self):
3175 """Test for parsing a date with a two-digit year.
3176
3177 Parsing a date with a two-digit year should return the correct
3178 four-digit year. RFC822 allows two-digit years, but RFC2822 (which
3179 obsoletes RFC822) requires four-digit years.
3180
3181 """
3182 self.assertEqual(utils.parsedate_tz('25 Feb 03 13:47:26 -0800'),
3183 utils.parsedate_tz('25 Feb 2003 13:47:26 -0800'))
3184 self.assertEqual(utils.parsedate_tz('25 Feb 71 13:47:26 -0800'),
3185 utils.parsedate_tz('25 Feb 1971 13:47:26 -0800'))
3186
3187 def test_parseaddr_empty(self):
3188 self.assertEqual(utils.parseaddr('<>'), ('', ''))
3189 self.assertEqual(utils.formataddr(utils.parseaddr('<>')), '')
3190
3191 def test_parseaddr_multiple_domains(self):
3192 self.assertEqual(
3193 utils.parseaddr('a@b@c'),
3194 ('', '')
3195 )
3196 self.assertEqual(
3197 utils.parseaddr('[email protected]@c'),
3198 ('', '')
3199 )
3200 self.assertEqual(
3201 utils.parseaddr('[email protected]@c'),
3202 ('', '')
3203 )
3204
3205 def test_noquote_dump(self):
3206 self.assertEqual(
3207 utils.formataddr(('A Silly Person', '[email protected]')),
3208 'A Silly Person <[email protected]>')
3209
3210 def test_escape_dump(self):
3211 self.assertEqual(
3212 utils.formataddr(('A (Very) Silly Person', '[email protected]')),
3213 r'"A (Very) Silly Person" <[email protected]>')
3214 self.assertEqual(
3215 utils.parseaddr(r'"A \(Very\) Silly Person" <[email protected]>'),
3216 ('A (Very) Silly Person', '[email protected]'))
3217 a = r'A \(Special\) Person'
3218 b = '[email protected]'
3219 self.assertEqual(utils.parseaddr(utils.formataddr((a, b))), (a, b))
3220
3221 def test_escape_backslashes(self):
3222 self.assertEqual(
3223 utils.formataddr((r'Arthur \Backslash\ Foobar', '[email protected]')),
3224 r'"Arthur \\Backslash\\ Foobar" <[email protected]>')
3225 a = r'Arthur \Backslash\ Foobar'
3226 b = '[email protected]'
3227 self.assertEqual(utils.parseaddr(utils.formataddr((a, b))), (a, b))
3228
3229 def test_quotes_unicode_names(self):
3230 # issue 1690608. email.utils.formataddr() should be rfc2047 aware.
3231 name = "H\u00e4ns W\u00fcrst"
3232 addr = '[email protected]'
3233 utf8_base64 = "=?utf-8?b?SMOkbnMgV8O8cnN0?= <[email protected]>"
3234 latin1_quopri = "=?iso-8859-1?q?H=E4ns_W=FCrst?= <[email protected]>"
3235 self.assertEqual(utils.formataddr((name, addr)), utf8_base64)
3236 self.assertEqual(utils.formataddr((name, addr), 'iso-8859-1'),
3237 latin1_quopri)
3238
3239 def test_accepts_any_charset_like_object(self):
3240 # issue 1690608. email.utils.formataddr() should be rfc2047 aware.
3241 name = "H\u00e4ns W\u00fcrst"
3242 addr = '[email protected]'
3243 utf8_base64 = "=?utf-8?b?SMOkbnMgV8O8cnN0?= <[email protected]>"
3244 foobar = "FOOBAR"
3245 class CharsetMock:
3246 def header_encode(self, string):
3247 return foobar
3248 mock = CharsetMock()
3249 mock_expected = "%s <%s>" % (foobar, addr)
3250 self.assertEqual(utils.formataddr((name, addr), mock), mock_expected)
3251 self.assertEqual(utils.formataddr((name, addr), Charset('utf-8')),
3252 utf8_base64)
3253
3254 def test_invalid_charset_like_object_raises_error(self):
3255 # issue 1690608. email.utils.formataddr() should be rfc2047 aware.
3256 name = "H\u00e4ns W\u00fcrst"
3257 addr = '[email protected]'
3258 # An object without a header_encode method:
3259 bad_charset = object()
3260 self.assertRaises(AttributeError, utils.formataddr, (name, addr),
3261 bad_charset)
3262
3263 def test_unicode_address_raises_error(self):
3264 # issue 1690608. email.utils.formataddr() should be rfc2047 aware.
3265 addr = 'pers\u00f6[email protected]'
3266 self.assertRaises(UnicodeError, utils.formataddr, (None, addr))
3267 self.assertRaises(UnicodeError, utils.formataddr, ("Name", addr))
3268
3269 def test_name_with_dot(self):
3270 x = 'John X. Doe <[email protected]>'
3271 y = '"John X. Doe" <[email protected]>'
3272 a, b = ('John X. Doe', '[email protected]')
3273 self.assertEqual(utils.parseaddr(x), (a, b))
3274 self.assertEqual(utils.parseaddr(y), (a, b))
3275 # formataddr() quotes the name if there's a dot in it
3276 self.assertEqual(utils.formataddr((a, b)), y)
3277
3278 def test_parseaddr_preserves_quoted_pairs_in_addresses(self):
3279 # issue 10005. Note that in the third test the second pair of
3280 # backslashes is not actually a quoted pair because it is not inside a
3281 # comment or quoted string: the address being parsed has a quoted
3282 # string containing a quoted backslash, followed by 'example' and two
3283 # backslashes, followed by another quoted string containing a space and
3284 # the word 'example'. parseaddr copies those two backslashes
3285 # literally. Per rfc5322 this is not technically correct since a \ may
3286 # not appear in an address outside of a quoted string. It is probably
3287 # a sensible Postel interpretation, though.
3288 eq = self.assertEqual
3289 eq(utils.parseaddr('""example" example"@example.com'),
3290 ('', '""example" example"@example.com'))
3291 eq(utils.parseaddr('"\\"example\\" example"@example.com'),
3292 ('', '"\\"example\\" example"@example.com'))
3293 eq(utils.parseaddr('"\\\\"example\\\\" example"@example.com'),
3294 ('', '"\\\\"example\\\\" example"@example.com'))
3295
3296 def test_parseaddr_preserves_spaces_in_local_part(self):
3297 # issue 9286. A normal RFC5322 local part should not contain any
3298 # folding white space, but legacy local parts can (they are a sequence
3299 # of atoms, not dotatoms). On the other hand we strip whitespace from
3300 # before the @ and around dots, on the assumption that the whitespace
3301 # around the punctuation is a mistake in what would otherwise be
3302 # an RFC5322 local part. Leading whitespace is, usual, stripped as well.
3303 self.assertEqual(('', "merwok [email protected]"),
3304 utils.parseaddr("merwok [email protected]"))
3305 self.assertEqual(('', "merwok [email protected]"),
3306 utils.parseaddr("merwok [email protected]"))
3307 self.assertEqual(('', "merwok [email protected]"),
3308 utils.parseaddr(" merwok wok @xample.com"))
3309 self.assertEqual(('', 'merwok"wok" [email protected]'),
3310 utils.parseaddr('merwok"wok" [email protected]'))
3311 self.assertEqual(('', '[email protected]'),
3312 utils.parseaddr('merwok. wok . [email protected]'))
3313
3314 def test_formataddr_does_not_quote_parens_in_quoted_string(self):
3315 addr = ("'[email protected]' ([email protected])",
3316 '[email protected]')
3317 addrstr = ('"\'[email protected]\' '
3318 '([email protected])" <[email protected]>')
3319 self.assertEqual(utils.parseaddr(addrstr), addr)
3320 self.assertEqual(utils.formataddr(addr), addrstr)
3321
3322
3323 def test_multiline_from_comment(self):
3324 x = """\
3325 Foo
3326 \tBar <[email protected]>"""
3327 self.assertEqual(utils.parseaddr(x), ('Foo Bar', '[email protected]'))
3328
3329 def test_quote_dump(self):
3330 self.assertEqual(
3331 utils.formataddr(('A Silly; Person', '[email protected]')),
3332 r'"A Silly; Person" <[email protected]>')
3333
3334 def test_charset_richcomparisons(self):
3335 eq = self.assertEqual
3336 ne = self.assertNotEqual
3337 cset1 = Charset()
3338 cset2 = Charset()
3339 eq(cset1, 'us-ascii')
3340 eq(cset1, 'US-ASCII')
3341 eq(cset1, 'Us-AsCiI')
3342 eq('us-ascii', cset1)
3343 eq('US-ASCII', cset1)
3344 eq('Us-AsCiI', cset1)
3345 ne(cset1, 'usascii')
3346 ne(cset1, 'USASCII')
3347 ne(cset1, 'UsAsCiI')
3348 ne('usascii', cset1)
3349 ne('USASCII', cset1)
3350 ne('UsAsCiI', cset1)
3351 eq(cset1, cset2)
3352 eq(cset2, cset1)
3353
3354 def test_getaddresses(self):
3355 eq = self.assertEqual
3356 eq(utils.getaddresses(['[email protected] (Al Person)',
3357 'Bud Person <[email protected]>']),
3358 [('Al Person', '[email protected]'),
3359 ('Bud Person', '[email protected]')])
3360
3361 def test_getaddresses_comma_in_name(self):
3362 """GH-106669 regression test."""
3363 self.assertEqual(
3364 utils.getaddresses(
3365 [
3366 '"Bud, Person" <[email protected]>',
3367 '[email protected] (Al Person)',
3368 '"Mariusz Felisiak" <[email protected]>',
3369 ]
3370 ),
3371 [
3372 ('Bud, Person', '[email protected]'),
3373 ('Al Person', '[email protected]'),
3374 ('Mariusz Felisiak', '[email protected]'),
3375 ],
3376 )
3377
3378 def test_parsing_errors(self):
3379 """Test for parsing errors from CVE-2023-27043 and CVE-2019-16056"""
3380 alice = '[email protected]'
3381 bob = '[email protected]'
3382 empty = ('', '')
3383
3384 # Test utils.getaddresses() and utils.parseaddr() on malformed email
3385 # addresses: default behavior (strict=True) rejects malformed address,
3386 # and strict=False which tolerates malformed address.
3387 for invalid_separator, expected_non_strict in (
3388 ('(', [(f'<{bob}>', alice)]),
3389 (')', [('', alice), empty, ('', bob)]),
3390 ('<', [('', alice), empty, ('', bob), empty]),
3391 ('>', [('', alice), empty, ('', bob)]),
3392 ('[', [('', f'{alice}[<{bob}>]')]),
3393 (']', [('', alice), empty, ('', bob)]),
3394 ('@', [empty, empty, ('', bob)]),
3395 (';', [('', alice), empty, ('', bob)]),
3396 (':', [('', alice), ('', bob)]),
3397 ('.', [('', alice + '.'), ('', bob)]),
3398 ('"', [('', alice), ('', f'<{bob}>')]),
3399 ):
3400 address = f'{alice}{invalid_separator}<{bob}>'
3401 with self.subTest(address=address):
3402 self.assertEqual(utils.getaddresses([address]),
3403 [empty])
3404 self.assertEqual(utils.getaddresses([address], strict=False),
3405 expected_non_strict)
3406
3407 self.assertEqual(utils.parseaddr([address]),
3408 empty)
3409 self.assertEqual(utils.parseaddr([address], strict=False),
3410 ('', address))
3411
3412 # Comma (',') is treated differently depending on strict parameter.
3413 # Comma without quotes.
3414 address = f'{alice},<{bob}>'
3415 self.assertEqual(utils.getaddresses([address]),
3416 [('', alice), ('', bob)])
3417 self.assertEqual(utils.getaddresses([address], strict=False),
3418 [('', alice), ('', bob)])
3419 self.assertEqual(utils.parseaddr([address]),
3420 empty)
3421 self.assertEqual(utils.parseaddr([address], strict=False),
3422 ('', address))
3423
3424 # Real name between quotes containing comma.
3425 address = '"Alice, [email protected]" <[email protected]>'
3426 expected_strict = ('Alice, [email protected]', '[email protected]')
3427 self.assertEqual(utils.getaddresses([address]), [expected_strict])
3428 self.assertEqual(utils.getaddresses([address], strict=False), [expected_strict])
3429 self.assertEqual(utils.parseaddr([address]), expected_strict)
3430 self.assertEqual(utils.parseaddr([address], strict=False),
3431 ('', address))
3432
3433 # Valid parenthesis in comments.
3434 address = '[email protected] (Alice)'
3435 expected_strict = ('Alice', '[email protected]')
3436 self.assertEqual(utils.getaddresses([address]), [expected_strict])
3437 self.assertEqual(utils.getaddresses([address], strict=False), [expected_strict])
3438 self.assertEqual(utils.parseaddr([address]), expected_strict)
3439 self.assertEqual(utils.parseaddr([address], strict=False),
3440 ('', address))
3441
3442 # Invalid parenthesis in comments.
3443 address = '[email protected] )Alice('
3444 self.assertEqual(utils.getaddresses([address]), [empty])
3445 self.assertEqual(utils.getaddresses([address], strict=False),
3446 [('', '[email protected]'), ('', ''), ('', 'Alice')])
3447 self.assertEqual(utils.parseaddr([address]), empty)
3448 self.assertEqual(utils.parseaddr([address], strict=False),
3449 ('', address))
3450
3451 # Two addresses with quotes separated by comma.
3452 address = '"Jane Doe" <[email protected]>, "John Doe" <[email protected]>'
3453 self.assertEqual(utils.getaddresses([address]),
3454 [('Jane Doe', '[email protected]'),
3455 ('John Doe', '[email protected]')])
3456 self.assertEqual(utils.getaddresses([address], strict=False),
3457 [('Jane Doe', '[email protected]'),
3458 ('John Doe', '[email protected]')])
3459 self.assertEqual(utils.parseaddr([address]), empty)
3460 self.assertEqual(utils.parseaddr([address], strict=False),
3461 ('', address))
3462
3463 # Test email.utils.supports_strict_parsing attribute
3464 self.assertEqual(email.utils.supports_strict_parsing, True)
3465
3466 def test_getaddresses_nasty(self):
3467 for addresses, expected in (
3468 (['"Sürname, Firstname" <[email protected]>'],
3469 [('Sürname, Firstname', '[email protected]')]),
3470
3471 (['foo: ;'],
3472 [('', '')]),
3473
3474 (['foo: ;', '"Jason R. Mastaler" <[email protected]>'],
3475 [('', ''), ('Jason R. Mastaler', '[email protected]')]),
3476
3477 ([r'Pete(A nice \) chap) <pete(his account)@silly.test(his host)>'],
3478 [('Pete (A nice ) chap his account his host)', '[email protected]')]),
3479
3480 (['(Empty list)(start)Undisclosed recipients :(nobody(I know))'],
3481 [('', '')]),
3482
3483 (['Mary <@machine.tld:[email protected]>, , jdoe@test . example'],
3484 [('Mary', '[email protected]'), ('', ''), ('', '[email protected]')]),
3485
3486 (['John Doe <jdoe@machine(comment). example>'],
3487 [('John Doe (comment)', '[email protected]')]),
3488
3489 (['"Mary Smith: Personal Account" <[email protected]>'],
3490 [('Mary Smith: Personal Account', '[email protected]')]),
3491
3492 (['Undisclosed recipients:;'],
3493 [('', '')]),
3494
3495 ([r'<[email protected]>, "Giant; \"Big\" Box" <[email protected]>'],
3496 [('', '[email protected]'), ('Giant; "Big" Box', '[email protected]')]),
3497 ):
3498 with self.subTest(addresses=addresses):
3499 self.assertEqual(utils.getaddresses(addresses),
3500 expected)
3501 self.assertEqual(utils.getaddresses(addresses, strict=False),
3502 expected)
3503
3504 addresses = ['[]*-- =~$']
3505 self.assertEqual(utils.getaddresses(addresses),
3506 [('', '')])
3507 self.assertEqual(utils.getaddresses(addresses, strict=False),
3508 [('', ''), ('', ''), ('', '*--')])
3509
3510 def test_getaddresses_embedded_comment(self):
3511 """Test proper handling of a nested comment"""
3512 eq = self.assertEqual
3513 addrs = utils.getaddresses(['User ((nested comment)) <[email protected]>'])
3514 eq(addrs[0][1], '[email protected]')
3515
3516 def test_getaddresses_header_obj(self):
3517 """Test the handling of a Header object."""
3518 addrs = utils.getaddresses([Header('Al Person <[email protected]>')])
3519 self.assertEqual(addrs[0][1], '[email protected]')
3520
3521 @threading_helper.requires_working_threading()
3522 @support.requires_resource('cpu')
3523 def test_make_msgid_collisions(self):
3524 # Test make_msgid uniqueness, even with multiple threads
3525 class MsgidsThread(Thread):
3526 def run(self):
3527 # generate msgids for 3 seconds
3528 self.msgids = []
3529 append = self.msgids.append
3530 make_msgid = utils.make_msgid
3531 clock = time.monotonic
3532 tfin = clock() + 3.0
3533 while clock() < tfin:
3534 append(make_msgid(domain='testdomain-string'))
3535
3536 threads = [MsgidsThread() for i in range(5)]
3537 with threading_helper.start_threads(threads):
3538 pass
3539 all_ids = sum([t.msgids for t in threads], [])
3540 self.assertEqual(len(set(all_ids)), len(all_ids))
3541
3542 def test_utils_quote_unquote(self):
3543 eq = self.assertEqual
3544 msg = Message()
3545 msg.add_header('content-disposition', 'attachment',
3546 filename='foo\\wacky"name')
3547 eq(msg.get_filename(), 'foo\\wacky"name')
3548
3549 def test_get_body_encoding_with_bogus_charset(self):
3550 charset = Charset('not a charset')
3551 self.assertEqual(charset.get_body_encoding(), 'base64')
3552
3553 def test_get_body_encoding_with_uppercase_charset(self):
3554 eq = self.assertEqual
3555 msg = Message()
3556 msg['Content-Type'] = 'text/plain; charset=UTF-8'
3557 eq(msg['content-type'], 'text/plain; charset=UTF-8')
3558 charsets = msg.get_charsets()
3559 eq(len(charsets), 1)
3560 eq(charsets[0], 'utf-8')
3561 charset = Charset(charsets[0])
3562 eq(charset.get_body_encoding(), 'base64')
3563 msg.set_payload(b'hello world', charset=charset)
3564 eq(msg.get_payload(), 'aGVsbG8gd29ybGQ=\n')
3565 eq(msg.get_payload(decode=True), b'hello world')
3566 eq(msg['content-transfer-encoding'], 'base64')
3567 # Try another one
3568 msg = Message()
3569 msg['Content-Type'] = 'text/plain; charset="US-ASCII"'
3570 charsets = msg.get_charsets()
3571 eq(len(charsets), 1)
3572 eq(charsets[0], 'us-ascii')
3573 charset = Charset(charsets[0])
3574 eq(charset.get_body_encoding(), encoders.encode_7or8bit)
3575 msg.set_payload('hello world', charset=charset)
3576 eq(msg.get_payload(), 'hello world')
3577 eq(msg['content-transfer-encoding'], '7bit')
3578
3579 def test_charsets_case_insensitive(self):
3580 lc = Charset('us-ascii')
3581 uc = Charset('US-ASCII')
3582 self.assertEqual(lc.get_body_encoding(), uc.get_body_encoding())
3583
3584 def test_partial_falls_inside_message_delivery_status(self):
3585 eq = self.ndiffAssertEqual
3586 # The Parser interface provides chunks of data to FeedParser in 8192
3587 # byte gulps. SF bug #1076485 found one of those chunks inside
3588 # message/delivery-status header block, which triggered an
3589 # unreadline() of NeedMoreData.
3590 msg = self._msgobj('msg_43.txt')
3591 sfp = StringIO()
3592 iterators._structure(msg, sfp)
3593 eq(sfp.getvalue(), """\
3594 multipart/report
3595 text/plain
3596 message/delivery-status
3597 text/plain
3598 text/plain
3599 text/plain
3600 text/plain
3601 text/plain
3602 text/plain
3603 text/plain
3604 text/plain
3605 text/plain
3606 text/plain
3607 text/plain
3608 text/plain
3609 text/plain
3610 text/plain
3611 text/plain
3612 text/plain
3613 text/plain
3614 text/plain
3615 text/plain
3616 text/plain
3617 text/plain
3618 text/plain
3619 text/plain
3620 text/plain
3621 text/plain
3622 text/plain
3623 text/rfc822-headers
3624 """)
3625
3626 def test_make_msgid_domain(self):
3627 self.assertEqual(
3628 email.utils.make_msgid(domain='testdomain-string')[-19:],
3629 '@testdomain-string>')
3630
3631 def test_make_msgid_idstring(self):
3632 self.assertEqual(
3633 email.utils.make_msgid(idstring='test-idstring',
3634 domain='testdomain-string')[-33:],
3635 '.test-idstring@testdomain-string>')
3636
3637 def test_make_msgid_default_domain(self):
3638 with patch('socket.getfqdn') as mock_getfqdn:
3639 mock_getfqdn.return_value = domain = 'pythontest.example.com'
3640 self.assertTrue(
3641 email.utils.make_msgid().endswith(
3642 '@' + domain + '>'))
3643
3644 def test_Generator_linend(self):
3645 # Issue 14645.
3646 with openfile('msg_26.txt', encoding="utf-8", newline='\n') as f:
3647 msgtxt = f.read()
3648 msgtxt_nl = msgtxt.replace('\r\n', '\n')
3649 msg = email.message_from_string(msgtxt)
3650 s = StringIO()
3651 g = email.generator.Generator(s)
3652 g.flatten(msg)
3653 self.assertEqual(s.getvalue(), msgtxt_nl)
3654
3655 def test_BytesGenerator_linend(self):
3656 # Issue 14645.
3657 with openfile('msg_26.txt', encoding="utf-8", newline='\n') as f:
3658 msgtxt = f.read()
3659 msgtxt_nl = msgtxt.replace('\r\n', '\n')
3660 msg = email.message_from_string(msgtxt_nl)
3661 s = BytesIO()
3662 g = email.generator.BytesGenerator(s)
3663 g.flatten(msg, linesep='\r\n')
3664 self.assertEqual(s.getvalue().decode('ascii'), msgtxt)
3665
3666 def test_BytesGenerator_linend_with_non_ascii(self):
3667 # Issue 14645.
3668 with openfile('msg_26.txt', 'rb') as f:
3669 msgtxt = f.read()
3670 msgtxt = msgtxt.replace(b'with attachment', b'fo\xf6')
3671 msgtxt_nl = msgtxt.replace(b'\r\n', b'\n')
3672 msg = email.message_from_bytes(msgtxt_nl)
3673 s = BytesIO()
3674 g = email.generator.BytesGenerator(s)
3675 g.flatten(msg, linesep='\r\n')
3676 self.assertEqual(s.getvalue(), msgtxt)
3677
3678 def test_mime_classes_policy_argument(self):
3679 with openfile('sndhdr.au', 'rb') as fp:
3680 audiodata = fp.read()
3681 with openfile('python.gif', 'rb') as fp:
3682 bindata = fp.read()
3683 classes = [
3684 (MIMEApplication, ('',)),
3685 (MIMEAudio, (audiodata,)),
3686 (MIMEImage, (bindata,)),
3687 (MIMEMessage, (Message(),)),
3688 (MIMENonMultipart, ('multipart', 'mixed')),
3689 (MIMEText, ('',)),
3690 ]
3691 for cls, constructor in classes:
3692 with self.subTest(cls=cls.__name__, policy='compat32'):
3693 m = cls(*constructor)
3694 self.assertIs(m.policy, email.policy.compat32)
3695 with self.subTest(cls=cls.__name__, policy='default'):
3696 m = cls(*constructor, policy=email.policy.default)
3697 self.assertIs(m.policy, email.policy.default)
3698
3699 def test_iter_escaped_chars(self):
3700 self.assertEqual(list(utils._iter_escaped_chars(r'a\\b\"c\\"d')),
3701 [(0, 'a'),
3702 (2, '\\\\'),
3703 (3, 'b'),
3704 (5, '\\"'),
3705 (6, 'c'),
3706 (8, '\\\\'),
3707 (9, '"'),
3708 (10, 'd')])
3709 self.assertEqual(list(utils._iter_escaped_chars('a\\')),
3710 [(0, 'a'), (1, '\\')])
3711
3712 def test_strip_quoted_realnames(self):
3713 def check(addr, expected):
3714 self.assertEqual(utils._strip_quoted_realnames(addr), expected)
3715
3716 check('"Jane Doe" <[email protected]>, "John Doe" <[email protected]>',
3717 ' <[email protected]>, <[email protected]>')
3718 check(r'"Jane \"Doe\"." <[email protected]>',
3719 ' <[email protected]>')
3720
3721 # special cases
3722 check(r'before"name"after', 'beforeafter')
3723 check(r'before"name"', 'before')
3724 check(r'b"name"', 'b') # single char
3725 check(r'"name"after', 'after')
3726 check(r'"name"a', 'a') # single char
3727 check(r'"name"', '')
3728
3729 # no change
3730 for addr in (
3731 'Jane Doe <[email protected]>, John Doe <[email protected]>',
3732 'lone " quote',
3733 ):
3734 self.assertEqual(utils._strip_quoted_realnames(addr), addr)
3735
3736
3737 def test_check_parenthesis(self):
3738 addr = '[email protected]'
3739 self.assertTrue(utils._check_parenthesis(f'{addr} (Alice)'))
3740 self.assertFalse(utils._check_parenthesis(f'{addr} )Alice('))
3741 self.assertFalse(utils._check_parenthesis(f'{addr} (Alice))'))
3742 self.assertFalse(utils._check_parenthesis(f'{addr} ((Alice)'))
3743
3744 # Ignore real name between quotes
3745 self.assertTrue(utils._check_parenthesis(f'")Alice((" {addr}'))
3746
3747
3748 # Test the iterator/generators
3749 class TestIterators(TestEmailBase):
3750 def test_body_line_iterator(self):
3751 eq = self.assertEqual
3752 neq = self.ndiffAssertEqual
3753 # First a simple non-multipart message
3754 msg = self._msgobj('msg_01.txt')
3755 it = iterators.body_line_iterator(msg)
3756 lines = list(it)
3757 eq(len(lines), 6)
3758 neq(EMPTYSTRING.join(lines), msg.get_payload())
3759 # Now a more complicated multipart
3760 msg = self._msgobj('msg_02.txt')
3761 it = iterators.body_line_iterator(msg)
3762 lines = list(it)
3763 eq(len(lines), 43)
3764 with openfile('msg_19.txt', encoding="utf-8") as fp:
3765 neq(EMPTYSTRING.join(lines), fp.read())
3766
3767 def test_typed_subpart_iterator(self):
3768 eq = self.assertEqual
3769 msg = self._msgobj('msg_04.txt')
3770 it = iterators.typed_subpart_iterator(msg, 'text')
3771 lines = []
3772 subparts = 0
3773 for subpart in it:
3774 subparts += 1
3775 lines.append(subpart.get_payload())
3776 eq(subparts, 2)
3777 eq(EMPTYSTRING.join(lines), """\
3778 a simple kind of mirror
3779 to reflect upon our own
3780 a simple kind of mirror
3781 to reflect upon our own
3782 """)
3783
3784 def test_typed_subpart_iterator_default_type(self):
3785 eq = self.assertEqual
3786 msg = self._msgobj('msg_03.txt')
3787 it = iterators.typed_subpart_iterator(msg, 'text', 'plain')
3788 lines = []
3789 subparts = 0
3790 for subpart in it:
3791 subparts += 1
3792 lines.append(subpart.get_payload())
3793 eq(subparts, 1)
3794 eq(EMPTYSTRING.join(lines), """\
3795
3796 Hi,
3797
3798 Do you like this message?
3799
3800 -Me
3801 """)
3802
3803 def test_pushCR_LF(self):
3804 '''FeedParser BufferedSubFile.push() assumed it received complete
3805 line endings. A CR ending one push() followed by a LF starting
3806 the next push() added an empty line.
3807 '''
3808 imt = [
3809 ("a\r \n", 2),
3810 ("b", 0),
3811 ("c\n", 1),
3812 ("", 0),
3813 ("d\r\n", 1),
3814 ("e\r", 0),
3815 ("\nf", 1),
3816 ("\r\n", 1),
3817 ]
3818 from email.feedparser import BufferedSubFile, NeedMoreData
3819 bsf = BufferedSubFile()
3820 om = []
3821 nt = 0
3822 for il, n in imt:
3823 bsf.push(il)
3824 nt += n
3825 n1 = 0
3826 for ol in iter(bsf.readline, NeedMoreData):
3827 om.append(ol)
3828 n1 += 1
3829 self.assertEqual(n, n1)
3830 self.assertEqual(len(om), nt)
3831 self.assertEqual(''.join([il for il, n in imt]), ''.join(om))
3832
3833 def test_push_random(self):
3834 from email.feedparser import BufferedSubFile, NeedMoreData
3835
3836 n = 10000
3837 chunksize = 5
3838 chars = 'abcd \t\r\n'
3839
3840 s = ''.join(choice(chars) for i in range(n)) + '\n'
3841 target = s.splitlines(True)
3842
3843 bsf = BufferedSubFile()
3844 lines = []
3845 for i in range(0, len(s), chunksize):
3846 chunk = s[i:i+chunksize]
3847 bsf.push(chunk)
3848 lines.extend(iter(bsf.readline, NeedMoreData))
3849 self.assertEqual(lines, target)
3850
3851
3852 class TestFeedParsers(TestEmailBase):
3853
3854 def parse(self, chunks):
3855 feedparser = FeedParser()
3856 for chunk in chunks:
3857 feedparser.feed(chunk)
3858 return feedparser.close()
3859
3860 def test_empty_header_name_handled(self):
3861 # Issue 19996
3862 msg = self.parse("First: val\n: bad\nSecond: val")
3863 self.assertEqual(msg['First'], 'val')
3864 self.assertEqual(msg['Second'], 'val')
3865
3866 def test_newlines(self):
3867 m = self.parse(['a:\nb:\rc:\r\nd:\n'])
3868 self.assertEqual(m.keys(), ['a', 'b', 'c', 'd'])
3869 m = self.parse(['a:\nb:\rc:\r\nd:'])
3870 self.assertEqual(m.keys(), ['a', 'b', 'c', 'd'])
3871 m = self.parse(['a:\rb', 'c:\n'])
3872 self.assertEqual(m.keys(), ['a', 'bc'])
3873 m = self.parse(['a:\r', 'b:\n'])
3874 self.assertEqual(m.keys(), ['a', 'b'])
3875 m = self.parse(['a:\r', '\nb:\n'])
3876 self.assertEqual(m.keys(), ['a', 'b'])
3877
3878 # Only CR and LF should break header fields
3879 m = self.parse(['a:\x85b:\u2028c:\n'])
3880 self.assertEqual(m.items(), [('a', '\x85b:\u2028c:')])
3881 m = self.parse(['a:\r', 'b:\x85', 'c:\n'])
3882 self.assertEqual(m.items(), [('a', ''), ('b', '\x85c:')])
3883
3884 def test_long_lines(self):
3885 # Expected peak memory use on 32-bit platform: 6*N*M bytes.
3886 M, N = 1000, 20000
3887 m = self.parse(['a:b\n\n'] + ['x'*M] * N)
3888 self.assertEqual(m.items(), [('a', 'b')])
3889 self.assertEqual(m.get_payload(), 'x'*M*N)
3890 m = self.parse(['a:b\r\r'] + ['x'*M] * N)
3891 self.assertEqual(m.items(), [('a', 'b')])
3892 self.assertEqual(m.get_payload(), 'x'*M*N)
3893 m = self.parse(['a:b\r\r'] + ['x'*M+'\x85'] * N)
3894 self.assertEqual(m.items(), [('a', 'b')])
3895 self.assertEqual(m.get_payload(), ('x'*M+'\x85')*N)
3896 m = self.parse(['a:\r', 'b: '] + ['x'*M] * N)
3897 self.assertEqual(m.items(), [('a', ''), ('b', 'x'*M*N)])
3898
3899
3900 class TestParsers(TestEmailBase):
3901
3902 def test_header_parser(self):
3903 eq = self.assertEqual
3904 # Parse only the headers of a complex multipart MIME document
3905 with openfile('msg_02.txt', encoding="utf-8") as fp:
3906 msg = HeaderParser().parse(fp)
3907 eq(msg['from'], '[email protected]')
3908 eq(msg['to'], '[email protected]')
3909 eq(msg.get_content_type(), 'multipart/mixed')
3910 self.assertFalse(msg.is_multipart())
3911 self.assertIsInstance(msg.get_payload(), str)
3912
3913 def test_bytes_header_parser(self):
3914 eq = self.assertEqual
3915 # Parse only the headers of a complex multipart MIME document
3916 with openfile('msg_02.txt', 'rb') as fp:
3917 msg = email.parser.BytesHeaderParser().parse(fp)
3918 eq(msg['from'], '[email protected]')
3919 eq(msg['to'], '[email protected]')
3920 eq(msg.get_content_type(), 'multipart/mixed')
3921 self.assertFalse(msg.is_multipart())
3922 self.assertIsInstance(msg.get_payload(), str)
3923 self.assertIsInstance(msg.get_payload(decode=True), bytes)
3924
3925 def test_header_parser_multipart_is_valid(self):
3926 # Don't flag valid multipart emails as having defects
3927 with openfile('msg_47.txt', encoding="utf-8") as fp:
3928 msgdata = fp.read()
3929
3930 parser = email.parser.Parser(policy=email.policy.default)
3931 parsed_msg = parser.parsestr(msgdata, headersonly=True)
3932
3933 self.assertEqual(parsed_msg.defects, [])
3934
3935 def test_bytes_parser_does_not_close_file(self):
3936 with openfile('msg_02.txt', 'rb') as fp:
3937 email.parser.BytesParser().parse(fp)
3938 self.assertFalse(fp.closed)
3939
3940 def test_bytes_parser_on_exception_does_not_close_file(self):
3941 with openfile('msg_15.txt', 'rb') as fp:
3942 bytesParser = email.parser.BytesParser
3943 self.assertRaises(email.errors.StartBoundaryNotFoundDefect,
3944 bytesParser(policy=email.policy.strict).parse,
3945 fp)
3946 self.assertFalse(fp.closed)
3947
3948 def test_parser_does_not_close_file(self):
3949 with openfile('msg_02.txt', encoding="utf-8") as fp:
3950 email.parser.Parser().parse(fp)
3951 self.assertFalse(fp.closed)
3952
3953 def test_parser_on_exception_does_not_close_file(self):
3954 with openfile('msg_15.txt', encoding="utf-8") as fp:
3955 parser = email.parser.Parser
3956 self.assertRaises(email.errors.StartBoundaryNotFoundDefect,
3957 parser(policy=email.policy.strict).parse, fp)
3958 self.assertFalse(fp.closed)
3959
3960 def test_whitespace_continuation(self):
3961 eq = self.assertEqual
3962 # This message contains a line after the Subject: header that has only
3963 # whitespace, but it is not empty!
3964 msg = email.message_from_string("""\
3965 From: [email protected]
3966 To: [email protected]
3967 Subject: the next line has a space on it
3968 \x20
3969 Date: Mon, 8 Apr 2002 15:09:19 -0400
3970 Message-ID: spam
3971
3972 Here's the message body
3973 """)
3974 eq(msg['subject'], 'the next line has a space on it\n ')
3975 eq(msg['message-id'], 'spam')
3976 eq(msg.get_payload(), "Here's the message body\n")
3977
3978 def test_whitespace_continuation_last_header(self):
3979 eq = self.assertEqual
3980 # Like the previous test, but the subject line is the last
3981 # header.
3982 msg = email.message_from_string("""\
3983 From: [email protected]
3984 To: [email protected]
3985 Date: Mon, 8 Apr 2002 15:09:19 -0400
3986 Message-ID: spam
3987 Subject: the next line has a space on it
3988 \x20
3989
3990 Here's the message body
3991 """)
3992 eq(msg['subject'], 'the next line has a space on it\n ')
3993 eq(msg['message-id'], 'spam')
3994 eq(msg.get_payload(), "Here's the message body\n")
3995
3996 def test_crlf_separation(self):
3997 eq = self.assertEqual
3998 with openfile('msg_26.txt', encoding="utf-8", newline='\n') as fp:
3999 msg = Parser().parse(fp)
4000 eq(len(msg.get_payload()), 2)
4001 part1 = msg.get_payload(0)
4002 eq(part1.get_content_type(), 'text/plain')
4003 eq(part1.get_payload(), 'Simple email with attachment.\r\n\r\n')
4004 part2 = msg.get_payload(1)
4005 eq(part2.get_content_type(), 'application/riscos')
4006
4007 def test_crlf_flatten(self):
4008 # Using newline='\n' preserves the crlfs in this input file.
4009 with openfile('msg_26.txt', encoding="utf-8", newline='\n') as fp:
4010 text = fp.read()
4011 msg = email.message_from_string(text)
4012 s = StringIO()
4013 g = Generator(s)
4014 g.flatten(msg, linesep='\r\n')
4015 self.assertEqual(s.getvalue(), text)
4016
4017 maxDiff = None
4018
4019 def test_multipart_digest_with_extra_mime_headers(self):
4020 eq = self.assertEqual
4021 neq = self.ndiffAssertEqual
4022 with openfile('msg_28.txt', encoding="utf-8") as fp:
4023 msg = email.message_from_file(fp)
4024 # Structure is:
4025 # multipart/digest
4026 # message/rfc822
4027 # text/plain
4028 # message/rfc822
4029 # text/plain
4030 eq(msg.is_multipart(), 1)
4031 eq(len(msg.get_payload()), 2)
4032 part1 = msg.get_payload(0)
4033 eq(part1.get_content_type(), 'message/rfc822')
4034 eq(part1.is_multipart(), 1)
4035 eq(len(part1.get_payload()), 1)
4036 part1a = part1.get_payload(0)
4037 eq(part1a.is_multipart(), 0)
4038 eq(part1a.get_content_type(), 'text/plain')
4039 neq(part1a.get_payload(), 'message 1\n')
4040 # next message/rfc822
4041 part2 = msg.get_payload(1)
4042 eq(part2.get_content_type(), 'message/rfc822')
4043 eq(part2.is_multipart(), 1)
4044 eq(len(part2.get_payload()), 1)
4045 part2a = part2.get_payload(0)
4046 eq(part2a.is_multipart(), 0)
4047 eq(part2a.get_content_type(), 'text/plain')
4048 neq(part2a.get_payload(), 'message 2\n')
4049
4050 def test_three_lines(self):
4051 # A bug report by Andrew McNamara
4052 lines = ['From: Andrew Person <[email protected]',
4053 'Subject: Test',
4054 'Date: Tue, 20 Aug 2002 16:43:45 +1000']
4055 msg = email.message_from_string(NL.join(lines))
4056 self.assertEqual(msg['date'], 'Tue, 20 Aug 2002 16:43:45 +1000')
4057
4058 def test_strip_line_feed_and_carriage_return_in_headers(self):
4059 eq = self.assertEqual
4060 # For [ 1002475 ] email message parser doesn't handle \r\n correctly
4061 value1 = 'text'
4062 value2 = 'more text'
4063 m = 'Header: %s\r\nNext-Header: %s\r\n\r\nBody\r\n\r\n' % (
4064 value1, value2)
4065 msg = email.message_from_string(m)
4066 eq(msg.get('Header'), value1)
4067 eq(msg.get('Next-Header'), value2)
4068
4069 def test_rfc2822_header_syntax(self):
4070 eq = self.assertEqual
4071 m = '>From: foo\nFrom: bar\n!"#QUX;~: zoo\n\nbody'
4072 msg = email.message_from_string(m)
4073 eq(len(msg), 3)
4074 eq(sorted(field for field in msg), ['!"#QUX;~', '>From', 'From'])
4075 eq(msg.get_payload(), 'body')
4076
4077 def test_rfc2822_space_not_allowed_in_header(self):
4078 eq = self.assertEqual
4079 m = '>From [email protected] 11:25:53\nFrom: bar\n!"#QUX;~: zoo\n\nbody'
4080 msg = email.message_from_string(m)
4081 eq(len(msg.keys()), 0)
4082
4083 def test_rfc2822_one_character_header(self):
4084 eq = self.assertEqual
4085 m = 'A: first header\nB: second header\nCC: third header\n\nbody'
4086 msg = email.message_from_string(m)
4087 headers = msg.keys()
4088 headers.sort()
4089 eq(headers, ['A', 'B', 'CC'])
4090 eq(msg.get_payload(), 'body')
4091
4092 def test_CRLFLF_at_end_of_part(self):
4093 # issue 5610: feedparser should not eat two chars from body part ending
4094 # with "\r\n\n".
4095 m = (
4096 "From: [email protected]\n"
4097 "To: baz\n"
4098 "Mime-Version: 1.0\n"
4099 "Content-Type: multipart/mixed; boundary=BOUNDARY\n"
4100 "\n"
4101 "--BOUNDARY\n"
4102 "Content-Type: text/plain\n"
4103 "\n"
4104 "body ending with CRLF newline\r\n"
4105 "\n"
4106 "--BOUNDARY--\n"
4107 )
4108 msg = email.message_from_string(m)
4109 self.assertTrue(msg.get_payload(0).get_payload().endswith('\r\n'))
4110
4111
4112 class Test8BitBytesHandling(TestEmailBase):
4113 # In Python3 all input is string, but that doesn't work if the actual input
4114 # uses an 8bit transfer encoding. To hack around that, in email 5.1 we
4115 # decode byte streams using the surrogateescape error handler, and
4116 # reconvert to binary at appropriate places if we detect surrogates. This
4117 # doesn't allow us to transform headers with 8bit bytes (they get munged),
4118 # but it does allow us to parse and preserve them, and to decode body
4119 # parts that use an 8bit CTE.
4120
4121 bodytest_msg = textwrap.dedent("""\
4122 From: [email protected]
4123 To: baz
4124 Mime-Version: 1.0
4125 Content-Type: text/plain; charset={charset}
4126 Content-Transfer-Encoding: {cte}
4127
4128 {bodyline}
4129 """)
4130
4131 def test_known_8bit_CTE(self):
4132 m = self.bodytest_msg.format(charset='utf-8',
4133 cte='8bit',
4134 bodyline='pöstal').encode('utf-8')
4135 msg = email.message_from_bytes(m)
4136 self.assertEqual(msg.get_payload(), "pöstal\n")
4137 self.assertEqual(msg.get_payload(decode=True),
4138 "pöstal\n".encode('utf-8'))
4139
4140 def test_unknown_8bit_CTE(self):
4141 m = self.bodytest_msg.format(charset='notavalidcharset',
4142 cte='8bit',
4143 bodyline='pöstal').encode('utf-8')
4144 msg = email.message_from_bytes(m)
4145 self.assertEqual(msg.get_payload(), "p\uFFFD\uFFFDstal\n")
4146 self.assertEqual(msg.get_payload(decode=True),
4147 "pöstal\n".encode('utf-8'))
4148
4149 def test_8bit_in_quopri_body(self):
4150 # This is non-RFC compliant data...without 'decode' the library code
4151 # decodes the body using the charset from the headers, and because the
4152 # source byte really is utf-8 this works. This is likely to fail
4153 # against real dirty data (ie: produce mojibake), but the data is
4154 # invalid anyway so it is as good a guess as any. But this means that
4155 # this test just confirms the current behavior; that behavior is not
4156 # necessarily the best possible behavior. With 'decode' it is
4157 # returning the raw bytes, so that test should be of correct behavior,
4158 # or at least produce the same result that email4 did.
4159 m = self.bodytest_msg.format(charset='utf-8',
4160 cte='quoted-printable',
4161 bodyline='p=C3=B6stál').encode('utf-8')
4162 msg = email.message_from_bytes(m)
4163 self.assertEqual(msg.get_payload(), 'p=C3=B6stál\n')
4164 self.assertEqual(msg.get_payload(decode=True),
4165 'pöstál\n'.encode('utf-8'))
4166
4167 def test_invalid_8bit_in_non_8bit_cte_uses_replace(self):
4168 # This is similar to the previous test, but proves that if the 8bit
4169 # byte is undecodeable in the specified charset, it gets replaced
4170 # by the unicode 'unknown' character. Again, this may or may not
4171 # be the ideal behavior. Note that if decode=False none of the
4172 # decoders will get involved, so this is the only test we need
4173 # for this behavior.
4174 m = self.bodytest_msg.format(charset='ascii',
4175 cte='quoted-printable',
4176 bodyline='p=C3=B6stál').encode('utf-8')
4177 msg = email.message_from_bytes(m)
4178 self.assertEqual(msg.get_payload(), 'p=C3=B6st\uFFFD\uFFFDl\n')
4179 self.assertEqual(msg.get_payload(decode=True),
4180 'pöstál\n'.encode('utf-8'))
4181
4182 # test_defect_handling:test_invalid_chars_in_base64_payload
4183 def test_8bit_in_base64_body(self):
4184 # If we get 8bit bytes in a base64 body, we can just ignore them
4185 # as being outside the base64 alphabet and decode anyway. But
4186 # we register a defect.
4187 m = self.bodytest_msg.format(charset='utf-8',
4188 cte='base64',
4189 bodyline='cMO2c3RhbAá=').encode('utf-8')
4190 msg = email.message_from_bytes(m)
4191 self.assertEqual(msg.get_payload(decode=True),
4192 'pöstal'.encode('utf-8'))
4193 self.assertIsInstance(msg.defects[0],
4194 errors.InvalidBase64CharactersDefect)
4195
4196 def test_8bit_in_uuencode_body(self):
4197 # Sticking an 8bit byte in a uuencode block makes it undecodable by
4198 # normal means, so the block is returned undecoded, but as bytes.
4199 m = self.bodytest_msg.format(charset='utf-8',
4200 cte='uuencode',
4201 bodyline='<,.V<W1A; á ').encode('utf-8')
4202 msg = email.message_from_bytes(m)
4203 self.assertEqual(msg.get_payload(decode=True),
4204 '<,.V<W1A; á \n'.encode('utf-8'))
4205
4206
4207 headertest_headers = (
4208 ('From: [email protected]', ('From', '[email protected]')),
4209 ('To: báz', ('To', '=?unknown-8bit?q?b=C3=A1z?=')),
4210 ('Subject: Maintenant je vous présente mon collègue, le pouf célèbre\n'
4211 '\tJean de Baddie',
4212 ('Subject', '=?unknown-8bit?q?Maintenant_je_vous_pr=C3=A9sente_mon_'
4213 'coll=C3=A8gue=2C_le_pouf_c=C3=A9l=C3=A8bre?=\n'
4214 ' =?unknown-8bit?q?_Jean_de_Baddie?=')),
4215 ('From: göst', ('From', '=?unknown-8bit?b?Z8O2c3Q=?=')),
4216 )
4217 headertest_msg = ('\n'.join([src for (src, _) in headertest_headers]) +
4218 '\nYes, they are flying.\n').encode('utf-8')
4219
4220 def test_get_8bit_header(self):
4221 msg = email.message_from_bytes(self.headertest_msg)
4222 self.assertEqual(str(msg.get('to')), 'b\uFFFD\uFFFDz')
4223 self.assertEqual(str(msg['to']), 'b\uFFFD\uFFFDz')
4224
4225 def test_print_8bit_headers(self):
4226 msg = email.message_from_bytes(self.headertest_msg)
4227 self.assertEqual(str(msg),
4228 textwrap.dedent("""\
4229 From: {}
4230 To: {}
4231 Subject: {}
4232 From: {}
4233
4234 Yes, they are flying.
4235 """).format(*[expected[1] for (_, expected) in
4236 self.headertest_headers]))
4237
4238 def test_values_with_8bit_headers(self):
4239 msg = email.message_from_bytes(self.headertest_msg)
4240 self.assertListEqual([str(x) for x in msg.values()],
4241 ['[email protected]',
4242 'b\uFFFD\uFFFDz',
4243 'Maintenant je vous pr\uFFFD\uFFFDsente mon '
4244 'coll\uFFFD\uFFFDgue, le pouf '
4245 'c\uFFFD\uFFFDl\uFFFD\uFFFDbre\n'
4246 '\tJean de Baddie',
4247 "g\uFFFD\uFFFDst"])
4248
4249 def test_items_with_8bit_headers(self):
4250 msg = email.message_from_bytes(self.headertest_msg)
4251 self.assertListEqual([(str(x), str(y)) for (x, y) in msg.items()],
4252 [('From', '[email protected]'),
4253 ('To', 'b\uFFFD\uFFFDz'),
4254 ('Subject', 'Maintenant je vous '
4255 'pr\uFFFD\uFFFDsente '
4256 'mon coll\uFFFD\uFFFDgue, le pouf '
4257 'c\uFFFD\uFFFDl\uFFFD\uFFFDbre\n'
4258 '\tJean de Baddie'),
4259 ('From', 'g\uFFFD\uFFFDst')])
4260
4261 def test_get_all_with_8bit_headers(self):
4262 msg = email.message_from_bytes(self.headertest_msg)
4263 self.assertListEqual([str(x) for x in msg.get_all('from')],
4264 ['[email protected]',
4265 'g\uFFFD\uFFFDst'])
4266
4267 def test_get_content_type_with_8bit(self):
4268 msg = email.message_from_bytes(textwrap.dedent("""\
4269 Content-Type: text/pl\xA7in; charset=utf-8
4270 """).encode('latin-1'))
4271 self.assertEqual(msg.get_content_type(), "text/pl\uFFFDin")
4272 self.assertEqual(msg.get_content_maintype(), "text")
4273 self.assertEqual(msg.get_content_subtype(), "pl\uFFFDin")
4274
4275 # test_headerregistry.TestContentTypeHeader.non_ascii_in_params
4276 def test_get_params_with_8bit(self):
4277 msg = email.message_from_bytes(
4278 'X-Header: foo=\xa7ne; b\xa7r=two; baz=three\n'.encode('latin-1'))
4279 self.assertEqual(msg.get_params(header='x-header'),
4280 [('foo', '\uFFFDne'), ('b\uFFFDr', 'two'), ('baz', 'three')])
4281 self.assertEqual(msg.get_param('Foo', header='x-header'), '\uFFFdne')
4282 # XXX: someday you might be able to get 'b\xa7r', for now you can't.
4283 self.assertEqual(msg.get_param('b\xa7r', header='x-header'), None)
4284
4285 # test_headerregistry.TestContentTypeHeader.non_ascii_in_rfc2231_value
4286 def test_get_rfc2231_params_with_8bit(self):
4287 msg = email.message_from_bytes(textwrap.dedent("""\
4288 Content-Type: text/plain; charset=us-ascii;
4289 title*=us-ascii'en'This%20is%20not%20f\xa7n"""
4290 ).encode('latin-1'))
4291 self.assertEqual(msg.get_param('title'),
4292 ('us-ascii', 'en', 'This is not f\uFFFDn'))
4293
4294 def test_set_rfc2231_params_with_8bit(self):
4295 msg = email.message_from_bytes(textwrap.dedent("""\
4296 Content-Type: text/plain; charset=us-ascii;
4297 title*=us-ascii'en'This%20is%20not%20f\xa7n"""
4298 ).encode('latin-1'))
4299 msg.set_param('title', 'test')
4300 self.assertEqual(msg.get_param('title'), 'test')
4301
4302 def test_del_rfc2231_params_with_8bit(self):
4303 msg = email.message_from_bytes(textwrap.dedent("""\
4304 Content-Type: text/plain; charset=us-ascii;
4305 title*=us-ascii'en'This%20is%20not%20f\xa7n"""
4306 ).encode('latin-1'))
4307 msg.del_param('title')
4308 self.assertEqual(msg.get_param('title'), None)
4309 self.assertEqual(msg.get_content_maintype(), 'text')
4310
4311 def test_get_payload_with_8bit_cte_header(self):
4312 msg = email.message_from_bytes(textwrap.dedent("""\
4313 Content-Transfer-Encoding: b\xa7se64
4314 Content-Type: text/plain; charset=latin-1
4315
4316 payload
4317 """).encode('latin-1'))
4318 self.assertEqual(msg.get_payload(), 'payload\n')
4319 self.assertEqual(msg.get_payload(decode=True), b'payload\n')
4320
4321 non_latin_bin_msg = textwrap.dedent("""\
4322 From: [email protected]
4323 To: báz
4324 Subject: Maintenant je vous présente mon collègue, le pouf célèbre
4325 \tJean de Baddie
4326 Mime-Version: 1.0
4327 Content-Type: text/plain; charset="utf-8"
4328 Content-Transfer-Encoding: 8bit
4329
4330 Да, они летят.
4331 """).encode('utf-8')
4332
4333 def test_bytes_generator(self):
4334 msg = email.message_from_bytes(self.non_latin_bin_msg)
4335 out = BytesIO()
4336 email.generator.BytesGenerator(out).flatten(msg)
4337 self.assertEqual(out.getvalue(), self.non_latin_bin_msg)
4338
4339 def test_bytes_generator_handles_None_body(self):
4340 #Issue 11019
4341 msg = email.message.Message()
4342 out = BytesIO()
4343 email.generator.BytesGenerator(out).flatten(msg)
4344 self.assertEqual(out.getvalue(), b"\n")
4345
4346 non_latin_bin_msg_as7bit_wrapped = textwrap.dedent("""\
4347 From: [email protected]
4348 To: =?unknown-8bit?q?b=C3=A1z?=
4349 Subject: =?unknown-8bit?q?Maintenant_je_vous_pr=C3=A9sente_mon_coll=C3=A8gue?=
4350 =?unknown-8bit?q?=2C_le_pouf_c=C3=A9l=C3=A8bre?=
4351 =?unknown-8bit?q?_Jean_de_Baddie?=
4352 Mime-Version: 1.0
4353 Content-Type: text/plain; charset="utf-8"
4354 Content-Transfer-Encoding: base64
4355
4356 0JTQsCwg0L7QvdC4INC70LXRgtGP0YIuCg==
4357 """)
4358
4359 def test_generator_handles_8bit(self):
4360 msg = email.message_from_bytes(self.non_latin_bin_msg)
4361 out = StringIO()
4362 email.generator.Generator(out).flatten(msg)
4363 self.assertEqual(out.getvalue(), self.non_latin_bin_msg_as7bit_wrapped)
4364
4365 def test_str_generator_should_not_mutate_msg_when_handling_8bit(self):
4366 msg = email.message_from_bytes(self.non_latin_bin_msg)
4367 out = BytesIO()
4368 BytesGenerator(out).flatten(msg)
4369 orig_value = out.getvalue()
4370 Generator(StringIO()).flatten(msg) # Should not mutate msg!
4371 out = BytesIO()
4372 BytesGenerator(out).flatten(msg)
4373 self.assertEqual(out.getvalue(), orig_value)
4374
4375 def test_bytes_generator_with_unix_from(self):
4376 # The unixfrom contains a current date, so we can't check it
4377 # literally. Just make sure the first word is 'From' and the
4378 # rest of the message matches the input.
4379 msg = email.message_from_bytes(self.non_latin_bin_msg)
4380 out = BytesIO()
4381 email.generator.BytesGenerator(out).flatten(msg, unixfrom=True)
4382 lines = out.getvalue().split(b'\n')
4383 self.assertEqual(lines[0].split()[0], b'From')
4384 self.assertEqual(b'\n'.join(lines[1:]), self.non_latin_bin_msg)
4385
4386 non_latin_bin_msg_as7bit = non_latin_bin_msg_as7bit_wrapped.split('\n')
4387 non_latin_bin_msg_as7bit[2:4] = [
4388 'Subject: =?unknown-8bit?q?Maintenant_je_vous_pr=C3=A9sente_mon_'
4389 'coll=C3=A8gue=2C_le_pouf_c=C3=A9l=C3=A8bre?=']
4390 non_latin_bin_msg_as7bit = '\n'.join(non_latin_bin_msg_as7bit)
4391
4392 def test_message_from_binary_file(self):
4393 fn = 'test.msg'
4394 self.addCleanup(unlink, fn)
4395 with open(fn, 'wb') as testfile:
4396 testfile.write(self.non_latin_bin_msg)
4397 with open(fn, 'rb') as testfile:
4398 m = email.parser.BytesParser().parse(testfile)
4399 self.assertEqual(str(m), self.non_latin_bin_msg_as7bit)
4400
4401 latin_bin_msg = textwrap.dedent("""\
4402 From: [email protected]
4403 To: Dinsdale
4404 Subject: Nudge nudge, wink, wink
4405 Mime-Version: 1.0
4406 Content-Type: text/plain; charset="latin-1"
4407 Content-Transfer-Encoding: 8bit
4408
4409 oh là là, know what I mean, know what I mean?
4410 """).encode('latin-1')
4411
4412 latin_bin_msg_as7bit = textwrap.dedent("""\
4413 From: [email protected]
4414 To: Dinsdale
4415 Subject: Nudge nudge, wink, wink
4416 Mime-Version: 1.0
4417 Content-Type: text/plain; charset="iso-8859-1"
4418 Content-Transfer-Encoding: quoted-printable
4419
4420 oh l=E0 l=E0, know what I mean, know what I mean?
4421 """)
4422
4423 def test_string_generator_reencodes_to_quopri_when_appropriate(self):
4424 m = email.message_from_bytes(self.latin_bin_msg)
4425 self.assertEqual(str(m), self.latin_bin_msg_as7bit)
4426
4427 def test_decoded_generator_emits_unicode_body(self):
4428 m = email.message_from_bytes(self.latin_bin_msg)
4429 out = StringIO()
4430 email.generator.DecodedGenerator(out).flatten(m)
4431 #DecodedHeader output contains an extra blank line compared
4432 #to the input message. RDM: not sure if this is a bug or not,
4433 #but it is not specific to the 8bit->7bit conversion.
4434 self.assertEqual(out.getvalue(),
4435 self.latin_bin_msg.decode('latin-1')+'\n')
4436
4437 def test_bytes_feedparser(self):
4438 bfp = email.feedparser.BytesFeedParser()
4439 for i in range(0, len(self.latin_bin_msg), 10):
4440 bfp.feed(self.latin_bin_msg[i:i+10])
4441 m = bfp.close()
4442 self.assertEqual(str(m), self.latin_bin_msg_as7bit)
4443
4444 def test_crlf_flatten(self):
4445 with openfile('msg_26.txt', 'rb') as fp:
4446 text = fp.read()
4447 msg = email.message_from_bytes(text)
4448 s = BytesIO()
4449 g = email.generator.BytesGenerator(s)
4450 g.flatten(msg, linesep='\r\n')
4451 self.assertEqual(s.getvalue(), text)
4452
4453 def test_8bit_multipart(self):
4454 # Issue 11605
4455 source = textwrap.dedent("""\
4456 Date: Fri, 18 Mar 2011 17:15:43 +0100
4457 To: [email protected]
4458 From: foodwatch-Newsletter <[email protected]>
4459 Subject: Aktuelles zu Japan, Klonfleisch und Smiley-System
4460 Message-ID: <[email protected]>
4461 MIME-Version: 1.0
4462 Content-Type: multipart/alternative;
4463 boundary="b1_76a486bee62b0d200f33dc2ca08220ad"
4464
4465 --b1_76a486bee62b0d200f33dc2ca08220ad
4466 Content-Type: text/plain; charset="utf-8"
4467 Content-Transfer-Encoding: 8bit
4468
4469 Guten Tag, ,
4470
4471 mit großer Betroffenheit verfolgen auch wir im foodwatch-Team die
4472 Nachrichten aus Japan.
4473
4474
4475 --b1_76a486bee62b0d200f33dc2ca08220ad
4476 Content-Type: text/html; charset="utf-8"
4477 Content-Transfer-Encoding: 8bit
4478
4479 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
4480 "http://www.w3.org/TR/html4/loose.dtd">
4481 <html lang="de">
4482 <head>
4483 <title>foodwatch - Newsletter</title>
4484 </head>
4485 <body>
4486 <p>mit gro&szlig;er Betroffenheit verfolgen auch wir im foodwatch-Team
4487 die Nachrichten aus Japan.</p>
4488 </body>
4489 </html>
4490 --b1_76a486bee62b0d200f33dc2ca08220ad--
4491
4492 """).encode('utf-8')
4493 msg = email.message_from_bytes(source)
4494 s = BytesIO()
4495 g = email.generator.BytesGenerator(s)
4496 g.flatten(msg)
4497 self.assertEqual(s.getvalue(), source)
4498
4499 def test_bytes_generator_b_encoding_linesep(self):
4500 # Issue 14062: b encoding was tacking on an extra \n.
4501 m = Message()
4502 # This has enough non-ascii that it should always end up b encoded.
4503 m['Subject'] = Header('žluťoučký kůň')
4504 s = BytesIO()
4505 g = email.generator.BytesGenerator(s)
4506 g.flatten(m, linesep='\r\n')
4507 self.assertEqual(
4508 s.getvalue(),
4509 b'Subject: =?utf-8?b?xb5sdcWlb3XEjWvDvSBrxa/FiA==?=\r\n\r\n')
4510
4511 def test_generator_b_encoding_linesep(self):
4512 # Since this broke in ByteGenerator, test Generator for completeness.
4513 m = Message()
4514 # This has enough non-ascii that it should always end up b encoded.
4515 m['Subject'] = Header('žluťoučký kůň')
4516 s = StringIO()
4517 g = email.generator.Generator(s)
4518 g.flatten(m, linesep='\r\n')
4519 self.assertEqual(
4520 s.getvalue(),
4521 'Subject: =?utf-8?b?xb5sdcWlb3XEjWvDvSBrxa/FiA==?=\r\n\r\n')
4522
4523 maxDiff = None
4524
4525
4526 class BaseTestBytesGeneratorIdempotent:
4527
4528 maxDiff = None
4529
4530 def _msgobj(self, filename):
4531 with openfile(filename, 'rb') as fp:
4532 data = fp.read()
4533 data = self.normalize_linesep_regex.sub(self.blinesep, data)
4534 msg = email.message_from_bytes(data)
4535 return msg, data
4536
4537 def _idempotent(self, msg, data, unixfrom=False):
4538 b = BytesIO()
4539 g = email.generator.BytesGenerator(b, maxheaderlen=0)
4540 g.flatten(msg, unixfrom=unixfrom, linesep=self.linesep)
4541 self.assertEqual(data, b.getvalue())
4542
4543
4544 class TestBytesGeneratorIdempotentNL(BaseTestBytesGeneratorIdempotent,
4545 TestIdempotent):
4546 linesep = '\n'
4547 blinesep = b'\n'
4548 normalize_linesep_regex = re.compile(br'\r\n')
4549
4550
4551 class TestBytesGeneratorIdempotentCRLF(BaseTestBytesGeneratorIdempotent,
4552 TestIdempotent):
4553 linesep = '\r\n'
4554 blinesep = b'\r\n'
4555 normalize_linesep_regex = re.compile(br'(?<!\r)\n')
4556
4557
4558 class TestBase64(unittest.TestCase):
4559 def test_len(self):
4560 eq = self.assertEqual
4561 eq(base64mime.header_length('hello'),
4562 len(base64mime.body_encode(b'hello', eol='')))
4563 for size in range(15):
4564 if size == 0 : bsize = 0
4565 elif size <= 3 : bsize = 4
4566 elif size <= 6 : bsize = 8
4567 elif size <= 9 : bsize = 12
4568 elif size <= 12: bsize = 16
4569 else : bsize = 20
4570 eq(base64mime.header_length('x' * size), bsize)
4571
4572 def test_decode(self):
4573 eq = self.assertEqual
4574 eq(base64mime.decode(''), b'')
4575 eq(base64mime.decode('aGVsbG8='), b'hello')
4576
4577 def test_encode(self):
4578 eq = self.assertEqual
4579 eq(base64mime.body_encode(b''), '')
4580 eq(base64mime.body_encode(b'hello'), 'aGVsbG8=\n')
4581 # Test the binary flag
4582 eq(base64mime.body_encode(b'hello\n'), 'aGVsbG8K\n')
4583 # Test the maxlinelen arg
4584 eq(base64mime.body_encode(b'xxxx ' * 20, maxlinelen=40), """\
4585 eHh4eCB4eHh4IHh4eHggeHh4eCB4eHh4IHh4eHgg
4586 eHh4eCB4eHh4IHh4eHggeHh4eCB4eHh4IHh4eHgg
4587 eHh4eCB4eHh4IHh4eHggeHh4eCB4eHh4IHh4eHgg
4588 eHh4eCB4eHh4IA==
4589 """)
4590 # Test the eol argument
4591 eq(base64mime.body_encode(b'xxxx ' * 20, maxlinelen=40, eol='\r\n'),
4592 """\
4593 eHh4eCB4eHh4IHh4eHggeHh4eCB4eHh4IHh4eHgg\r
4594 eHh4eCB4eHh4IHh4eHggeHh4eCB4eHh4IHh4eHgg\r
4595 eHh4eCB4eHh4IHh4eHggeHh4eCB4eHh4IHh4eHgg\r
4596 eHh4eCB4eHh4IA==\r
4597 """)
4598
4599 def test_header_encode(self):
4600 eq = self.assertEqual
4601 he = base64mime.header_encode
4602 eq(he('hello'), '=?iso-8859-1?b?aGVsbG8=?=')
4603 eq(he('hello\r\nworld'), '=?iso-8859-1?b?aGVsbG8NCndvcmxk?=')
4604 eq(he('hello\nworld'), '=?iso-8859-1?b?aGVsbG8Kd29ybGQ=?=')
4605 # Test the charset option
4606 eq(he('hello', charset='iso-8859-2'), '=?iso-8859-2?b?aGVsbG8=?=')
4607 eq(he('hello\nworld'), '=?iso-8859-1?b?aGVsbG8Kd29ybGQ=?=')
4608
4609
4610 class TestQuopri(unittest.TestCase):
4611 def setUp(self):
4612 # Set of characters (as byte integers) that don't need to be encoded
4613 # in headers.
4614 self.hlit = list(chain(
4615 range(ord('a'), ord('z') + 1),
4616 range(ord('A'), ord('Z') + 1),
4617 range(ord('0'), ord('9') + 1),
4618 (c for c in b'!*+-/')))
4619 # Set of characters (as byte integers) that do need to be encoded in
4620 # headers.
4621 self.hnon = [c for c in range(256) if c not in self.hlit]
4622 assert len(self.hlit) + len(self.hnon) == 256
4623 # Set of characters (as byte integers) that don't need to be encoded
4624 # in bodies.
4625 self.blit = list(range(ord(' '), ord('~') + 1))
4626 self.blit.append(ord('\t'))
4627 self.blit.remove(ord('='))
4628 # Set of characters (as byte integers) that do need to be encoded in
4629 # bodies.
4630 self.bnon = [c for c in range(256) if c not in self.blit]
4631 assert len(self.blit) + len(self.bnon) == 256
4632
4633 def test_quopri_header_check(self):
4634 for c in self.hlit:
4635 self.assertFalse(quoprimime.header_check(c),
4636 'Should not be header quopri encoded: %s' % chr(c))
4637 for c in self.hnon:
4638 self.assertTrue(quoprimime.header_check(c),
4639 'Should be header quopri encoded: %s' % chr(c))
4640
4641 def test_quopri_body_check(self):
4642 for c in self.blit:
4643 self.assertFalse(quoprimime.body_check(c),
4644 'Should not be body quopri encoded: %s' % chr(c))
4645 for c in self.bnon:
4646 self.assertTrue(quoprimime.body_check(c),
4647 'Should be body quopri encoded: %s' % chr(c))
4648
4649 def test_header_quopri_len(self):
4650 eq = self.assertEqual
4651 eq(quoprimime.header_length(b'hello'), 5)
4652 # RFC 2047 chrome is not included in header_length().
4653 eq(len(quoprimime.header_encode(b'hello', charset='xxx')),
4654 quoprimime.header_length(b'hello') +
4655 # =?xxx?q?...?= means 10 extra characters
4656 10)
4657 eq(quoprimime.header_length(b'h@e@l@l@o@'), 20)
4658 # RFC 2047 chrome is not included in header_length().
4659 eq(len(quoprimime.header_encode(b'h@e@l@l@o@', charset='xxx')),
4660 quoprimime.header_length(b'h@e@l@l@o@') +
4661 # =?xxx?q?...?= means 10 extra characters
4662 10)
4663 for c in self.hlit:
4664 eq(quoprimime.header_length(bytes([c])), 1,
4665 'expected length 1 for %r' % chr(c))
4666 for c in self.hnon:
4667 # Space is special; it's encoded to _
4668 if c == ord(' '):
4669 continue
4670 eq(quoprimime.header_length(bytes([c])), 3,
4671 'expected length 3 for %r' % chr(c))
4672 eq(quoprimime.header_length(b' '), 1)
4673
4674 def test_body_quopri_len(self):
4675 eq = self.assertEqual
4676 for c in self.blit:
4677 eq(quoprimime.body_length(bytes([c])), 1)
4678 for c in self.bnon:
4679 eq(quoprimime.body_length(bytes([c])), 3)
4680
4681 def test_quote_unquote_idempotent(self):
4682 for x in range(256):
4683 c = chr(x)
4684 self.assertEqual(quoprimime.unquote(quoprimime.quote(c)), c)
4685
4686 def _test_header_encode(self, header, expected_encoded_header, charset=None):
4687 if charset is None:
4688 encoded_header = quoprimime.header_encode(header)
4689 else:
4690 encoded_header = quoprimime.header_encode(header, charset)
4691 self.assertEqual(encoded_header, expected_encoded_header)
4692
4693 def test_header_encode_null(self):
4694 self._test_header_encode(b'', '')
4695
4696 def test_header_encode_one_word(self):
4697 self._test_header_encode(b'hello', '=?iso-8859-1?q?hello?=')
4698
4699 def test_header_encode_two_lines(self):
4700 self._test_header_encode(b'hello\nworld',
4701 '=?iso-8859-1?q?hello=0Aworld?=')
4702
4703 def test_header_encode_non_ascii(self):
4704 self._test_header_encode(b'hello\xc7there',
4705 '=?iso-8859-1?q?hello=C7there?=')
4706
4707 def test_header_encode_alt_charset(self):
4708 self._test_header_encode(b'hello', '=?iso-8859-2?q?hello?=',
4709 charset='iso-8859-2')
4710
4711 def _test_header_decode(self, encoded_header, expected_decoded_header):
4712 decoded_header = quoprimime.header_decode(encoded_header)
4713 self.assertEqual(decoded_header, expected_decoded_header)
4714
4715 def test_header_decode_null(self):
4716 self._test_header_decode('', '')
4717
4718 def test_header_decode_one_word(self):
4719 self._test_header_decode('hello', 'hello')
4720
4721 def test_header_decode_two_lines(self):
4722 self._test_header_decode('hello=0Aworld', 'hello\nworld')
4723
4724 def test_header_decode_non_ascii(self):
4725 self._test_header_decode('hello=C7there', 'hello\xc7there')
4726
4727 def test_header_decode_re_bug_18380(self):
4728 # Issue 18380: Call re.sub with a positional argument for flags in the wrong position
4729 self.assertEqual(quoprimime.header_decode('=30' * 257), '0' * 257)
4730
4731 def _test_decode(self, encoded, expected_decoded, eol=None):
4732 if eol is None:
4733 decoded = quoprimime.decode(encoded)
4734 else:
4735 decoded = quoprimime.decode(encoded, eol=eol)
4736 self.assertEqual(decoded, expected_decoded)
4737
4738 def test_decode_null_word(self):
4739 self._test_decode('', '')
4740
4741 def test_decode_null_line_null_word(self):
4742 self._test_decode('\r\n', '\n')
4743
4744 def test_decode_one_word(self):
4745 self._test_decode('hello', 'hello')
4746
4747 def test_decode_one_word_eol(self):
4748 self._test_decode('hello', 'hello', eol='X')
4749
4750 def test_decode_one_line(self):
4751 self._test_decode('hello\r\n', 'hello\n')
4752
4753 def test_decode_one_line_lf(self):
4754 self._test_decode('hello\n', 'hello\n')
4755
4756 def test_decode_one_line_cr(self):
4757 self._test_decode('hello\r', 'hello\n')
4758
4759 def test_decode_one_line_nl(self):
4760 self._test_decode('hello\n', 'helloX', eol='X')
4761
4762 def test_decode_one_line_crnl(self):
4763 self._test_decode('hello\r\n', 'helloX', eol='X')
4764
4765 def test_decode_one_line_one_word(self):
4766 self._test_decode('hello\r\nworld', 'hello\nworld')
4767
4768 def test_decode_one_line_one_word_eol(self):
4769 self._test_decode('hello\r\nworld', 'helloXworld', eol='X')
4770
4771 def test_decode_two_lines(self):
4772 self._test_decode('hello\r\nworld\r\n', 'hello\nworld\n')
4773
4774 def test_decode_two_lines_eol(self):
4775 self._test_decode('hello\r\nworld\r\n', 'helloXworldX', eol='X')
4776
4777 def test_decode_one_long_line(self):
4778 self._test_decode('Spam' * 250, 'Spam' * 250)
4779
4780 def test_decode_one_space(self):
4781 self._test_decode(' ', '')
4782
4783 def test_decode_multiple_spaces(self):
4784 self._test_decode(' ' * 5, '')
4785
4786 def test_decode_one_line_trailing_spaces(self):
4787 self._test_decode('hello \r\n', 'hello\n')
4788
4789 def test_decode_two_lines_trailing_spaces(self):
4790 self._test_decode('hello \r\nworld \r\n', 'hello\nworld\n')
4791
4792 def test_decode_quoted_word(self):
4793 self._test_decode('=22quoted=20words=22', '"quoted words"')
4794
4795 def test_decode_uppercase_quoting(self):
4796 self._test_decode('ab=CD=EF', 'ab\xcd\xef')
4797
4798 def test_decode_lowercase_quoting(self):
4799 self._test_decode('ab=cd=ef', 'ab\xcd\xef')
4800
4801 def test_decode_soft_line_break(self):
4802 self._test_decode('soft line=\r\nbreak', 'soft linebreak')
4803
4804 def test_decode_false_quoting(self):
4805 self._test_decode('A=1,B=A ==> A+B==2', 'A=1,B=A ==> A+B==2')
4806
4807 def _test_encode(self, body, expected_encoded_body, maxlinelen=None, eol=None):
4808 kwargs = {}
4809 if maxlinelen is None:
4810 # Use body_encode's default.
4811 maxlinelen = 76
4812 else:
4813 kwargs['maxlinelen'] = maxlinelen
4814 if eol is None:
4815 # Use body_encode's default.
4816 eol = '\n'
4817 else:
4818 kwargs['eol'] = eol
4819 encoded_body = quoprimime.body_encode(body, **kwargs)
4820 self.assertEqual(encoded_body, expected_encoded_body)
4821 if eol == '\n' or eol == '\r\n':
4822 # We know how to split the result back into lines, so maxlinelen
4823 # can be checked.
4824 for line in encoded_body.splitlines():
4825 self.assertLessEqual(len(line), maxlinelen)
4826
4827 def test_encode_null(self):
4828 self._test_encode('', '')
4829
4830 def test_encode_null_lines(self):
4831 self._test_encode('\n\n', '\n\n')
4832
4833 def test_encode_one_line(self):
4834 self._test_encode('hello\n', 'hello\n')
4835
4836 def test_encode_one_line_crlf(self):
4837 self._test_encode('hello\r\n', 'hello\n')
4838
4839 def test_encode_one_line_eol(self):
4840 self._test_encode('hello\n', 'hello\r\n', eol='\r\n')
4841
4842 def test_encode_one_line_eol_after_non_ascii(self):
4843 # issue 20206; see changeset 0cf700464177 for why the encode/decode.
4844 self._test_encode('hello\u03c5\n'.encode('utf-8').decode('latin1'),
4845 'hello=CF=85\r\n', eol='\r\n')
4846
4847 def test_encode_one_space(self):
4848 self._test_encode(' ', '=20')
4849
4850 def test_encode_one_line_one_space(self):
4851 self._test_encode(' \n', '=20\n')
4852
4853 # XXX: body_encode() expect strings, but uses ord(char) from these strings
4854 # to index into a 256-entry list. For code points above 255, this will fail.
4855 # Should there be a check for 8-bit only ord() values in body, or at least
4856 # a comment about the expected input?
4857
4858 def test_encode_two_lines_one_space(self):
4859 self._test_encode(' \n \n', '=20\n=20\n')
4860
4861 def test_encode_one_word_trailing_spaces(self):
4862 self._test_encode('hello ', 'hello =20')
4863
4864 def test_encode_one_line_trailing_spaces(self):
4865 self._test_encode('hello \n', 'hello =20\n')
4866
4867 def test_encode_one_word_trailing_tab(self):
4868 self._test_encode('hello \t', 'hello =09')
4869
4870 def test_encode_one_line_trailing_tab(self):
4871 self._test_encode('hello \t\n', 'hello =09\n')
4872
4873 def test_encode_trailing_space_before_maxlinelen(self):
4874 self._test_encode('abcd \n1234', 'abcd =\n\n1234', maxlinelen=6)
4875
4876 def test_encode_trailing_space_at_maxlinelen(self):
4877 self._test_encode('abcd \n1234', 'abcd=\n=20\n1234', maxlinelen=5)
4878
4879 def test_encode_trailing_space_beyond_maxlinelen(self):
4880 self._test_encode('abcd \n1234', 'abc=\nd=20\n1234', maxlinelen=4)
4881
4882 def test_encode_whitespace_lines(self):
4883 self._test_encode(' \n' * 5, '=20\n' * 5)
4884
4885 def test_encode_quoted_equals(self):
4886 self._test_encode('a = b', 'a =3D b')
4887
4888 def test_encode_one_long_string(self):
4889 self._test_encode('x' * 100, 'x' * 75 + '=\n' + 'x' * 25)
4890
4891 def test_encode_one_long_line(self):
4892 self._test_encode('x' * 100 + '\n', 'x' * 75 + '=\n' + 'x' * 25 + '\n')
4893
4894 def test_encode_one_very_long_line(self):
4895 self._test_encode('x' * 200 + '\n',
4896 2 * ('x' * 75 + '=\n') + 'x' * 50 + '\n')
4897
4898 def test_encode_shortest_maxlinelen(self):
4899 self._test_encode('=' * 5, '=3D=\n' * 4 + '=3D', maxlinelen=4)
4900
4901 def test_encode_maxlinelen_too_small(self):
4902 self.assertRaises(ValueError, self._test_encode, '', '', maxlinelen=3)
4903
4904 def test_encode(self):
4905 eq = self.assertEqual
4906 eq(quoprimime.body_encode(''), '')
4907 eq(quoprimime.body_encode('hello'), 'hello')
4908 # Test the binary flag
4909 eq(quoprimime.body_encode('hello\r\nworld'), 'hello\nworld')
4910 # Test the maxlinelen arg
4911 eq(quoprimime.body_encode('xxxx ' * 20, maxlinelen=40), """\
4912 xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx=
4913 xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxx=
4914 x xxxx xxxx xxxx xxxx=20""")
4915 # Test the eol argument
4916 eq(quoprimime.body_encode('xxxx ' * 20, maxlinelen=40, eol='\r\n'),
4917 """\
4918 xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx=\r
4919 xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxx=\r
4920 x xxxx xxxx xxxx xxxx=20""")
4921 eq(quoprimime.body_encode("""\
4922 one line
4923
4924 two line"""), """\
4925 one line
4926
4927 two line""")
4928
4929
4930
4931 # Test the Charset class
4932 class TestCharset(unittest.TestCase):
4933 def tearDown(self):
4934 from email import charset as CharsetModule
4935 try:
4936 del CharsetModule.CHARSETS['fake']
4937 except KeyError:
4938 pass
4939
4940 def test_codec_encodeable(self):
4941 eq = self.assertEqual
4942 # Make sure us-ascii = no Unicode conversion
4943 c = Charset('us-ascii')
4944 eq(c.header_encode('Hello World!'), 'Hello World!')
4945 # Test 8-bit idempotency with us-ascii
4946 s = '\xa4\xa2\xa4\xa4\xa4\xa6\xa4\xa8\xa4\xaa'
4947 self.assertRaises(UnicodeError, c.header_encode, s)
4948 c = Charset('utf-8')
4949 eq(c.header_encode(s), '=?utf-8?b?wqTCosKkwqTCpMKmwqTCqMKkwqo=?=')
4950
4951 def test_body_encode(self):
4952 eq = self.assertEqual
4953 # Try a charset with QP body encoding
4954 c = Charset('iso-8859-1')
4955 eq('hello w=F6rld', c.body_encode('hello w\xf6rld'))
4956 # Try a charset with Base64 body encoding
4957 c = Charset('utf-8')
4958 eq('aGVsbG8gd29ybGQ=\n', c.body_encode(b'hello world'))
4959 # Try a charset with None body encoding
4960 c = Charset('us-ascii')
4961 eq('hello world', c.body_encode('hello world'))
4962 # Try the convert argument, where input codec != output codec
4963 c = Charset('euc-jp')
4964 # With apologies to Tokio Kikuchi ;)
4965 # XXX FIXME
4966 ## try:
4967 ## eq('\x1b$B5FCO;~IW\x1b(B',
4968 ## c.body_encode('\xb5\xc6\xc3\xcf\xbb\xfe\xc9\xd7'))
4969 ## eq('\xb5\xc6\xc3\xcf\xbb\xfe\xc9\xd7',
4970 ## c.body_encode('\xb5\xc6\xc3\xcf\xbb\xfe\xc9\xd7', False))
4971 ## except LookupError:
4972 ## # We probably don't have the Japanese codecs installed
4973 ## pass
4974 # Testing SF bug #625509, which we have to fake, since there are no
4975 # built-in encodings where the header encoding is QP but the body
4976 # encoding is not.
4977 from email import charset as CharsetModule
4978 CharsetModule.add_charset('fake', CharsetModule.QP, None, 'utf-8')
4979 c = Charset('fake')
4980 eq('hello world', c.body_encode('hello world'))
4981
4982 def test_unicode_charset_name(self):
4983 charset = Charset('us-ascii')
4984 self.assertEqual(str(charset), 'us-ascii')
4985 self.assertRaises(errors.CharsetError, Charset, 'asc\xffii')
4986
4987
4988
4989 # Test multilingual MIME headers.
4990 class TestHeader(TestEmailBase):
4991 def test_simple(self):
4992 eq = self.ndiffAssertEqual
4993 h = Header('Hello World!')
4994 eq(h.encode(), 'Hello World!')
4995 h.append(' Goodbye World!')
4996 eq(h.encode(), 'Hello World! Goodbye World!')
4997
4998 def test_simple_surprise(self):
4999 eq = self.ndiffAssertEqual
5000 h = Header('Hello World!')
5001 eq(h.encode(), 'Hello World!')
5002 h.append('Goodbye World!')
5003 eq(h.encode(), 'Hello World! Goodbye World!')
5004
5005 def test_header_needs_no_decoding(self):
5006 h = 'no decoding needed'
5007 self.assertEqual(decode_header(h), [(h, None)])
5008
5009 def test_long(self):
5010 h = Header("I am the very model of a modern Major-General; I've information vegetable, animal, and mineral; I know the kings of England, and I quote the fights historical from Marathon to Waterloo, in order categorical; I'm very well acquainted, too, with matters mathematical; I understand equations, both the simple and quadratical; about binomial theorem I'm teeming with a lot o' news, with many cheerful facts about the square of the hypotenuse.",
5011 maxlinelen=76)
5012 for l in h.encode(splitchars=' ').split('\n '):
5013 self.assertLessEqual(len(l), 76)
5014
5015 def test_multilingual(self):
5016 eq = self.ndiffAssertEqual
5017 g = Charset("iso-8859-1")
5018 cz = Charset("iso-8859-2")
5019 utf8 = Charset("utf-8")
5020 g_head = (b'Die Mieter treten hier ein werden mit einem '
5021 b'Foerderband komfortabel den Korridor entlang, '
5022 b'an s\xfcdl\xfcndischen Wandgem\xe4lden vorbei, '
5023 b'gegen die rotierenden Klingen bef\xf6rdert. ')
5024 cz_head = (b'Finan\xe8ni metropole se hroutily pod tlakem jejich '
5025 b'd\xf9vtipu.. ')
5026 utf8_head = ('\u6b63\u78ba\u306b\u8a00\u3046\u3068\u7ffb\u8a33\u306f'
5027 '\u3055\u308c\u3066\u3044\u307e\u305b\u3093\u3002\u4e00'
5028 '\u90e8\u306f\u30c9\u30a4\u30c4\u8a9e\u3067\u3059\u304c'
5029 '\u3001\u3042\u3068\u306f\u3067\u305f\u3089\u3081\u3067'
5030 '\u3059\u3002\u5b9f\u969b\u306b\u306f\u300cWenn ist das '
5031 'Nunstuck git und Slotermeyer? Ja! Beiherhund das Oder '
5032 'die Flipperwaldt gersput.\u300d\u3068\u8a00\u3063\u3066'
5033 '\u3044\u307e\u3059\u3002')
5034 h = Header(g_head, g)
5035 h.append(cz_head, cz)
5036 h.append(utf8_head, utf8)
5037 enc = h.encode(maxlinelen=76)
5038 eq(enc, """\
5039 =?iso-8859-1?q?Die_Mieter_treten_hier_ein_werden_mit_einem_Foerderband_kom?=
5040 =?iso-8859-1?q?fortabel_den_Korridor_entlang=2C_an_s=FCdl=FCndischen_Wand?=
5041 =?iso-8859-1?q?gem=E4lden_vorbei=2C_gegen_die_rotierenden_Klingen_bef=F6r?=
5042 =?iso-8859-1?q?dert=2E_?= =?iso-8859-2?q?Finan=E8ni_metropole_se_hroutily?=
5043 =?iso-8859-2?q?_pod_tlakem_jejich_d=F9vtipu=2E=2E_?= =?utf-8?b?5q2j56K6?=
5044 =?utf-8?b?44Gr6KiA44GG44Go57+76Kiz44Gv44GV44KM44Gm44GE44G+44Gb44KT44CC?=
5045 =?utf-8?b?5LiA6YOo44Gv44OJ44Kk44OE6Kqe44Gn44GZ44GM44CB44GC44Go44Gv44Gn?=
5046 =?utf-8?b?44Gf44KJ44KB44Gn44GZ44CC5a6f6Zqb44Gr44Gv44CMV2VubiBpc3QgZGFz?=
5047 =?utf-8?b?IE51bnN0dWNrIGdpdCB1bmQgU2xvdGVybWV5ZXI/IEphISBCZWloZXJodW5k?=
5048 =?utf-8?b?IGRhcyBPZGVyIGRpZSBGbGlwcGVyd2FsZHQgZ2Vyc3B1dC7jgI3jgajoqIA=?=
5049 =?utf-8?b?44Gj44Gm44GE44G+44GZ44CC?=""")
5050 decoded = decode_header(enc)
5051 eq(len(decoded), 3)
5052 eq(decoded[0], (g_head, 'iso-8859-1'))
5053 eq(decoded[1], (cz_head, 'iso-8859-2'))
5054 eq(decoded[2], (utf8_head.encode('utf-8'), 'utf-8'))
5055 ustr = str(h)
5056 eq(ustr,
5057 (b'Die Mieter treten hier ein werden mit einem Foerderband '
5058 b'komfortabel den Korridor entlang, an s\xc3\xbcdl\xc3\xbcndischen '
5059 b'Wandgem\xc3\xa4lden vorbei, gegen die rotierenden Klingen '
5060 b'bef\xc3\xb6rdert. Finan\xc4\x8dni metropole se hroutily pod '
5061 b'tlakem jejich d\xc5\xafvtipu.. \xe6\xad\xa3\xe7\xa2\xba\xe3\x81'
5062 b'\xab\xe8\xa8\x80\xe3\x81\x86\xe3\x81\xa8\xe7\xbf\xbb\xe8\xa8\xb3'
5063 b'\xe3\x81\xaf\xe3\x81\x95\xe3\x82\x8c\xe3\x81\xa6\xe3\x81\x84\xe3'
5064 b'\x81\xbe\xe3\x81\x9b\xe3\x82\x93\xe3\x80\x82\xe4\xb8\x80\xe9\x83'
5065 b'\xa8\xe3\x81\xaf\xe3\x83\x89\xe3\x82\xa4\xe3\x83\x84\xe8\xaa\x9e'
5066 b'\xe3\x81\xa7\xe3\x81\x99\xe3\x81\x8c\xe3\x80\x81\xe3\x81\x82\xe3'
5067 b'\x81\xa8\xe3\x81\xaf\xe3\x81\xa7\xe3\x81\x9f\xe3\x82\x89\xe3\x82'
5068 b'\x81\xe3\x81\xa7\xe3\x81\x99\xe3\x80\x82\xe5\xae\x9f\xe9\x9a\x9b'
5069 b'\xe3\x81\xab\xe3\x81\xaf\xe3\x80\x8cWenn ist das Nunstuck git '
5070 b'und Slotermeyer? Ja! Beiherhund das Oder die Flipperwaldt '
5071 b'gersput.\xe3\x80\x8d\xe3\x81\xa8\xe8\xa8\x80\xe3\x81\xa3\xe3\x81'
5072 b'\xa6\xe3\x81\x84\xe3\x81\xbe\xe3\x81\x99\xe3\x80\x82'
5073 ).decode('utf-8'))
5074 # Test make_header()
5075 newh = make_header(decode_header(enc))
5076 eq(newh, h)
5077
5078 def test_empty_header_encode(self):
5079 h = Header()
5080 self.assertEqual(h.encode(), '')
5081
5082 def test_header_ctor_default_args(self):
5083 eq = self.ndiffAssertEqual
5084 h = Header()
5085 eq(h, '')
5086 h.append('foo', Charset('iso-8859-1'))
5087 eq(h, 'foo')
5088
5089 def test_explicit_maxlinelen(self):
5090 eq = self.ndiffAssertEqual
5091 hstr = ('A very long line that must get split to something other '
5092 'than at the 76th character boundary to test the non-default '
5093 'behavior')
5094 h = Header(hstr)
5095 eq(h.encode(), '''\
5096 A very long line that must get split to something other than at the 76th
5097 character boundary to test the non-default behavior''')
5098 eq(str(h), hstr)
5099 h = Header(hstr, header_name='Subject')
5100 eq(h.encode(), '''\
5101 A very long line that must get split to something other than at the
5102 76th character boundary to test the non-default behavior''')
5103 eq(str(h), hstr)
5104 h = Header(hstr, maxlinelen=1024, header_name='Subject')
5105 eq(h.encode(), hstr)
5106 eq(str(h), hstr)
5107
5108 def test_quopri_splittable(self):
5109 eq = self.ndiffAssertEqual
5110 h = Header(charset='iso-8859-1', maxlinelen=20)
5111 x = 'xxxx ' * 20
5112 h.append(x)
5113 s = h.encode()
5114 eq(s, """\
5115 =?iso-8859-1?q?xxx?=
5116 =?iso-8859-1?q?x_?=
5117 =?iso-8859-1?q?xx?=
5118 =?iso-8859-1?q?xx?=
5119 =?iso-8859-1?q?_x?=
5120 =?iso-8859-1?q?xx?=
5121 =?iso-8859-1?q?x_?=
5122 =?iso-8859-1?q?xx?=
5123 =?iso-8859-1?q?xx?=
5124 =?iso-8859-1?q?_x?=
5125 =?iso-8859-1?q?xx?=
5126 =?iso-8859-1?q?x_?=
5127 =?iso-8859-1?q?xx?=
5128 =?iso-8859-1?q?xx?=
5129 =?iso-8859-1?q?_x?=
5130 =?iso-8859-1?q?xx?=
5131 =?iso-8859-1?q?x_?=
5132 =?iso-8859-1?q?xx?=
5133 =?iso-8859-1?q?xx?=
5134 =?iso-8859-1?q?_x?=
5135 =?iso-8859-1?q?xx?=
5136 =?iso-8859-1?q?x_?=
5137 =?iso-8859-1?q?xx?=
5138 =?iso-8859-1?q?xx?=
5139 =?iso-8859-1?q?_x?=
5140 =?iso-8859-1?q?xx?=
5141 =?iso-8859-1?q?x_?=
5142 =?iso-8859-1?q?xx?=
5143 =?iso-8859-1?q?xx?=
5144 =?iso-8859-1?q?_x?=
5145 =?iso-8859-1?q?xx?=
5146 =?iso-8859-1?q?x_?=
5147 =?iso-8859-1?q?xx?=
5148 =?iso-8859-1?q?xx?=
5149 =?iso-8859-1?q?_x?=
5150 =?iso-8859-1?q?xx?=
5151 =?iso-8859-1?q?x_?=
5152 =?iso-8859-1?q?xx?=
5153 =?iso-8859-1?q?xx?=
5154 =?iso-8859-1?q?_x?=
5155 =?iso-8859-1?q?xx?=
5156 =?iso-8859-1?q?x_?=
5157 =?iso-8859-1?q?xx?=
5158 =?iso-8859-1?q?xx?=
5159 =?iso-8859-1?q?_x?=
5160 =?iso-8859-1?q?xx?=
5161 =?iso-8859-1?q?x_?=
5162 =?iso-8859-1?q?xx?=
5163 =?iso-8859-1?q?xx?=
5164 =?iso-8859-1?q?_?=""")
5165 eq(x, str(make_header(decode_header(s))))
5166 h = Header(charset='iso-8859-1', maxlinelen=40)
5167 h.append('xxxx ' * 20)
5168 s = h.encode()
5169 eq(s, """\
5170 =?iso-8859-1?q?xxxx_xxxx_xxxx_xxxx_xxx?=
5171 =?iso-8859-1?q?x_xxxx_xxxx_xxxx_xxxx_?=
5172 =?iso-8859-1?q?xxxx_xxxx_xxxx_xxxx_xx?=
5173 =?iso-8859-1?q?xx_xxxx_xxxx_xxxx_xxxx?=
5174 =?iso-8859-1?q?_xxxx_xxxx_?=""")
5175 eq(x, str(make_header(decode_header(s))))
5176
5177 def test_base64_splittable(self):
5178 eq = self.ndiffAssertEqual
5179 h = Header(charset='koi8-r', maxlinelen=20)
5180 x = 'xxxx ' * 20
5181 h.append(x)
5182 s = h.encode()
5183 eq(s, """\
5184 =?koi8-r?b?eHh4?=
5185 =?koi8-r?b?eCB4?=
5186 =?koi8-r?b?eHh4?=
5187 =?koi8-r?b?IHh4?=
5188 =?koi8-r?b?eHgg?=
5189 =?koi8-r?b?eHh4?=
5190 =?koi8-r?b?eCB4?=
5191 =?koi8-r?b?eHh4?=
5192 =?koi8-r?b?IHh4?=
5193 =?koi8-r?b?eHgg?=
5194 =?koi8-r?b?eHh4?=
5195 =?koi8-r?b?eCB4?=
5196 =?koi8-r?b?eHh4?=
5197 =?koi8-r?b?IHh4?=
5198 =?koi8-r?b?eHgg?=
5199 =?koi8-r?b?eHh4?=
5200 =?koi8-r?b?eCB4?=
5201 =?koi8-r?b?eHh4?=
5202 =?koi8-r?b?IHh4?=
5203 =?koi8-r?b?eHgg?=
5204 =?koi8-r?b?eHh4?=
5205 =?koi8-r?b?eCB4?=
5206 =?koi8-r?b?eHh4?=
5207 =?koi8-r?b?IHh4?=
5208 =?koi8-r?b?eHgg?=
5209 =?koi8-r?b?eHh4?=
5210 =?koi8-r?b?eCB4?=
5211 =?koi8-r?b?eHh4?=
5212 =?koi8-r?b?IHh4?=
5213 =?koi8-r?b?eHgg?=
5214 =?koi8-r?b?eHh4?=
5215 =?koi8-r?b?eCB4?=
5216 =?koi8-r?b?eHh4?=
5217 =?koi8-r?b?IA==?=""")
5218 eq(x, str(make_header(decode_header(s))))
5219 h = Header(charset='koi8-r', maxlinelen=40)
5220 h.append(x)
5221 s = h.encode()
5222 eq(s, """\
5223 =?koi8-r?b?eHh4eCB4eHh4IHh4eHggeHh4?=
5224 =?koi8-r?b?eCB4eHh4IHh4eHggeHh4eCB4?=
5225 =?koi8-r?b?eHh4IHh4eHggeHh4eCB4eHh4?=
5226 =?koi8-r?b?IHh4eHggeHh4eCB4eHh4IHh4?=
5227 =?koi8-r?b?eHggeHh4eCB4eHh4IHh4eHgg?=
5228 =?koi8-r?b?eHh4eCB4eHh4IA==?=""")
5229 eq(x, str(make_header(decode_header(s))))
5230
5231 def test_us_ascii_header(self):
5232 eq = self.assertEqual
5233 s = 'hello'
5234 x = decode_header(s)
5235 eq(x, [('hello', None)])
5236 h = make_header(x)
5237 eq(s, h.encode())
5238
5239 def test_string_charset(self):
5240 eq = self.assertEqual
5241 h = Header()
5242 h.append('hello', 'iso-8859-1')
5243 eq(h, 'hello')
5244
5245 ## def test_unicode_error(self):
5246 ## raises = self.assertRaises
5247 ## raises(UnicodeError, Header, u'[P\xf6stal]', 'us-ascii')
5248 ## raises(UnicodeError, Header, '[P\xf6stal]', 'us-ascii')
5249 ## h = Header()
5250 ## raises(UnicodeError, h.append, u'[P\xf6stal]', 'us-ascii')
5251 ## raises(UnicodeError, h.append, '[P\xf6stal]', 'us-ascii')
5252 ## raises(UnicodeError, Header, u'\u83ca\u5730\u6642\u592b', 'iso-8859-1')
5253
5254 def test_utf8_shortest(self):
5255 eq = self.assertEqual
5256 h = Header('p\xf6stal', 'utf-8')
5257 eq(h.encode(), '=?utf-8?q?p=C3=B6stal?=')
5258 h = Header('\u83ca\u5730\u6642\u592b', 'utf-8')
5259 eq(h.encode(), '=?utf-8?b?6I+K5Zyw5pmC5aSr?=')
5260
5261 def test_bad_8bit_header(self):
5262 raises = self.assertRaises
5263 eq = self.assertEqual
5264 x = b'Ynwp4dUEbay Auction Semiar- No Charge \x96 Earn Big'
5265 raises(UnicodeError, Header, x)
5266 h = Header()
5267 raises(UnicodeError, h.append, x)
5268 e = x.decode('utf-8', 'replace')
5269 eq(str(Header(x, errors='replace')), e)
5270 h.append(x, errors='replace')
5271 eq(str(h), e)
5272
5273 def test_escaped_8bit_header(self):
5274 x = b'Ynwp4dUEbay Auction Semiar- No Charge \x96 Earn Big'
5275 e = x.decode('ascii', 'surrogateescape')
5276 h = Header(e, charset=email.charset.UNKNOWN8BIT)
5277 self.assertEqual(str(h),
5278 'Ynwp4dUEbay Auction Semiar- No Charge \uFFFD Earn Big')
5279 self.assertEqual(email.header.decode_header(h), [(x, 'unknown-8bit')])
5280
5281 def test_header_handles_binary_unknown8bit(self):
5282 x = b'Ynwp4dUEbay Auction Semiar- No Charge \x96 Earn Big'
5283 h = Header(x, charset=email.charset.UNKNOWN8BIT)
5284 self.assertEqual(str(h),
5285 'Ynwp4dUEbay Auction Semiar- No Charge \uFFFD Earn Big')
5286 self.assertEqual(email.header.decode_header(h), [(x, 'unknown-8bit')])
5287
5288 def test_make_header_handles_binary_unknown8bit(self):
5289 x = b'Ynwp4dUEbay Auction Semiar- No Charge \x96 Earn Big'
5290 h = Header(x, charset=email.charset.UNKNOWN8BIT)
5291 h2 = email.header.make_header(email.header.decode_header(h))
5292 self.assertEqual(str(h2),
5293 'Ynwp4dUEbay Auction Semiar- No Charge \uFFFD Earn Big')
5294 self.assertEqual(email.header.decode_header(h2), [(x, 'unknown-8bit')])
5295
5296 def test_modify_returned_list_does_not_change_header(self):
5297 h = Header('test')
5298 chunks = email.header.decode_header(h)
5299 chunks.append(('ascii', 'test2'))
5300 self.assertEqual(str(h), 'test')
5301
5302 def test_encoded_adjacent_nonencoded(self):
5303 eq = self.assertEqual
5304 h = Header()
5305 h.append('hello', 'iso-8859-1')
5306 h.append('world')
5307 s = h.encode()
5308 eq(s, '=?iso-8859-1?q?hello?= world')
5309 h = make_header(decode_header(s))
5310 eq(h.encode(), s)
5311
5312 def test_whitespace_keeper(self):
5313 eq = self.assertEqual
5314 s = 'Subject: =?koi8-r?b?8NLP18XSy8EgzsEgxsnOwczYztk=?= =?koi8-r?q?=CA?= zz.'
5315 parts = decode_header(s)
5316 eq(parts, [(b'Subject: ', None), (b'\xf0\xd2\xcf\xd7\xc5\xd2\xcb\xc1 \xce\xc1 \xc6\xc9\xce\xc1\xcc\xd8\xce\xd9\xca', 'koi8-r'), (b' zz.', None)])
5317 hdr = make_header(parts)
5318 eq(hdr.encode(),
5319 'Subject: =?koi8-r?b?8NLP18XSy8EgzsEgxsnOwczYztnK?= zz.')
5320
5321 def test_broken_base64_header(self):
5322 raises = self.assertRaises
5323 s = 'Subject: =?EUC-KR?B?CSixpLDtKSC/7Liuvsax4iC6uLmwMcijIKHaILzSwd/H0SC8+LCjwLsgv7W/+Mj3I ?='
5324 raises(errors.HeaderParseError, decode_header, s)
5325
5326 def test_shift_jis_charset(self):
5327 h = Header('文', charset='shift_jis')
5328 self.assertEqual(h.encode(), '=?iso-2022-jp?b?GyRCSjgbKEI=?=')
5329
5330 def test_flatten_header_with_no_value(self):
5331 # Issue 11401 (regression from email 4.x) Note that the space after
5332 # the header doesn't reflect the input, but this is also the way
5333 # email 4.x behaved. At some point it would be nice to fix that.
5334 msg = email.message_from_string("EmptyHeader:")
5335 self.assertEqual(str(msg), "EmptyHeader: \n\n")
5336
5337 def test_encode_preserves_leading_ws_on_value(self):
5338 msg = Message()
5339 msg['SomeHeader'] = ' value with leading ws'
5340 self.assertEqual(str(msg), "SomeHeader: value with leading ws\n\n")
5341
5342 def test_whitespace_header(self):
5343 self.assertEqual(Header(' ').encode(), ' ')
5344
5345
5346
5347 # Test RFC 2231 header parameters (en/de)coding
5348 class TestRFC2231(TestEmailBase):
5349
5350 # test_headerregistry.TestContentTypeHeader.rfc2231_encoded_with_double_quotes
5351 # test_headerregistry.TestContentTypeHeader.rfc2231_single_quote_inside_double_quotes
5352 def test_get_param(self):
5353 eq = self.assertEqual
5354 msg = self._msgobj('msg_29.txt')
5355 eq(msg.get_param('title'),
5356 ('us-ascii', 'en', 'This is even more ***fun*** isn\'t it!'))
5357 eq(msg.get_param('title', unquote=False),
5358 ('us-ascii', 'en', '"This is even more ***fun*** isn\'t it!"'))
5359
5360 def test_set_param(self):
5361 eq = self.ndiffAssertEqual
5362 msg = Message()
5363 msg.set_param('title', 'This is even more ***fun*** isn\'t it!',
5364 charset='us-ascii')
5365 eq(msg.get_param('title'),
5366 ('us-ascii', '', 'This is even more ***fun*** isn\'t it!'))
5367 msg.set_param('title', 'This is even more ***fun*** isn\'t it!',
5368 charset='us-ascii', language='en')
5369 eq(msg.get_param('title'),
5370 ('us-ascii', 'en', 'This is even more ***fun*** isn\'t it!'))
5371 msg = self._msgobj('msg_01.txt')
5372 msg.set_param('title', 'This is even more ***fun*** isn\'t it!',
5373 charset='us-ascii', language='en')
5374 eq(msg.as_string(maxheaderlen=78), """\
5375 Return-Path: <[email protected]>
5376 Delivered-To: [email protected]
5377 Received: by mail.zzz.org (Postfix, from userid 889)
5378 \tid 27CEAD38CC; Fri, 4 May 2001 14:05:44 -0400 (EDT)
5379 MIME-Version: 1.0
5380 Content-Transfer-Encoding: 7bit
5381 Message-ID: <[email protected]>
5382 From: [email protected] (John X. Doe)
5383 To: [email protected]
5384 Subject: This is a test message
5385 Date: Fri, 4 May 2001 14:05:44 -0400
5386 Content-Type: text/plain; charset=us-ascii;
5387 title*=us-ascii'en'This%20is%20even%20more%20%2A%2A%2Afun%2A%2A%2A%20isn%27t%20it%21
5388
5389
5390 Hi,
5391
5392 Do you like this message?
5393
5394 -Me
5395 """)
5396
5397 def test_set_param_requote(self):
5398 msg = Message()
5399 msg.set_param('title', 'foo')
5400 self.assertEqual(msg['content-type'], 'text/plain; title="foo"')
5401 msg.set_param('title', 'bar', requote=False)
5402 self.assertEqual(msg['content-type'], 'text/plain; title=bar')
5403 # tspecial is still quoted.
5404 msg.set_param('title', "(bar)bell", requote=False)
5405 self.assertEqual(msg['content-type'], 'text/plain; title="(bar)bell"')
5406
5407 def test_del_param(self):
5408 eq = self.ndiffAssertEqual
5409 msg = self._msgobj('msg_01.txt')
5410 msg.set_param('foo', 'bar', charset='us-ascii', language='en')
5411 msg.set_param('title', 'This is even more ***fun*** isn\'t it!',
5412 charset='us-ascii', language='en')
5413 msg.del_param('foo', header='Content-Type')
5414 eq(msg.as_string(maxheaderlen=78), """\
5415 Return-Path: <[email protected]>
5416 Delivered-To: [email protected]
5417 Received: by mail.zzz.org (Postfix, from userid 889)
5418 \tid 27CEAD38CC; Fri, 4 May 2001 14:05:44 -0400 (EDT)
5419 MIME-Version: 1.0
5420 Content-Transfer-Encoding: 7bit
5421 Message-ID: <[email protected]>
5422 From: [email protected] (John X. Doe)
5423 To: [email protected]
5424 Subject: This is a test message
5425 Date: Fri, 4 May 2001 14:05:44 -0400
5426 Content-Type: text/plain; charset="us-ascii";
5427 title*=us-ascii'en'This%20is%20even%20more%20%2A%2A%2Afun%2A%2A%2A%20isn%27t%20it%21
5428
5429
5430 Hi,
5431
5432 Do you like this message?
5433
5434 -Me
5435 """)
5436
5437 # test_headerregistry.TestContentTypeHeader.rfc2231_encoded_charset
5438 # I changed the charset name, though, because the one in the file isn't
5439 # a legal charset name. Should add a test for an illegal charset.
5440 def test_rfc2231_get_content_charset(self):
5441 eq = self.assertEqual
5442 msg = self._msgobj('msg_32.txt')
5443 eq(msg.get_content_charset(), 'us-ascii')
5444
5445 # test_headerregistry.TestContentTypeHeader.rfc2231_encoded_no_double_quotes
5446 def test_rfc2231_parse_rfc_quoting(self):
5447 m = textwrap.dedent('''\
5448 Content-Disposition: inline;
5449 \tfilename*0*=''This%20is%20even%20more%20;
5450 \tfilename*1*=%2A%2A%2Afun%2A%2A%2A%20;
5451 \tfilename*2="is it not.pdf"
5452
5453 ''')
5454 msg = email.message_from_string(m)
5455 self.assertEqual(msg.get_filename(),
5456 'This is even more ***fun*** is it not.pdf')
5457 self.assertEqual(m, msg.as_string())
5458
5459 # test_headerregistry.TestContentTypeHeader.rfc2231_encoded_with_double_quotes
5460 def test_rfc2231_parse_extra_quoting(self):
5461 m = textwrap.dedent('''\
5462 Content-Disposition: inline;
5463 \tfilename*0*="''This%20is%20even%20more%20";
5464 \tfilename*1*="%2A%2A%2Afun%2A%2A%2A%20";
5465 \tfilename*2="is it not.pdf"
5466
5467 ''')
5468 msg = email.message_from_string(m)
5469 self.assertEqual(msg.get_filename(),
5470 'This is even more ***fun*** is it not.pdf')
5471 self.assertEqual(m, msg.as_string())
5472
5473 # test_headerregistry.TestContentTypeHeader.rfc2231_no_language_or_charset
5474 # but new test uses *0* because otherwise lang/charset is not valid.
5475 # test_headerregistry.TestContentTypeHeader.rfc2231_segmented_normal_values
5476 def test_rfc2231_no_language_or_charset(self):
5477 m = '''\
5478 Content-Transfer-Encoding: 8bit
5479 Content-Disposition: inline; filename="file____C__DOCUMENTS_20AND_20SETTINGS_FABIEN_LOCAL_20SETTINGS_TEMP_nsmail.htm"
5480 Content-Type: text/html; NAME*0=file____C__DOCUMENTS_20AND_20SETTINGS_FABIEN_LOCAL_20SETTINGS_TEM; NAME*1=P_nsmail.htm
5481
5482 '''
5483 msg = email.message_from_string(m)
5484 param = msg.get_param('NAME')
5485 self.assertNotIsInstance(param, tuple)
5486 self.assertEqual(
5487 param,
5488 'file____C__DOCUMENTS_20AND_20SETTINGS_FABIEN_LOCAL_20SETTINGS_TEMP_nsmail.htm')
5489
5490 # test_headerregistry.TestContentTypeHeader.rfc2231_encoded_no_charset
5491 def test_rfc2231_no_language_or_charset_in_filename(self):
5492 m = '''\
5493 Content-Disposition: inline;
5494 \tfilename*0*="''This%20is%20even%20more%20";
5495 \tfilename*1*="%2A%2A%2Afun%2A%2A%2A%20";
5496 \tfilename*2="is it not.pdf"
5497
5498 '''
5499 msg = email.message_from_string(m)
5500 self.assertEqual(msg.get_filename(),
5501 'This is even more ***fun*** is it not.pdf')
5502
5503 # Duplicate of previous test?
5504 def test_rfc2231_no_language_or_charset_in_filename_encoded(self):
5505 m = '''\
5506 Content-Disposition: inline;
5507 \tfilename*0*="''This%20is%20even%20more%20";
5508 \tfilename*1*="%2A%2A%2Afun%2A%2A%2A%20";
5509 \tfilename*2="is it not.pdf"
5510
5511 '''
5512 msg = email.message_from_string(m)
5513 self.assertEqual(msg.get_filename(),
5514 'This is even more ***fun*** is it not.pdf')
5515
5516 # test_headerregistry.TestContentTypeHeader.rfc2231_partly_encoded,
5517 # but the test below is wrong (the first part should be decoded).
5518 def test_rfc2231_partly_encoded(self):
5519 m = '''\
5520 Content-Disposition: inline;
5521 \tfilename*0="''This%20is%20even%20more%20";
5522 \tfilename*1*="%2A%2A%2Afun%2A%2A%2A%20";
5523 \tfilename*2="is it not.pdf"
5524
5525 '''
5526 msg = email.message_from_string(m)
5527 self.assertEqual(
5528 msg.get_filename(),
5529 'This%20is%20even%20more%20***fun*** is it not.pdf')
5530
5531 def test_rfc2231_partly_nonencoded(self):
5532 m = '''\
5533 Content-Disposition: inline;
5534 \tfilename*0="This%20is%20even%20more%20";
5535 \tfilename*1="%2A%2A%2Afun%2A%2A%2A%20";
5536 \tfilename*2="is it not.pdf"
5537
5538 '''
5539 msg = email.message_from_string(m)
5540 self.assertEqual(
5541 msg.get_filename(),
5542 'This%20is%20even%20more%20%2A%2A%2Afun%2A%2A%2A%20is it not.pdf')
5543
5544 def test_rfc2231_no_language_or_charset_in_boundary(self):
5545 m = '''\
5546 Content-Type: multipart/alternative;
5547 \tboundary*0*="''This%20is%20even%20more%20";
5548 \tboundary*1*="%2A%2A%2Afun%2A%2A%2A%20";
5549 \tboundary*2="is it not.pdf"
5550
5551 '''
5552 msg = email.message_from_string(m)
5553 self.assertEqual(msg.get_boundary(),
5554 'This is even more ***fun*** is it not.pdf')
5555
5556 def test_rfc2231_no_language_or_charset_in_charset(self):
5557 # This is a nonsensical charset value, but tests the code anyway
5558 m = '''\
5559 Content-Type: text/plain;
5560 \tcharset*0*="This%20is%20even%20more%20";
5561 \tcharset*1*="%2A%2A%2Afun%2A%2A%2A%20";
5562 \tcharset*2="is it not.pdf"
5563
5564 '''
5565 msg = email.message_from_string(m)
5566 self.assertEqual(msg.get_content_charset(),
5567 'this is even more ***fun*** is it not.pdf')
5568
5569 # test_headerregistry.TestContentTypeHeader.rfc2231_unknown_charset_treated_as_ascii
5570 def test_rfc2231_bad_encoding_in_filename(self):
5571 m = '''\
5572 Content-Disposition: inline;
5573 \tfilename*0*="bogus'xx'This%20is%20even%20more%20";
5574 \tfilename*1*="%2A%2A%2Afun%2A%2A%2A%20";
5575 \tfilename*2="is it not.pdf"
5576
5577 '''
5578 msg = email.message_from_string(m)
5579 self.assertEqual(msg.get_filename(),
5580 'This is even more ***fun*** is it not.pdf')
5581
5582 def test_rfc2231_bad_encoding_in_charset(self):
5583 m = """\
5584 Content-Type: text/plain; charset*=bogus''utf-8%E2%80%9D
5585
5586 """
5587 msg = email.message_from_string(m)
5588 # This should return None because non-ascii characters in the charset
5589 # are not allowed.
5590 self.assertEqual(msg.get_content_charset(), None)
5591
5592 def test_rfc2231_bad_character_in_charset(self):
5593 m = """\
5594 Content-Type: text/plain; charset*=ascii''utf-8%E2%80%9D
5595
5596 """
5597 msg = email.message_from_string(m)
5598 # This should return None because non-ascii characters in the charset
5599 # are not allowed.
5600 self.assertEqual(msg.get_content_charset(), None)
5601
5602 def test_rfc2231_bad_character_in_filename(self):
5603 m = '''\
5604 Content-Disposition: inline;
5605 \tfilename*0*="ascii'xx'This%20is%20even%20more%20";
5606 \tfilename*1*="%2A%2A%2Afun%2A%2A%2A%20";
5607 \tfilename*2*="is it not.pdf%E2"
5608
5609 '''
5610 msg = email.message_from_string(m)
5611 self.assertEqual(msg.get_filename(),
5612 'This is even more ***fun*** is it not.pdf\ufffd')
5613
5614 def test_rfc2231_unknown_encoding(self):
5615 m = """\
5616 Content-Transfer-Encoding: 8bit
5617 Content-Disposition: inline; filename*=X-UNKNOWN''myfile.txt
5618
5619 """
5620 msg = email.message_from_string(m)
5621 self.assertEqual(msg.get_filename(), 'myfile.txt')
5622
5623 def test_rfc2231_bad_character_in_encoding(self):
5624 m = """\
5625 Content-Transfer-Encoding: 8bit
5626 Content-Disposition: inline; filename*=utf-8\udce2\udc80\udc9d''myfile.txt
5627
5628 """
5629 msg = email.message_from_string(m)
5630 self.assertEqual(msg.get_filename(), 'myfile.txt')
5631
5632 def test_rfc2231_single_tick_in_filename_extended(self):
5633 eq = self.assertEqual
5634 m = """\
5635 Content-Type: application/x-foo;
5636 \tname*0*=\"Frank's\"; name*1*=\" Document\"
5637
5638 """
5639 msg = email.message_from_string(m)
5640 charset, language, s = msg.get_param('name')
5641 eq(charset, None)
5642 eq(language, None)
5643 eq(s, "Frank's Document")
5644
5645 # test_headerregistry.TestContentTypeHeader.rfc2231_single_quote_inside_double_quotes
5646 def test_rfc2231_single_tick_in_filename(self):
5647 m = """\
5648 Content-Type: application/x-foo; name*0=\"Frank's\"; name*1=\" Document\"
5649
5650 """
5651 msg = email.message_from_string(m)
5652 param = msg.get_param('name')
5653 self.assertNotIsInstance(param, tuple)
5654 self.assertEqual(param, "Frank's Document")
5655
5656 def test_rfc2231_missing_tick(self):
5657 m = '''\
5658 Content-Disposition: inline;
5659 \tfilename*0*="'This%20is%20broken";
5660 '''
5661 msg = email.message_from_string(m)
5662 self.assertEqual(
5663 msg.get_filename(),
5664 "'This is broken")
5665
5666 def test_rfc2231_missing_tick_with_encoded_non_ascii(self):
5667 m = '''\
5668 Content-Disposition: inline;
5669 \tfilename*0*="'This%20is%E2broken";
5670 '''
5671 msg = email.message_from_string(m)
5672 self.assertEqual(
5673 msg.get_filename(),
5674 "'This is\ufffdbroken")
5675
5676 # test_headerregistry.TestContentTypeHeader.rfc2231_single_quote_in_value_with_charset_and_lang
5677 def test_rfc2231_tick_attack_extended(self):
5678 eq = self.assertEqual
5679 m = """\
5680 Content-Type: application/x-foo;
5681 \tname*0*=\"us-ascii'en-us'Frank's\"; name*1*=\" Document\"
5682
5683 """
5684 msg = email.message_from_string(m)
5685 charset, language, s = msg.get_param('name')
5686 eq(charset, 'us-ascii')
5687 eq(language, 'en-us')
5688 eq(s, "Frank's Document")
5689
5690 # test_headerregistry.TestContentTypeHeader.rfc2231_single_quote_in_non_encoded_value
5691 def test_rfc2231_tick_attack(self):
5692 m = """\
5693 Content-Type: application/x-foo;
5694 \tname*0=\"us-ascii'en-us'Frank's\"; name*1=\" Document\"
5695
5696 """
5697 msg = email.message_from_string(m)
5698 param = msg.get_param('name')
5699 self.assertNotIsInstance(param, tuple)
5700 self.assertEqual(param, "us-ascii'en-us'Frank's Document")
5701
5702 # test_headerregistry.TestContentTypeHeader.rfc2231_single_quotes_inside_quotes
5703 def test_rfc2231_no_extended_values(self):
5704 eq = self.assertEqual
5705 m = """\
5706 Content-Type: application/x-foo; name=\"Frank's Document\"
5707
5708 """
5709 msg = email.message_from_string(m)
5710 eq(msg.get_param('name'), "Frank's Document")
5711
5712 # test_headerregistry.TestContentTypeHeader.rfc2231_encoded_then_unencoded_segments
5713 def test_rfc2231_encoded_then_unencoded_segments(self):
5714 eq = self.assertEqual
5715 m = """\
5716 Content-Type: application/x-foo;
5717 \tname*0*=\"us-ascii'en-us'My\";
5718 \tname*1=\" Document\";
5719 \tname*2*=\" For You\"
5720
5721 """
5722 msg = email.message_from_string(m)
5723 charset, language, s = msg.get_param('name')
5724 eq(charset, 'us-ascii')
5725 eq(language, 'en-us')
5726 eq(s, 'My Document For You')
5727
5728 # test_headerregistry.TestContentTypeHeader.rfc2231_unencoded_then_encoded_segments
5729 # test_headerregistry.TestContentTypeHeader.rfc2231_quoted_unencoded_then_encoded_segments
5730 def test_rfc2231_unencoded_then_encoded_segments(self):
5731 eq = self.assertEqual
5732 m = """\
5733 Content-Type: application/x-foo;
5734 \tname*0=\"us-ascii'en-us'My\";
5735 \tname*1*=\" Document\";
5736 \tname*2*=\" For You\"
5737
5738 """
5739 msg = email.message_from_string(m)
5740 charset, language, s = msg.get_param('name')
5741 eq(charset, 'us-ascii')
5742 eq(language, 'en-us')
5743 eq(s, 'My Document For You')
5744
5745 def test_should_not_hang_on_invalid_ew_messages(self):
5746 messages = ["""From: [email protected]
5747 To: [email protected]
5748 Bad-Header:
5749 =?us-ascii?Q?LCSwrV11+IB0rSbSker+M9vWR7wEDSuGqmHD89Gt=ea0nJFSaiz4vX3XMJPT4vrE?=
5750 =?us-ascii?Q?xGUZeOnp0o22pLBB7CYLH74Js=wOlK6Tfru2U47qR?=
5751 =?us-ascii?Q?72OfyEY2p2=2FrA9xNFyvH+fBTCmazxwzF8nGkK6D?=
5752
5753 Hello!
5754 """, """From: ����� �������� <xxx@xxx>
5755 To: "xxx" <xxx@xxx>
5756 Subject: ��� ���������� ����� ����� � ��������� �� ����
5757 MIME-Version: 1.0
5758 Content-Type: text/plain; charset="windows-1251";
5759 Content-Transfer-Encoding: 8bit
5760
5761 �� ����� � ���� ������ ��� ��������
5762 """]
5763 for m in messages:
5764 with self.subTest(m=m):
5765 msg = email.message_from_string(m)
5766
5767
5768 # Tests to ensure that signed parts of an email are completely preserved, as
5769 # required by RFC1847 section 2.1. Note that these are incomplete, because the
5770 # email package does not currently always preserve the body. See issue 1670765.
5771 class TestSigned(TestEmailBase):
5772
5773 def _msg_and_obj(self, filename):
5774 with openfile(filename, encoding="utf-8") as fp:
5775 original = fp.read()
5776 msg = email.message_from_string(original)
5777 return original, msg
5778
5779 def _signed_parts_eq(self, original, result):
5780 # Extract the first mime part of each message
5781 import re
5782 repart = re.compile(r'^--([^\n]+)\n(.*?)\n--\1$', re.S | re.M)
5783 inpart = repart.search(original).group(2)
5784 outpart = repart.search(result).group(2)
5785 self.assertEqual(outpart, inpart)
5786
5787 def test_long_headers_as_string(self):
5788 original, msg = self._msg_and_obj('msg_45.txt')
5789 result = msg.as_string()
5790 self._signed_parts_eq(original, result)
5791
5792 def test_long_headers_as_string_maxheaderlen(self):
5793 original, msg = self._msg_and_obj('msg_45.txt')
5794 result = msg.as_string(maxheaderlen=60)
5795 self._signed_parts_eq(original, result)
5796
5797 def test_long_headers_flatten(self):
5798 original, msg = self._msg_and_obj('msg_45.txt')
5799 fp = StringIO()
5800 Generator(fp).flatten(msg)
5801 result = fp.getvalue()
5802 self._signed_parts_eq(original, result)
5803
5804 class TestHeaderRegistry(TestEmailBase):
5805 # See issue gh-93010.
5806 def test_HeaderRegistry(self):
5807 reg = HeaderRegistry()
5808 a = reg('Content-Disposition', 'attachment; 0*00="foo"')
5809 self.assertIsInstance(a.defects[0], errors.InvalidHeaderDefect)
5810
5811 if __name__ == '__main__':
5812 unittest.main()