Debian Codegraph @

Lib/test/test_email/test_email.py

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