PageRenderTime 71ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/lib-python/2.7/email/test/test_email.py

https://bitbucket.org/varialus/jyjy
Python | 3529 lines | 3431 code | 43 blank | 55 comment | 9 complexity | 365340ec651367d3cf81fdff842ea2a4 MD5 | raw file
  1. # Copyright (C) 2001-2010 Python Software Foundation
  2. # Contact: email-sig@python.org
  3. # email package unit tests
  4. import os
  5. import sys
  6. import time
  7. import base64
  8. import difflib
  9. import unittest
  10. import warnings
  11. from cStringIO import StringIO
  12. import email
  13. from email.Charset import Charset
  14. from email.Header import Header, decode_header, make_header
  15. from email.Parser import Parser, HeaderParser
  16. from email.Generator import Generator, DecodedGenerator
  17. from email.Message import Message
  18. from email.MIMEAudio import MIMEAudio
  19. from email.MIMEText import MIMEText
  20. from email.MIMEImage import MIMEImage
  21. from email.MIMEBase import MIMEBase
  22. from email.MIMEMessage import MIMEMessage
  23. from email.MIMEMultipart import MIMEMultipart
  24. from email import Utils
  25. from email import Errors
  26. from email import Encoders
  27. from email import Iterators
  28. from email import base64MIME
  29. from email import quopriMIME
  30. from test.test_support import findfile, run_unittest
  31. from email.test import __file__ as landmark
  32. NL = '\n'
  33. EMPTYSTRING = ''
  34. SPACE = ' '
  35. def openfile(filename, mode='r'):
  36. path = os.path.join(os.path.dirname(landmark), 'data', filename)
  37. return open(path, mode)
  38. # Base test class
  39. class TestEmailBase(unittest.TestCase):
  40. def ndiffAssertEqual(self, first, second):
  41. """Like assertEqual except use ndiff for readable output."""
  42. if first != second:
  43. sfirst = str(first)
  44. ssecond = str(second)
  45. diff = difflib.ndiff(sfirst.splitlines(), ssecond.splitlines())
  46. fp = StringIO()
  47. print >> fp, NL, NL.join(diff)
  48. raise self.failureException, fp.getvalue()
  49. def _msgobj(self, filename):
  50. fp = openfile(findfile(filename))
  51. try:
  52. msg = email.message_from_file(fp)
  53. finally:
  54. fp.close()
  55. return msg
  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'), ['ccc@zzz.org', 'ddd@zzz.org', 'eee@zzz.org'])
  62. eq(msg.get_all('xx', 'n/a'), 'n/a')
  63. def test_getset_charset(self):
  64. eq = self.assertEqual
  65. msg = Message()
  66. eq(msg.get_charset(), None)
  67. charset = Charset('iso-8859-1')
  68. msg.set_charset(charset)
  69. eq(msg['mime-version'], '1.0')
  70. eq(msg.get_content_type(), 'text/plain')
  71. eq(msg['content-type'], 'text/plain; charset="iso-8859-1"')
  72. eq(msg.get_param('charset'), 'iso-8859-1')
  73. eq(msg['content-transfer-encoding'], 'quoted-printable')
  74. eq(msg.get_charset().input_charset, 'iso-8859-1')
  75. # Remove the charset
  76. msg.set_charset(None)
  77. eq(msg.get_charset(), None)
  78. eq(msg['content-type'], 'text/plain')
  79. # Try adding a charset when there's already MIME headers present
  80. msg = Message()
  81. msg['MIME-Version'] = '2.0'
  82. msg['Content-Type'] = 'text/x-weird'
  83. msg['Content-Transfer-Encoding'] = 'quinted-puntable'
  84. msg.set_charset(charset)
  85. eq(msg['mime-version'], '2.0')
  86. eq(msg['content-type'], 'text/x-weird; charset="iso-8859-1"')
  87. eq(msg['content-transfer-encoding'], 'quinted-puntable')
  88. def test_set_charset_from_string(self):
  89. eq = self.assertEqual
  90. msg = Message()
  91. msg.set_charset('us-ascii')
  92. eq(msg.get_charset().input_charset, 'us-ascii')
  93. eq(msg['content-type'], 'text/plain; charset="us-ascii"')
  94. def test_set_payload_with_charset(self):
  95. msg = Message()
  96. charset = Charset('iso-8859-1')
  97. msg.set_payload('This is a string payload', charset)
  98. self.assertEqual(msg.get_charset().input_charset, 'iso-8859-1')
  99. def test_get_charsets(self):
  100. eq = self.assertEqual
  101. msg = self._msgobj('msg_08.txt')
  102. charsets = msg.get_charsets()
  103. eq(charsets, [None, 'us-ascii', 'iso-8859-1', 'iso-8859-2', 'koi8-r'])
  104. msg = self._msgobj('msg_09.txt')
  105. charsets = msg.get_charsets('dingbat')
  106. eq(charsets, ['dingbat', 'us-ascii', 'iso-8859-1', 'dingbat',
  107. 'koi8-r'])
  108. msg = self._msgobj('msg_12.txt')
  109. charsets = msg.get_charsets()
  110. eq(charsets, [None, 'us-ascii', 'iso-8859-1', None, 'iso-8859-2',
  111. 'iso-8859-3', 'us-ascii', 'koi8-r'])
  112. def test_get_filename(self):
  113. eq = self.assertEqual
  114. msg = self._msgobj('msg_04.txt')
  115. filenames = [p.get_filename() for p in msg.get_payload()]
  116. eq(filenames, ['msg.txt', 'msg.txt'])
  117. msg = self._msgobj('msg_07.txt')
  118. subpart = msg.get_payload(1)
  119. eq(subpart.get_filename(), 'dingusfish.gif')
  120. def test_get_filename_with_name_parameter(self):
  121. eq = self.assertEqual
  122. msg = self._msgobj('msg_44.txt')
  123. filenames = [p.get_filename() for p in msg.get_payload()]
  124. eq(filenames, ['msg.txt', 'msg.txt'])
  125. def test_get_boundary(self):
  126. eq = self.assertEqual
  127. msg = self._msgobj('msg_07.txt')
  128. # No quotes!
  129. eq(msg.get_boundary(), 'BOUNDARY')
  130. def test_set_boundary(self):
  131. eq = self.assertEqual
  132. # This one has no existing boundary parameter, but the Content-Type:
  133. # header appears fifth.
  134. msg = self._msgobj('msg_01.txt')
  135. msg.set_boundary('BOUNDARY')
  136. header, value = msg.items()[4]
  137. eq(header.lower(), 'content-type')
  138. eq(value, 'text/plain; charset="us-ascii"; boundary="BOUNDARY"')
  139. # This one has a Content-Type: header, with a boundary, stuck in the
  140. # middle of its headers. Make sure the order is preserved; it should
  141. # be fifth.
  142. msg = self._msgobj('msg_04.txt')
  143. msg.set_boundary('BOUNDARY')
  144. header, value = msg.items()[4]
  145. eq(header.lower(), 'content-type')
  146. eq(value, 'multipart/mixed; boundary="BOUNDARY"')
  147. # And this one has no Content-Type: header at all.
  148. msg = self._msgobj('msg_03.txt')
  149. self.assertRaises(Errors.HeaderParseError,
  150. msg.set_boundary, 'BOUNDARY')
  151. def test_make_boundary(self):
  152. msg = MIMEMultipart('form-data')
  153. # Note that when the boundary gets created is an implementation
  154. # detail and might change.
  155. self.assertEqual(msg.items()[0][1], 'multipart/form-data')
  156. # Trigger creation of boundary
  157. msg.as_string()
  158. self.assertEqual(msg.items()[0][1][:33],
  159. 'multipart/form-data; boundary="==')
  160. # XXX: there ought to be tests of the uniqueness of the boundary, too.
  161. def test_message_rfc822_only(self):
  162. # Issue 7970: message/rfc822 not in multipart parsed by
  163. # HeaderParser caused an exception when flattened.
  164. fp = openfile(findfile('msg_46.txt'))
  165. msgdata = fp.read()
  166. parser = email.Parser.HeaderParser()
  167. msg = parser.parsestr(msgdata)
  168. out = StringIO()
  169. gen = email.Generator.Generator(out, True, 0)
  170. gen.flatten(msg, False)
  171. self.assertEqual(out.getvalue(), msgdata)
  172. def test_get_decoded_payload(self):
  173. eq = self.assertEqual
  174. msg = self._msgobj('msg_10.txt')
  175. # The outer message is a multipart
  176. eq(msg.get_payload(decode=True), None)
  177. # Subpart 1 is 7bit encoded
  178. eq(msg.get_payload(0).get_payload(decode=True),
  179. 'This is a 7bit encoded message.\n')
  180. # Subpart 2 is quopri
  181. eq(msg.get_payload(1).get_payload(decode=True),
  182. '\xa1This is a Quoted Printable encoded message!\n')
  183. # Subpart 3 is base64
  184. eq(msg.get_payload(2).get_payload(decode=True),
  185. 'This is a Base64 encoded message.')
  186. # Subpart 4 is base64 with a trailing newline, which
  187. # used to be stripped (issue 7143).
  188. eq(msg.get_payload(3).get_payload(decode=True),
  189. 'This is a Base64 encoded message.\n')
  190. # Subpart 5 has no Content-Transfer-Encoding: header.
  191. eq(msg.get_payload(4).get_payload(decode=True),
  192. 'This has no Content-Transfer-Encoding: header.\n')
  193. def test_get_decoded_uu_payload(self):
  194. eq = self.assertEqual
  195. msg = Message()
  196. msg.set_payload('begin 666 -\n+:&5L;&\\@=V]R;&0 \n \nend\n')
  197. for cte in ('x-uuencode', 'uuencode', 'uue', 'x-uue'):
  198. msg['content-transfer-encoding'] = cte
  199. eq(msg.get_payload(decode=True), 'hello world')
  200. # Now try some bogus data
  201. msg.set_payload('foo')
  202. eq(msg.get_payload(decode=True), 'foo')
  203. def test_decode_bogus_uu_payload_quietly(self):
  204. msg = Message()
  205. msg.set_payload('begin 664 foo.txt\n%<W1F=0000H \n \nend\n')
  206. msg['Content-Transfer-Encoding'] = 'x-uuencode'
  207. old_stderr = sys.stderr
  208. try:
  209. sys.stderr = sfp = StringIO()
  210. # We don't care about the payload
  211. msg.get_payload(decode=True)
  212. finally:
  213. sys.stderr = old_stderr
  214. self.assertEqual(sfp.getvalue(), '')
  215. def test_decoded_generator(self):
  216. eq = self.assertEqual
  217. msg = self._msgobj('msg_07.txt')
  218. fp = openfile('msg_17.txt')
  219. try:
  220. text = fp.read()
  221. finally:
  222. fp.close()
  223. s = StringIO()
  224. g = DecodedGenerator(s)
  225. g.flatten(msg)
  226. eq(s.getvalue(), text)
  227. def test__contains__(self):
  228. msg = Message()
  229. msg['From'] = 'Me'
  230. msg['to'] = 'You'
  231. # Check for case insensitivity
  232. self.assertTrue('from' in msg)
  233. self.assertTrue('From' in msg)
  234. self.assertTrue('FROM' in msg)
  235. self.assertTrue('to' in msg)
  236. self.assertTrue('To' in msg)
  237. self.assertTrue('TO' in msg)
  238. def test_as_string(self):
  239. eq = self.assertEqual
  240. msg = self._msgobj('msg_01.txt')
  241. fp = openfile('msg_01.txt')
  242. try:
  243. # BAW 30-Mar-2009 Evil be here. So, the generator is broken with
  244. # respect to long line breaking. It's also not idempotent when a
  245. # header from a parsed message is continued with tabs rather than
  246. # spaces. Before we fixed bug 1974 it was reversedly broken,
  247. # i.e. headers that were continued with spaces got continued with
  248. # tabs. For Python 2.x there's really no good fix and in Python
  249. # 3.x all this stuff is re-written to be right(er). Chris Withers
  250. # convinced me that using space as the default continuation
  251. # character is less bad for more applications.
  252. text = fp.read().replace('\t', ' ')
  253. finally:
  254. fp.close()
  255. eq(text, msg.as_string())
  256. fullrepr = str(msg)
  257. lines = fullrepr.split('\n')
  258. self.assertTrue(lines[0].startswith('From '))
  259. eq(text, NL.join(lines[1:]))
  260. def test_bad_param(self):
  261. msg = email.message_from_string("Content-Type: blarg; baz; boo\n")
  262. self.assertEqual(msg.get_param('baz'), '')
  263. def test_missing_filename(self):
  264. msg = email.message_from_string("From: foo\n")
  265. self.assertEqual(msg.get_filename(), None)
  266. def test_bogus_filename(self):
  267. msg = email.message_from_string(
  268. "Content-Disposition: blarg; filename\n")
  269. self.assertEqual(msg.get_filename(), '')
  270. def test_missing_boundary(self):
  271. msg = email.message_from_string("From: foo\n")
  272. self.assertEqual(msg.get_boundary(), None)
  273. def test_get_params(self):
  274. eq = self.assertEqual
  275. msg = email.message_from_string(
  276. 'X-Header: foo=one; bar=two; baz=three\n')
  277. eq(msg.get_params(header='x-header'),
  278. [('foo', 'one'), ('bar', 'two'), ('baz', 'three')])
  279. msg = email.message_from_string(
  280. 'X-Header: foo; bar=one; baz=two\n')
  281. eq(msg.get_params(header='x-header'),
  282. [('foo', ''), ('bar', 'one'), ('baz', 'two')])
  283. eq(msg.get_params(), None)
  284. msg = email.message_from_string(
  285. 'X-Header: foo; bar="one"; baz=two\n')
  286. eq(msg.get_params(header='x-header'),
  287. [('foo', ''), ('bar', 'one'), ('baz', 'two')])
  288. def test_get_param_liberal(self):
  289. msg = Message()
  290. msg['Content-Type'] = 'Content-Type: Multipart/mixed; boundary = "CPIMSSMTPC06p5f3tG"'
  291. self.assertEqual(msg.get_param('boundary'), 'CPIMSSMTPC06p5f3tG')
  292. def test_get_param(self):
  293. eq = self.assertEqual
  294. msg = email.message_from_string(
  295. "X-Header: foo=one; bar=two; baz=three\n")
  296. eq(msg.get_param('bar', header='x-header'), 'two')
  297. eq(msg.get_param('quuz', header='x-header'), None)
  298. eq(msg.get_param('quuz'), None)
  299. msg = email.message_from_string(
  300. 'X-Header: foo; bar="one"; baz=two\n')
  301. eq(msg.get_param('foo', header='x-header'), '')
  302. eq(msg.get_param('bar', header='x-header'), 'one')
  303. eq(msg.get_param('baz', header='x-header'), 'two')
  304. # XXX: We are not RFC-2045 compliant! We cannot parse:
  305. # msg["Content-Type"] = 'text/plain; weird="hey; dolly? [you] @ <\\"home\\">?"'
  306. # msg.get_param("weird")
  307. # yet.
  308. def test_get_param_funky_continuation_lines(self):
  309. msg = self._msgobj('msg_22.txt')
  310. self.assertEqual(msg.get_payload(1).get_param('name'), 'wibble.JPG')
  311. def test_get_param_with_semis_in_quotes(self):
  312. msg = email.message_from_string(
  313. 'Content-Type: image/pjpeg; name="Jim&amp;&amp;Jill"\n')
  314. self.assertEqual(msg.get_param('name'), 'Jim&amp;&amp;Jill')
  315. self.assertEqual(msg.get_param('name', unquote=False),
  316. '"Jim&amp;&amp;Jill"')
  317. def test_get_param_with_quotes(self):
  318. msg = email.message_from_string(
  319. 'Content-Type: foo; bar*0="baz\\"foobar"; bar*1="\\"baz"')
  320. self.assertEqual(msg.get_param('bar'), 'baz"foobar"baz')
  321. msg = email.message_from_string(
  322. "Content-Type: foo; bar*0=\"baz\\\"foobar\"; bar*1=\"\\\"baz\"")
  323. self.assertEqual(msg.get_param('bar'), 'baz"foobar"baz')
  324. def test_has_key(self):
  325. msg = email.message_from_string('Header: exists')
  326. self.assertTrue(msg.has_key('header'))
  327. self.assertTrue(msg.has_key('Header'))
  328. self.assertTrue(msg.has_key('HEADER'))
  329. self.assertFalse(msg.has_key('headeri'))
  330. def test_set_param(self):
  331. eq = self.assertEqual
  332. msg = Message()
  333. msg.set_param('charset', 'iso-2022-jp')
  334. eq(msg.get_param('charset'), 'iso-2022-jp')
  335. msg.set_param('importance', 'high value')
  336. eq(msg.get_param('importance'), 'high value')
  337. eq(msg.get_param('importance', unquote=False), '"high value"')
  338. eq(msg.get_params(), [('text/plain', ''),
  339. ('charset', 'iso-2022-jp'),
  340. ('importance', 'high value')])
  341. eq(msg.get_params(unquote=False), [('text/plain', ''),
  342. ('charset', '"iso-2022-jp"'),
  343. ('importance', '"high value"')])
  344. msg.set_param('charset', 'iso-9999-xx', header='X-Jimmy')
  345. eq(msg.get_param('charset', header='X-Jimmy'), 'iso-9999-xx')
  346. def test_del_param(self):
  347. eq = self.assertEqual
  348. msg = self._msgobj('msg_05.txt')
  349. eq(msg.get_params(),
  350. [('multipart/report', ''), ('report-type', 'delivery-status'),
  351. ('boundary', 'D1690A7AC1.996856090/mail.example.com')])
  352. old_val = msg.get_param("report-type")
  353. msg.del_param("report-type")
  354. eq(msg.get_params(),
  355. [('multipart/report', ''),
  356. ('boundary', 'D1690A7AC1.996856090/mail.example.com')])
  357. msg.set_param("report-type", old_val)
  358. eq(msg.get_params(),
  359. [('multipart/report', ''),
  360. ('boundary', 'D1690A7AC1.996856090/mail.example.com'),
  361. ('report-type', old_val)])
  362. def test_del_param_on_other_header(self):
  363. msg = Message()
  364. msg.add_header('Content-Disposition', 'attachment', filename='bud.gif')
  365. msg.del_param('filename', 'content-disposition')
  366. self.assertEqual(msg['content-disposition'], 'attachment')
  367. def test_set_type(self):
  368. eq = self.assertEqual
  369. msg = Message()
  370. self.assertRaises(ValueError, msg.set_type, 'text')
  371. msg.set_type('text/plain')
  372. eq(msg['content-type'], 'text/plain')
  373. msg.set_param('charset', 'us-ascii')
  374. eq(msg['content-type'], 'text/plain; charset="us-ascii"')
  375. msg.set_type('text/html')
  376. eq(msg['content-type'], 'text/html; charset="us-ascii"')
  377. def test_set_type_on_other_header(self):
  378. msg = Message()
  379. msg['X-Content-Type'] = 'text/plain'
  380. msg.set_type('application/octet-stream', 'X-Content-Type')
  381. self.assertEqual(msg['x-content-type'], 'application/octet-stream')
  382. def test_get_content_type_missing(self):
  383. msg = Message()
  384. self.assertEqual(msg.get_content_type(), 'text/plain')
  385. def test_get_content_type_missing_with_default_type(self):
  386. msg = Message()
  387. msg.set_default_type('message/rfc822')
  388. self.assertEqual(msg.get_content_type(), 'message/rfc822')
  389. def test_get_content_type_from_message_implicit(self):
  390. msg = self._msgobj('msg_30.txt')
  391. self.assertEqual(msg.get_payload(0).get_content_type(),
  392. 'message/rfc822')
  393. def test_get_content_type_from_message_explicit(self):
  394. msg = self._msgobj('msg_28.txt')
  395. self.assertEqual(msg.get_payload(0).get_content_type(),
  396. 'message/rfc822')
  397. def test_get_content_type_from_message_text_plain_implicit(self):
  398. msg = self._msgobj('msg_03.txt')
  399. self.assertEqual(msg.get_content_type(), 'text/plain')
  400. def test_get_content_type_from_message_text_plain_explicit(self):
  401. msg = self._msgobj('msg_01.txt')
  402. self.assertEqual(msg.get_content_type(), 'text/plain')
  403. def test_get_content_maintype_missing(self):
  404. msg = Message()
  405. self.assertEqual(msg.get_content_maintype(), 'text')
  406. def test_get_content_maintype_missing_with_default_type(self):
  407. msg = Message()
  408. msg.set_default_type('message/rfc822')
  409. self.assertEqual(msg.get_content_maintype(), 'message')
  410. def test_get_content_maintype_from_message_implicit(self):
  411. msg = self._msgobj('msg_30.txt')
  412. self.assertEqual(msg.get_payload(0).get_content_maintype(), 'message')
  413. def test_get_content_maintype_from_message_explicit(self):
  414. msg = self._msgobj('msg_28.txt')
  415. self.assertEqual(msg.get_payload(0).get_content_maintype(), 'message')
  416. def test_get_content_maintype_from_message_text_plain_implicit(self):
  417. msg = self._msgobj('msg_03.txt')
  418. self.assertEqual(msg.get_content_maintype(), 'text')
  419. def test_get_content_maintype_from_message_text_plain_explicit(self):
  420. msg = self._msgobj('msg_01.txt')
  421. self.assertEqual(msg.get_content_maintype(), 'text')
  422. def test_get_content_subtype_missing(self):
  423. msg = Message()
  424. self.assertEqual(msg.get_content_subtype(), 'plain')
  425. def test_get_content_subtype_missing_with_default_type(self):
  426. msg = Message()
  427. msg.set_default_type('message/rfc822')
  428. self.assertEqual(msg.get_content_subtype(), 'rfc822')
  429. def test_get_content_subtype_from_message_implicit(self):
  430. msg = self._msgobj('msg_30.txt')
  431. self.assertEqual(msg.get_payload(0).get_content_subtype(), 'rfc822')
  432. def test_get_content_subtype_from_message_explicit(self):
  433. msg = self._msgobj('msg_28.txt')
  434. self.assertEqual(msg.get_payload(0).get_content_subtype(), 'rfc822')
  435. def test_get_content_subtype_from_message_text_plain_implicit(self):
  436. msg = self._msgobj('msg_03.txt')
  437. self.assertEqual(msg.get_content_subtype(), 'plain')
  438. def test_get_content_subtype_from_message_text_plain_explicit(self):
  439. msg = self._msgobj('msg_01.txt')
  440. self.assertEqual(msg.get_content_subtype(), 'plain')
  441. def test_get_content_maintype_error(self):
  442. msg = Message()
  443. msg['Content-Type'] = 'no-slash-in-this-string'
  444. self.assertEqual(msg.get_content_maintype(), 'text')
  445. def test_get_content_subtype_error(self):
  446. msg = Message()
  447. msg['Content-Type'] = 'no-slash-in-this-string'
  448. self.assertEqual(msg.get_content_subtype(), 'plain')
  449. def test_replace_header(self):
  450. eq = self.assertEqual
  451. msg = Message()
  452. msg.add_header('First', 'One')
  453. msg.add_header('Second', 'Two')
  454. msg.add_header('Third', 'Three')
  455. eq(msg.keys(), ['First', 'Second', 'Third'])
  456. eq(msg.values(), ['One', 'Two', 'Three'])
  457. msg.replace_header('Second', 'Twenty')
  458. eq(msg.keys(), ['First', 'Second', 'Third'])
  459. eq(msg.values(), ['One', 'Twenty', 'Three'])
  460. msg.add_header('First', 'Eleven')
  461. msg.replace_header('First', 'One Hundred')
  462. eq(msg.keys(), ['First', 'Second', 'Third', 'First'])
  463. eq(msg.values(), ['One Hundred', 'Twenty', 'Three', 'Eleven'])
  464. self.assertRaises(KeyError, msg.replace_header, 'Fourth', 'Missing')
  465. def test_broken_base64_payload(self):
  466. x = 'AwDp0P7//y6LwKEAcPa/6Q=9'
  467. msg = Message()
  468. msg['content-type'] = 'audio/x-midi'
  469. msg['content-transfer-encoding'] = 'base64'
  470. msg.set_payload(x)
  471. self.assertEqual(msg.get_payload(decode=True), x)
  472. def test_get_content_charset(self):
  473. msg = Message()
  474. msg.set_charset('us-ascii')
  475. self.assertEqual('us-ascii', msg.get_content_charset())
  476. msg.set_charset(u'us-ascii')
  477. self.assertEqual('us-ascii', msg.get_content_charset())
  478. # Issue 5871: reject an attempt to embed a header inside a header value
  479. # (header injection attack).
  480. def test_embeded_header_via_Header_rejected(self):
  481. msg = Message()
  482. msg['Dummy'] = Header('dummy\nX-Injected-Header: test')
  483. self.assertRaises(Errors.HeaderParseError, msg.as_string)
  484. def test_embeded_header_via_string_rejected(self):
  485. msg = Message()
  486. msg['Dummy'] = 'dummy\nX-Injected-Header: test'
  487. self.assertRaises(Errors.HeaderParseError, msg.as_string)
  488. # Test the email.Encoders module
  489. class TestEncoders(unittest.TestCase):
  490. def test_encode_empty_payload(self):
  491. eq = self.assertEqual
  492. msg = Message()
  493. msg.set_charset('us-ascii')
  494. eq(msg['content-transfer-encoding'], '7bit')
  495. def test_default_cte(self):
  496. eq = self.assertEqual
  497. # 7bit data and the default us-ascii _charset
  498. msg = MIMEText('hello world')
  499. eq(msg['content-transfer-encoding'], '7bit')
  500. # Similar, but with 8bit data
  501. msg = MIMEText('hello \xf8 world')
  502. eq(msg['content-transfer-encoding'], '8bit')
  503. # And now with a different charset
  504. msg = MIMEText('hello \xf8 world', _charset='iso-8859-1')
  505. eq(msg['content-transfer-encoding'], 'quoted-printable')
  506. def test_encode7or8bit(self):
  507. # Make sure a charset whose input character set is 8bit but
  508. # whose output character set is 7bit gets a transfer-encoding
  509. # of 7bit.
  510. eq = self.assertEqual
  511. msg = email.MIMEText.MIMEText('\xca\xb8', _charset='euc-jp')
  512. eq(msg['content-transfer-encoding'], '7bit')
  513. # Test long header wrapping
  514. class TestLongHeaders(TestEmailBase):
  515. def test_split_long_continuation(self):
  516. eq = self.ndiffAssertEqual
  517. msg = email.message_from_string("""\
  518. Subject: bug demonstration
  519. \t12345678911234567892123456789312345678941234567895123456789612345678971234567898112345678911234567892123456789112345678911234567892123456789
  520. \tmore text
  521. test
  522. """)
  523. sfp = StringIO()
  524. g = Generator(sfp)
  525. g.flatten(msg)
  526. eq(sfp.getvalue(), """\
  527. Subject: bug demonstration
  528. 12345678911234567892123456789312345678941234567895123456789612345678971234567898112345678911234567892123456789112345678911234567892123456789
  529. more text
  530. test
  531. """)
  532. def test_another_long_almost_unsplittable_header(self):
  533. eq = self.ndiffAssertEqual
  534. hstr = """\
  535. bug demonstration
  536. \t12345678911234567892123456789312345678941234567895123456789612345678971234567898112345678911234567892123456789112345678911234567892123456789
  537. \tmore text"""
  538. h = Header(hstr, continuation_ws='\t')
  539. eq(h.encode(), """\
  540. bug demonstration
  541. \t12345678911234567892123456789312345678941234567895123456789612345678971234567898112345678911234567892123456789112345678911234567892123456789
  542. \tmore text""")
  543. h = Header(hstr)
  544. eq(h.encode(), """\
  545. bug demonstration
  546. 12345678911234567892123456789312345678941234567895123456789612345678971234567898112345678911234567892123456789112345678911234567892123456789
  547. more text""")
  548. def test_long_nonstring(self):
  549. eq = self.ndiffAssertEqual
  550. g = Charset("iso-8859-1")
  551. cz = Charset("iso-8859-2")
  552. utf8 = Charset("utf-8")
  553. g_head = "Die Mieter treten hier ein werden mit einem Foerderband komfortabel den Korridor entlang, an s\xfcdl\xfcndischen Wandgem\xe4lden vorbei, gegen die rotierenden Klingen bef\xf6rdert. "
  554. cz_head = "Finan\xe8ni metropole se hroutily pod tlakem jejich d\xf9vtipu.. "
  555. utf8_head = u"\u6b63\u78ba\u306b\u8a00\u3046\u3068\u7ffb\u8a33\u306f\u3055\u308c\u3066\u3044\u307e\u305b\u3093\u3002\u4e00\u90e8\u306f\u30c9\u30a4\u30c4\u8a9e\u3067\u3059\u304c\u3001\u3042\u3068\u306f\u3067\u305f\u3089\u3081\u3067\u3059\u3002\u5b9f\u969b\u306b\u306f\u300cWenn ist das Nunstuck git und Slotermeyer? Ja! Beiherhund das Oder die Flipperwaldt gersput.\u300d\u3068\u8a00\u3063\u3066\u3044\u307e\u3059\u3002".encode("utf-8")
  556. h = Header(g_head, g, header_name='Subject')
  557. h.append(cz_head, cz)
  558. h.append(utf8_head, utf8)
  559. msg = Message()
  560. msg['Subject'] = h
  561. sfp = StringIO()
  562. g = Generator(sfp)
  563. g.flatten(msg)
  564. eq(sfp.getvalue(), """\
  565. Subject: =?iso-8859-1?q?Die_Mieter_treten_hier_ein_werden_mit_einem_Foerd?=
  566. =?iso-8859-1?q?erband_komfortabel_den_Korridor_entlang=2C_an_s=FCdl=FCndi?=
  567. =?iso-8859-1?q?schen_Wandgem=E4lden_vorbei=2C_gegen_die_rotierenden_Kling?=
  568. =?iso-8859-1?q?en_bef=F6rdert=2E_?= =?iso-8859-2?q?Finan=E8ni_met?=
  569. =?iso-8859-2?q?ropole_se_hroutily_pod_tlakem_jejich_d=F9vtipu=2E=2E_?=
  570. =?utf-8?b?5q2j56K644Gr6KiA44GG44Go57+76Kiz44Gv44GV44KM44Gm44GE?=
  571. =?utf-8?b?44G+44Gb44KT44CC5LiA6YOo44Gv44OJ44Kk44OE6Kqe44Gn44GZ44GM44CB?=
  572. =?utf-8?b?44GC44Go44Gv44Gn44Gf44KJ44KB44Gn44GZ44CC5a6f6Zqb44Gr44Gv44CM?=
  573. =?utf-8?q?Wenn_ist_das_Nunstuck_git_und_Slotermeyer=3F_Ja!_Beiherhund_das?=
  574. =?utf-8?b?IE9kZXIgZGllIEZsaXBwZXJ3YWxkdCBnZXJzcHV0LuOAjeOBqOiogOOBow==?=
  575. =?utf-8?b?44Gm44GE44G+44GZ44CC?=
  576. """)
  577. eq(h.encode(), """\
  578. =?iso-8859-1?q?Die_Mieter_treten_hier_ein_werden_mit_einem_Foerd?=
  579. =?iso-8859-1?q?erband_komfortabel_den_Korridor_entlang=2C_an_s=FCdl=FCndi?=
  580. =?iso-8859-1?q?schen_Wandgem=E4lden_vorbei=2C_gegen_die_rotierenden_Kling?=
  581. =?iso-8859-1?q?en_bef=F6rdert=2E_?= =?iso-8859-2?q?Finan=E8ni_met?=
  582. =?iso-8859-2?q?ropole_se_hroutily_pod_tlakem_jejich_d=F9vtipu=2E=2E_?=
  583. =?utf-8?b?5q2j56K644Gr6KiA44GG44Go57+76Kiz44Gv44GV44KM44Gm44GE?=
  584. =?utf-8?b?44G+44Gb44KT44CC5LiA6YOo44Gv44OJ44Kk44OE6Kqe44Gn44GZ44GM44CB?=
  585. =?utf-8?b?44GC44Go44Gv44Gn44Gf44KJ44KB44Gn44GZ44CC5a6f6Zqb44Gr44Gv44CM?=
  586. =?utf-8?q?Wenn_ist_das_Nunstuck_git_und_Slotermeyer=3F_Ja!_Beiherhund_das?=
  587. =?utf-8?b?IE9kZXIgZGllIEZsaXBwZXJ3YWxkdCBnZXJzcHV0LuOAjeOBqOiogOOBow==?=
  588. =?utf-8?b?44Gm44GE44G+44GZ44CC?=""")
  589. def test_long_header_encode(self):
  590. eq = self.ndiffAssertEqual
  591. h = Header('wasnipoop; giraffes="very-long-necked-animals"; '
  592. 'spooge="yummy"; hippos="gargantuan"; marshmallows="gooey"',
  593. header_name='X-Foobar-Spoink-Defrobnit')
  594. eq(h.encode(), '''\
  595. wasnipoop; giraffes="very-long-necked-animals";
  596. spooge="yummy"; hippos="gargantuan"; marshmallows="gooey"''')
  597. def test_long_header_encode_with_tab_continuation(self):
  598. eq = self.ndiffAssertEqual
  599. h = Header('wasnipoop; giraffes="very-long-necked-animals"; '
  600. 'spooge="yummy"; hippos="gargantuan"; marshmallows="gooey"',
  601. header_name='X-Foobar-Spoink-Defrobnit',
  602. continuation_ws='\t')
  603. eq(h.encode(), '''\
  604. wasnipoop; giraffes="very-long-necked-animals";
  605. \tspooge="yummy"; hippos="gargantuan"; marshmallows="gooey"''')
  606. def test_header_splitter(self):
  607. eq = self.ndiffAssertEqual
  608. msg = MIMEText('')
  609. # It'd be great if we could use add_header() here, but that doesn't
  610. # guarantee an order of the parameters.
  611. msg['X-Foobar-Spoink-Defrobnit'] = (
  612. 'wasnipoop; giraffes="very-long-necked-animals"; '
  613. 'spooge="yummy"; hippos="gargantuan"; marshmallows="gooey"')
  614. sfp = StringIO()
  615. g = Generator(sfp)
  616. g.flatten(msg)
  617. eq(sfp.getvalue(), '''\
  618. Content-Type: text/plain; charset="us-ascii"
  619. MIME-Version: 1.0
  620. Content-Transfer-Encoding: 7bit
  621. X-Foobar-Spoink-Defrobnit: wasnipoop; giraffes="very-long-necked-animals";
  622. spooge="yummy"; hippos="gargantuan"; marshmallows="gooey"
  623. ''')
  624. def test_no_semis_header_splitter(self):
  625. eq = self.ndiffAssertEqual
  626. msg = Message()
  627. msg['From'] = 'test@dom.ain'
  628. msg['References'] = SPACE.join(['<%d@dom.ain>' % i for i in range(10)])
  629. msg.set_payload('Test')
  630. sfp = StringIO()
  631. g = Generator(sfp)
  632. g.flatten(msg)
  633. eq(sfp.getvalue(), """\
  634. From: test@dom.ain
  635. References: <0@dom.ain> <1@dom.ain> <2@dom.ain> <3@dom.ain> <4@dom.ain>
  636. <5@dom.ain> <6@dom.ain> <7@dom.ain> <8@dom.ain> <9@dom.ain>
  637. Test""")
  638. def test_no_split_long_header(self):
  639. eq = self.ndiffAssertEqual
  640. hstr = 'References: ' + 'x' * 80
  641. h = Header(hstr, continuation_ws='\t')
  642. eq(h.encode(), """\
  643. References: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx""")
  644. def test_splitting_multiple_long_lines(self):
  645. eq = self.ndiffAssertEqual
  646. hstr = """\
  647. from babylon.socal-raves.org (localhost [127.0.0.1]); by babylon.socal-raves.org (Postfix) with ESMTP id B570E51B81; for <mailman-admin@babylon.socal-raves.org>; Sat, 2 Feb 2002 17:00:06 -0800 (PST)
  648. \tfrom babylon.socal-raves.org (localhost [127.0.0.1]); by babylon.socal-raves.org (Postfix) with ESMTP id B570E51B81; for <mailman-admin@babylon.socal-raves.org>; Sat, 2 Feb 2002 17:00:06 -0800 (PST)
  649. \tfrom babylon.socal-raves.org (localhost [127.0.0.1]); by babylon.socal-raves.org (Postfix) with ESMTP id B570E51B81; for <mailman-admin@babylon.socal-raves.org>; Sat, 2 Feb 2002 17:00:06 -0800 (PST)
  650. """
  651. h = Header(hstr, continuation_ws='\t')
  652. eq(h.encode(), """\
  653. from babylon.socal-raves.org (localhost [127.0.0.1]);
  654. \tby babylon.socal-raves.org (Postfix) with ESMTP id B570E51B81;
  655. \tfor <mailman-admin@babylon.socal-raves.org>;
  656. \tSat, 2 Feb 2002 17:00:06 -0800 (PST)
  657. \tfrom babylon.socal-raves.org (localhost [127.0.0.1]);
  658. \tby babylon.socal-raves.org (Postfix) with ESMTP id B570E51B81;
  659. \tfor <mailman-admin@babylon.socal-raves.org>;
  660. \tSat, 2 Feb 2002 17:00:06 -0800 (PST)
  661. \tfrom babylon.socal-raves.org (localhost [127.0.0.1]);
  662. \tby babylon.socal-raves.org (Postfix) with ESMTP id B570E51B81;
  663. \tfor <mailman-admin@babylon.socal-raves.org>;
  664. \tSat, 2 Feb 2002 17:00:06 -0800 (PST)""")
  665. def test_splitting_first_line_only_is_long(self):
  666. eq = self.ndiffAssertEqual
  667. hstr = """\
  668. from modemcable093.139-201-24.que.mc.videotron.ca ([24.201.139.93] helo=cthulhu.gerg.ca)
  669. \tby kronos.mems-exchange.org with esmtp (Exim 4.05)
  670. \tid 17k4h5-00034i-00
  671. \tfor test@mems-exchange.org; Wed, 28 Aug 2002 11:25:20 -0400"""
  672. h = Header(hstr, maxlinelen=78, header_name='Received',
  673. continuation_ws='\t')
  674. eq(h.encode(), """\
  675. from modemcable093.139-201-24.que.mc.videotron.ca ([24.201.139.93]
  676. \thelo=cthulhu.gerg.ca)
  677. \tby kronos.mems-exchange.org with esmtp (Exim 4.05)
  678. \tid 17k4h5-00034i-00
  679. \tfor test@mems-exchange.org; Wed, 28 Aug 2002 11:25:20 -0400""")
  680. def test_long_8bit_header(self):
  681. eq = self.ndiffAssertEqual
  682. msg = Message()
  683. h = Header('Britische Regierung gibt', 'iso-8859-1',
  684. header_name='Subject')
  685. h.append('gr\xfcnes Licht f\xfcr Offshore-Windkraftprojekte')
  686. msg['Subject'] = h
  687. eq(msg.as_string(), """\
  688. Subject: =?iso-8859-1?q?Britische_Regierung_gibt?= =?iso-8859-1?q?gr=FCnes?=
  689. =?iso-8859-1?q?_Licht_f=FCr_Offshore-Windkraftprojekte?=
  690. """)
  691. def test_long_8bit_header_no_charset(self):
  692. eq = self.ndiffAssertEqual
  693. msg = Message()
  694. msg['Reply-To'] = 'Britische Regierung gibt gr\xfcnes Licht f\xfcr Offshore-Windkraftprojekte <a-very-long-address@example.com>'
  695. eq(msg.as_string(), """\
  696. Reply-To: Britische Regierung gibt gr\xfcnes Licht f\xfcr Offshore-Windkraftprojekte <a-very-long-address@example.com>
  697. """)
  698. def test_long_to_header(self):
  699. eq = self.ndiffAssertEqual
  700. to = '"Someone Test #A" <someone@eecs.umich.edu>,<someone@eecs.umich.edu>,"Someone Test #B" <someone@umich.edu>, "Someone Test #C" <someone@eecs.umich.edu>, "Someone Test #D" <someone@eecs.umich.edu>'
  701. msg = Message()
  702. msg['To'] = to
  703. eq(msg.as_string(0), '''\
  704. To: "Someone Test #A" <someone@eecs.umich.edu>, <someone@eecs.umich.edu>,
  705. "Someone Test #B" <someone@umich.edu>,
  706. "Someone Test #C" <someone@eecs.umich.edu>,
  707. "Someone Test #D" <someone@eecs.umich.edu>
  708. ''')
  709. def test_long_line_after_append(self):
  710. eq = self.ndiffAssertEqual
  711. s = 'This is an example of string which has almost the limit of header length.'
  712. h = Header(s)
  713. h.append('Add another line.')
  714. eq(h.encode(), """\
  715. This is an example of string which has almost the limit of header length.
  716. Add another line.""")
  717. def test_shorter_line_with_append(self):
  718. eq = self.ndiffAssertEqual
  719. s = 'This is a shorter line.'
  720. h = Header(s)
  721. h.append('Add another sentence. (Surprise?)')
  722. eq(h.encode(),
  723. 'This is a shorter line. Add another sentence. (Surprise?)')
  724. def test_long_field_name(self):
  725. eq = self.ndiffAssertEqual
  726. fn = 'X-Very-Very-Very-Long-Header-Name'
  727. gs = "Die Mieter treten hier ein werden mit einem Foerderband komfortabel den Korridor entlang, an s\xfcdl\xfcndischen Wandgem\xe4lden vorbei, gegen die rotierenden Klingen bef\xf6rdert. "
  728. h = Header(gs, 'iso-8859-1', header_name=fn)
  729. # BAW: this seems broken because the first line is too long
  730. eq(h.encode(), """\
  731. =?iso-8859-1?q?Die_Mieter_treten_hier_?=
  732. =?iso-8859-1?q?ein_werden_mit_einem_Foerderband_komfortabel_den_Korridor_?=
  733. =?iso-8859-1?q?entlang=2C_an_s=FCdl=FCndischen_Wandgem=E4lden_vorbei=2C_g?=
  734. =?iso-8859-1?q?egen_die_rotierenden_Klingen_bef=F6rdert=2E_?=""")
  735. def test_long_received_header(self):
  736. h = 'from FOO.TLD (vizworld.acl.foo.tld [123.452.678.9]) by hrothgar.la.mastaler.com (tmda-ofmipd) with ESMTP; Wed, 05 Mar 2003 18:10:18 -0700'
  737. msg = Message()
  738. msg['Received-1'] = Header(h, continuation_ws='\t')
  739. msg['Received-2'] = h
  740. self.assertEqual(msg.as_string(), """\
  741. Received-1: from FOO.TLD (vizworld.acl.foo.tld [123.452.678.9]) by
  742. \throthgar.la.mastaler.com (tmda-ofmipd) with ESMTP;
  743. \tWed, 05 Mar 2003 18:10:18 -0700
  744. Received-2: from FOO.TLD (vizworld.acl.foo.tld [123.452.678.9]) by
  745. hrothgar.la.mastaler.com (tmda-ofmipd) with ESMTP;
  746. Wed, 05 Mar 2003 18:10:18 -0700
  747. """)
  748. def test_string_headerinst_eq(self):
  749. h = '<15975.17901.207240.414604@sgigritzmann1.mathematik.tu-muenchen.de> (David Bremner\'s message of "Thu, 6 Mar 2003 13:58:21 +0100")'
  750. msg = Message()
  751. msg['Received'] = Header(h, header_name='Received',
  752. continuation_ws='\t')
  753. msg['Received'] = h
  754. self.ndiffAssertEqual(msg.as_string(), """\
  755. Received: <15975.17901.207240.414604@sgigritzmann1.mathematik.tu-muenchen.de>
  756. \t(David Bremner's message of "Thu, 6 Mar 2003 13:58:21 +0100")
  757. Received: <15975.17901.207240.414604@sgigritzmann1.mathematik.tu-muenchen.de>
  758. (David Bremner's message of "Thu, 6 Mar 2003 13:58:21 +0100")
  759. """)
  760. def test_long_unbreakable_lines_with_continuation(self):
  761. eq = self.ndiffAssertEqual
  762. msg = Message()
  763. t = """\
  764. iVBORw0KGgoAAAANSUhEUgAAADAAAAAwBAMAAAClLOS0AAAAGFBMVEUAAAAkHiJeRUIcGBi9
  765. locQDQ4zJykFBAXJfWDjAAACYUlEQVR4nF2TQY/jIAyFc6lydlG5x8Nyp1Y69wj1PN2I5gzp"""
  766. msg['Face-1'] = t
  767. msg['Face-2'] = Header(t, header_name='Face-2')
  768. eq(msg.as_string(), """\
  769. Face-1: iVBORw0KGgoAAAANSUhEUgAAADAAAAAwBAMAAAClLOS0AAAAGFBMVEUAAAAkHiJeRUIcGBi9
  770. locQDQ4zJykFBAXJfWDjAAACYUlEQVR4nF2TQY/jIAyFc6lydlG5x8Nyp1Y69wj1PN2I5gzp
  771. Face-2: iVBORw0KGgoAAAANSUhEUgAAADAAAAAwBAMAAAClLOS0AAAAGFBMVEUAAAAkHiJeRUIcGBi9
  772. locQDQ4zJykFBAXJfWDjAAACYUlEQVR4nF2TQY/jIAyFc6lydlG5x8Nyp1Y69wj1PN2I5gzp
  773. """)
  774. def test_another_long_multiline_header(self):
  775. eq = self.ndiffAssertEqual
  776. m = '''\
  777. Received: from siimage.com ([172.25.1.3]) by zima.siliconimage.com with Microsoft SMTPSVC(5.0.2195.4905);
  778. Wed, 16 Oct 2002 07:41:11 -0700'''
  779. msg = email.message_from_string(m)
  780. eq(msg.as_string(), '''\
  781. Received: from siimage.com ([172.25.1.3]) by zima.siliconimage.com with
  782. Microsoft SMTPSVC(5.0.2195.4905); Wed, 16 Oct 2002 07:41:11 -0700
  783. ''')
  784. def test_long_lines_with_different_header(self):
  785. eq = self.ndiffAssertEqual
  786. h = """\
  787. List-Unsubscribe: <https://lists.sourceforge.net/lists/listinfo/spamassassin-talk>,
  788. <mailto:spamassassin-talk-request@lists.sourceforge.net?subject=unsubscribe>"""
  789. msg = Message()
  790. msg['List'] = h
  791. msg['List'] = Header(h, header_name='List')
  792. eq(msg.as_string(), """\
  793. List: List-Unsubscribe: <https://lists.sourceforge.net/lists/listinfo/spamassassin-talk>,
  794. <mailto:spamassassin-talk-request@lists.sourceforge.net?subject=unsubscribe>
  795. List: List-Unsubscribe: <https://lists.sourceforge.net/lists/listinfo/spamassassin-talk>,
  796. <mailto:spamassassin-talk-request@lists.sourceforge.net?subject=unsubscribe>
  797. """)
  798. # Test mangling of "From " lines in the body of a message
  799. class TestFromMangling(unittest.TestCase):
  800. def setUp(self):
  801. self.msg = Message()
  802. self.msg['From'] = 'aaa@bbb.org'
  803. self.msg.set_payload("""\
  804. From the desk of A.A.A.:
  805. Blah blah blah
  806. """)
  807. def test_mangled_from(self):
  808. s = StringIO()
  809. g = Generator(s, mangle_from_=True)
  810. g.flatten(self.msg)
  811. self.assertEqual(s.getvalue(), """\
  812. From: aaa@bbb.org
  813. >From the desk of A.A.A.:
  814. Blah blah blah
  815. """)
  816. def test_dont_mangle_from(self):
  817. s = StringIO()
  818. g = Generator(s, mangle_from_=False)
  819. g.flatten(self.msg)
  820. self.assertEqual(s.getvalue(), """\
  821. From: aaa@bbb.org
  822. From the desk of A.A.A.:
  823. Blah blah blah
  824. """)
  825. # Test the basic MIMEAudio class
  826. class TestMIMEAudio(unittest.TestCase):
  827. def setUp(self):
  828. # Make sure we pick up the audiotest.au that lives in email/test/data.
  829. # In Python, there's an audiotest.au living in Lib/test but that isn't
  830. # included in some binary distros that don't include the test
  831. # package. The trailing empty string on the .join() is significant
  832. # since findfile() will do a dirname().
  833. datadir = os.path.join(os.path.dirname(landmark), 'data', '')
  834. fp = open(findfile('audiotest.au', datadir), 'rb')
  835. try:
  836. self._audiodata = fp.read()
  837. finally:
  838. fp.close()
  839. self._au = MIMEAudio(self._audiodata)
  840. def test_guess_minor_type(self):
  841. self.assertEqual(self._au.get_content_type(), 'audio/basic')
  842. def test_encoding(self):
  843. payload = self._au.get_payload()
  844. self.assertEqual(base64.decodestring(payload), self._audiodata)
  845. def test_checkSetMinor(self):
  846. au = MIMEAudio(self._audiodata, 'fish')
  847. self.assertEqual(au.get_content_type(), 'audio/fish')
  848. def test_add_header(self):
  849. eq = self.assertEqual
  850. unless = self.assertTrue
  851. self._au.add_header('Content-Disposition', 'attachment',
  852. filename='audiotest.au')
  853. eq(self._au['content-disposition'],
  854. 'attachment; filename="audiotest.au"')
  855. eq(self._au.get_params(header='content-disposition'),
  856. [('attachment', ''), ('filename', 'audiotest.au')])
  857. eq(self._au.get_param('filename', header='content-disposition'),
  858. 'audiotest.au')
  859. missing = []
  860. eq(self._au.get_param('attachment', header='content-disposition'), '')
  861. unless(self._au.get_param('foo', failobj=missing,
  862. header='content-disposition') is missing)
  863. # Try some missing stuff
  864. unless(self._au.get_param('foobar', missing) is missing)
  865. unless(self._au.get_param('attachment', missing,
  866. header='foobar') is missing)
  867. # Test the basic MIMEImage class
  868. class TestMIMEImage(unittest.TestCase):
  869. def setUp(self):
  870. fp = openfile('PyBanner048.gif')
  871. try:
  872. self._imgdata = fp.read()
  873. finally:
  874. fp.close()
  875. self._im = MIMEImage(self._imgdata)
  876. def test_guess_minor_type(self):
  877. self.assertEqual(self._im.get_content_type(), 'image/gif')
  878. def test_encoding(self):
  879. payload = self._im.get_payload()
  880. self.assertEqual(base64.decodestring(payload), self._imgdata)
  881. def test_checkSetMinor(self):
  882. im = MIMEImage(self._imgdata, 'fish')
  883. self.assertEqual(im.get_content_type(), 'image/fish')
  884. def test_add_header(self):
  885. eq = self.assertEqual
  886. unless = self.assertTrue
  887. self._im.add_header('Content-Disposition', 'attachment',
  888. filename='dingusfish.gif')
  889. eq(self._im['content-disposition'],
  890. 'attachment; filename="dingusfish.gif"')
  891. eq(self._im.get_params(header='content-disposition'),
  892. [('attachment', ''), ('filename', 'dingusfish.gif')])
  893. eq(self._im.get_param('filename', header='content-disposition'),
  894. 'dingusfish.gif')
  895. missing = []
  896. eq(self._im.get_param('attachment', header='content-disposition'), '')
  897. unless(self._im.get_param('foo', failobj=missing,
  898. header='content-disposition') is missing)
  899. # Try some missing stuff
  900. unless(self._im.get_param('foobar', missing) is missing)
  901. unless(self._im.get_param('attachment', missing,
  902. header='foobar') is missing)
  903. # Test the basic MIMEText class
  904. class TestMIMEText(unittest.TestCase):
  905. def setUp(self):
  906. self._msg = MIMEText('hello there')
  907. def test_types(self):
  908. eq = self.assertEqual
  909. unless = self.assertTrue
  910. eq(self._msg.get_content_type(), 'text/plain')
  911. eq(self._msg.get_param('charset'), 'us-ascii')
  912. missing = []
  913. unless(self._msg.get_param('foobar', missing) is missing)
  914. unless(self._msg.get_param('charset', missing, header='foobar')
  915. is missing)
  916. def test_payload(self):
  917. self.assertEqual(self._msg.get_payload(), 'hello there')
  918. self.assertTrue(not self._msg.is_multipart())
  919. def test_charset(self):
  920. eq = self.assertEqual
  921. msg = MIMEText('hello there', _charset='us-ascii')
  922. eq(msg.get_charset().input_charset, 'us-ascii')
  923. eq(msg['content-type'], 'text/plain; charset="us-ascii"')
  924. def test_7bit_unicode_input(self):
  925. eq = self.assertEqual
  926. msg = MIMEText(u'hello there', _charset='us-ascii')
  927. eq(msg.get_charset().input_charset, 'us-ascii')
  928. eq(msg['content-type'], 'text/plain; charset="us-ascii"')
  929. def test_7bit_unicode_input_no_charset(self):
  930. eq = self.assertEqual
  931. msg = MIMEText(u'hello there')
  932. eq(msg.get_charset(), 'us-ascii')
  933. eq(msg['content-type'], 'text/plain; charset="us-ascii"')
  934. self.assertTrue('hello there' in msg.as_string())
  935. def test_8bit_unicode_input(self):
  936. teststr = u'\u043a\u0438\u0440\u0438\u043b\u0438\u0446\u0430'
  937. eq = self.assertEqual
  938. msg = MIMEText(teststr, _charset='utf-8')
  939. eq(msg.get_charset().output_charset, 'utf-8')
  940. eq(msg['content-type'], 'text/plain; charset="utf-8"')
  941. eq(msg.get_payload(decode=True), teststr.encode('utf-8'))
  942. def test_8bit_unicode_input_no_charset(self):
  943. teststr = u'\u043a\u0438\u0440\u0438\u043b\u0438\u0446\u0430'
  944. self.assertRaises(UnicodeEncodeError, MIMEText, teststr)
  945. # Test complicated multipart/* messages
  946. class TestMultipart(TestEmailBase):
  947. def setUp(self):
  948. fp = openfile('PyBanner048.gif')
  949. try:
  950. data = fp.read()
  951. finally:
  952. fp.close()
  953. container = MIMEBase('multipart', 'mixed', boundary='BOUNDARY')
  954. image = MIMEImage(data, name='dingusfish.gif')
  955. image.add_header('content-disposition', 'attachment',
  956. filename='dingusfish.gif')
  957. intro = MIMEText('''\
  958. Hi there,
  959. This is the dingus fish.
  960. ''')
  961. container.attach(intro)
  962. container.attach(image)
  963. container['From'] = 'Barry <barry@digicool.com>'
  964. container['To'] = 'Dingus Lovers <cravindogs@cravindogs.com>'
  965. container['Subject'] = 'Here is your dingus fish'
  966. now = 987809702.54848599
  967. timetuple = time.localtime(now)
  968. if timetuple[-1] == 0:
  969. tzsecs = time.timezone
  970. else:
  971. tzsecs = time.altzone
  972. if tzsecs > 0:
  973. sign = '-'
  974. else:
  975. sign = '+'
  976. tzoffset = ' %s%04d' % (sign, tzsecs // 36)
  977. container['Date'] = time.strftime(
  978. '%a, %d %b %Y %H:%M:%S',
  979. time.localtime(now)) + tzoffset
  980. self._msg = container
  981. self._im = image
  982. self._txt = intro
  983. def test_hierarchy(self):
  984. # convenience
  985. eq = self.assertEqual
  986. unless = self.assertTrue
  987. raises = self.assertRaises
  988. # tests
  989. m = self._msg
  990. unless(m.is_multipart())
  991. eq(m.get_content_type(), 'multipart/mixed')
  992. eq(len(m.get_payload()), 2)
  993. raises(IndexError, m.get_payload, 2)
  994. m0 = m.get_payload(0)
  995. m1 = m.get_payload(1)
  996. unless(m0 is self._txt)
  997. unless(m1 is self._im)
  998. eq(m.get_payload(), [m0, m1])
  999. unless(not m0.is_multipart())
  1000. unless(not m1.is_multipart())
  1001. def test_empty_multipart_idempotent(self):
  1002. text = """\
  1003. Content-Type: multipart/mixed; boundary="BOUNDARY"
  1004. MIME-Version: 1.0
  1005. Subject: A subject
  1006. To: aperson@dom.ain
  1007. From: bperson@dom.ain
  1008. --BOUNDARY
  1009. --BOUNDARY--
  1010. """
  1011. msg = Parser().parsestr(text)
  1012. self.ndiffAssertEqual(text, msg.as_string())
  1013. def test_no_parts_in_a_multipart_with_none_epilogue(self):
  1014. outer = MIMEBase('multipart', 'mixed')
  1015. outer['Subject'] = 'A subject'
  1016. outer['To'] = 'aperson@dom.ain'
  1017. outer['From'] = 'bperson@dom.ain'
  1018. outer.set_boundary('BOUNDARY')
  1019. self.ndiffAssertEqual(outer.as_string(), '''\
  1020. Content-Type: multipart/mixed; boundary="BOUNDARY"
  1021. MIME-Version: 1.0
  1022. Subject: A subject
  1023. To: aperson@dom.ain
  1024. From: bperson@dom.ain
  1025. --BOUNDARY
  1026. --BOUNDARY--''')
  1027. def test_no_parts_in_a_multipart_with_empty_epilogue(self):
  1028. outer = MIMEBase('multipart', 'mixed')
  1029. outer['Subject'] = 'A subject'
  1030. outer['To'] = 'aperson@dom.ain'
  1031. outer['From'] = 'bperson@dom.ain'
  1032. outer.preamble = ''
  1033. outer.epilogue = ''
  1034. outer.set_boundary('BOUNDARY')
  1035. self.ndiffAssertEqual(outer.as_string(), '''\
  1036. Content-Type: multipart/mixed; boundary="BOUNDARY"
  1037. MIME-Version: 1.0
  1038. Subject: A subject
  1039. To: aperson@dom.ain
  1040. From: bperson@dom.ain
  1041. --BOUNDARY
  1042. --BOUNDARY--
  1043. ''')
  1044. def test_one_part_in_a_multipart(self):
  1045. eq = self.ndiffAssertEqual
  1046. outer = MIMEBase('multipart', 'mixed')
  1047. outer['Subject'] = 'A subject'
  1048. outer['To'] = 'aperson@dom.ain'
  1049. outer['From'] = 'bperson@dom.ain'
  1050. outer.set_boundary('BOUNDARY')
  1051. msg = MIMEText('hello world')
  1052. outer.attach(msg)
  1053. eq(outer.as_string(), '''\
  1054. Content-Type: multipart/mixed; boundary="BOUNDARY"
  1055. MIME-Version: 1.0
  1056. Subject: A subject
  1057. To: aperson@dom.ain
  1058. From: bperson@dom.ain
  1059. --BOUNDARY
  1060. Content-Type: text/plain; charset="us-ascii"
  1061. MIME-Version: 1.0
  1062. Content-Transfer-Encoding: 7bit
  1063. hello world
  1064. --BOUNDARY--''')
  1065. def test_seq_parts_in_a_multipart_with_empty_preamble(self):
  1066. eq = self.ndiffAssertEqual
  1067. outer = MIMEBase('multipart', 'mixed')
  1068. outer['Subject'] = 'A subject'
  1069. outer['To'] = 'aperson@dom.ain'
  1070. outer['From'] = 'bperson@dom.ain'
  1071. outer.preamble = ''
  1072. msg = MIMEText('hello world')
  1073. outer.attach(msg)
  1074. outer.set_boundary('BOUNDARY')
  1075. eq(outer.as_string(), '''\
  1076. Content-Type: multipart/mixed; boundary="BOUNDARY"
  1077. MIME-Version: 1.0
  1078. Subject: A subject
  1079. To: aperson@dom.ain
  1080. From: bperson@dom.ain
  1081. --BOUNDARY
  1082. Content-Type: text/plain; charset="us-ascii"
  1083. MIME-Version: 1.0
  1084. Content-Transfer-Encoding: 7bit
  1085. hello world
  1086. --BOUNDARY--''')
  1087. def test_seq_parts_in_a_multipart_with_none_preamble(self):
  1088. eq = self.ndiffAssertEqual
  1089. outer = MIMEBase('multipart', 'mixed')
  1090. outer['Subject'] = 'A subject'
  1091. outer['To'] = 'aperson@dom.ain'
  1092. outer['From'] = 'bperson@dom.ain'
  1093. outer.preamble = None
  1094. msg = MIMEText('hello world')
  1095. outer.attach(msg)
  1096. outer.set_boundary('BOUNDARY')
  1097. eq(outer.as_string(), '''\
  1098. Content-Type: multipart/mixed; boundary="BOUNDARY"
  1099. MIME-Version: 1.0
  1100. Subject: A subject
  1101. To: aperson@dom.ain
  1102. From: bperson@dom.ain
  1103. --BOUNDARY
  1104. Content-Type: text/plain; charset="us-ascii"
  1105. MIME-Version: 1.0
  1106. Content-Transfer-Encoding: 7bit
  1107. hello world
  1108. --BOUNDARY--''')
  1109. def test_seq_parts_in_a_multipart_with_none_epilogue(self):
  1110. eq = self.ndiffAssertEqual
  1111. outer = MIMEBase('multipart', 'mixed')
  1112. outer['Subject'] = 'A subject'
  1113. outer['To'] = 'aperson@dom.ain'
  1114. outer['From'] = 'bperson@dom.ain'
  1115. outer.epilogue = None
  1116. msg = MIMEText('hello world')
  1117. outer.attach(msg)
  1118. outer.set_boundary('BOUNDARY')
  1119. eq(outer.as_string(), '''\
  1120. Content-Type: multipart/mixed; boundary="BOUNDARY"
  1121. MIME-Version: 1.0
  1122. Subject: A subject
  1123. To: aperson@dom.ain
  1124. From: bperson@dom.ain
  1125. --BOUNDARY
  1126. Content-Type: text/plain; charset="us-ascii"
  1127. MIME-Version: 1.0
  1128. Content-Transfer-Encoding: 7bit
  1129. hello world
  1130. --BOUNDARY--''')
  1131. def test_seq_parts_in_a_multipart_with_empty_epilogue(self):
  1132. eq = self.ndiffAssertEqual
  1133. outer = MIMEBase('multipart', 'mixed')
  1134. outer['Subject'] = 'A subject'
  1135. outer['To'] = 'aperson@dom.ain'
  1136. outer['From'] = 'bperson@dom.ain'
  1137. outer.epilogue = ''
  1138. msg = MIMEText('hello world')
  1139. outer.attach(msg)
  1140. outer.set_boundary('BOUNDARY')
  1141. eq(outer.as_string(), '''\
  1142. Content-Type: multipart/mixed; boundary="BOUNDARY"
  1143. MIME-Version: 1.0
  1144. Subject: A subject
  1145. To: aperson@dom.ain
  1146. From: bperson@dom.ain
  1147. --BOUNDARY
  1148. Content-Type: text/plain; charset="us-ascii"
  1149. MIME-Version: 1.0
  1150. Content-Transfer-Encoding: 7bit
  1151. hello world
  1152. --BOUNDARY--
  1153. ''')
  1154. def test_seq_parts_in_a_multipart_with_nl_epilogue(self):
  1155. eq = self.ndiffAssertEqual
  1156. outer = MIMEBase('multipart', 'mixed')
  1157. outer['Subject'] = 'A subject'
  1158. outer['To'] = 'aperson@dom.ain'
  1159. outer['From'] = 'bperson@dom.ain'
  1160. outer.epilogue = '\n'
  1161. msg = MIMEText('hello world')
  1162. outer.attach(msg)
  1163. outer.set_boundary('BOUNDARY')
  1164. eq(outer.as_string(), '''\
  1165. Content-Type: multipart/mixed; boundary="BOUNDARY"
  1166. MIME-Version: 1.0
  1167. Subject: A subject
  1168. To: aperson@dom.ain
  1169. From: bperson@dom.ain
  1170. --BOUNDARY
  1171. Content-Type: text/plain; charset="us-ascii"
  1172. MIME-Version: 1.0
  1173. Content-Transfer-Encoding: 7bit
  1174. hello world
  1175. --BOUNDARY--
  1176. ''')
  1177. def test_message_external_body(self):
  1178. eq = self.assertEqual
  1179. msg = self._msgobj('msg_36.txt')
  1180. eq(len(msg.get_payload()), 2)
  1181. msg1 = msg.get_payload(1)
  1182. eq(msg1.get_content_type(), 'multipart/alternative')
  1183. eq(len(msg1.get_payload()), 2)
  1184. for subpart in msg1.get_payload():
  1185. eq(subpart.get_content_type(), 'message/external-body')
  1186. eq(len(subpart.get_payload()), 1)
  1187. subsubpart = subpart.get_payload(0)
  1188. eq(subsubpart.get_content_type(), 'text/plain')
  1189. def test_double_boundary(self):
  1190. # msg_37.txt is a multipart that contains two dash-boundary's in a
  1191. # row. Our interpretation of RFC 2046 calls for ignoring the second
  1192. # and subsequent boundaries.
  1193. msg = self._msgobj('msg_37.txt')
  1194. self.assertEqual(len(msg.get_payload()), 3)
  1195. def test_nested_inner_contains_outer_boundary(self):
  1196. eq = self.ndiffAssertEqual
  1197. # msg_38.txt has an inner part that contains outer boundaries. My
  1198. # interpretation of RFC 2046 (based on sections 5.1 and 5.1.2) say
  1199. # these are illegal and should be interpreted as unterminated inner
  1200. # parts.
  1201. msg = self._msgobj('msg_38.txt')
  1202. sfp = StringIO()
  1203. Iterators._structure(msg, sfp)
  1204. eq(sfp.getvalue(), """\
  1205. multipart/mixed
  1206. multipart/mixed
  1207. multipart/alternative
  1208. text/plain
  1209. text/plain
  1210. text/plain
  1211. text/plain
  1212. """)
  1213. def test_nested_with_same_boundary(self):
  1214. eq = self.ndiffAssertEqual
  1215. # msg 39.txt is similarly evil in that it's got inner parts that use
  1216. # the same boundary as outer parts. Again, I believe the way this is
  1217. # parsed is closest to the spirit of RFC 2046
  1218. msg = self._msgobj('msg_39.txt')
  1219. sfp = StringIO()
  1220. Iterators._structure(msg, sfp)
  1221. eq(sfp.getvalue(), """\
  1222. multipart/mixed
  1223. multipart/mixed
  1224. multipart/alternative
  1225. application/octet-stream
  1226. application/octet-stream
  1227. text/plain
  1228. """)
  1229. def test_boundary_in_non_multipart(self):
  1230. msg = self._msgobj('msg_40.txt')
  1231. self.assertEqual(msg.as_string(), '''\
  1232. MIME-Version: 1.0
  1233. Content-Type: text/html; boundary="--961284236552522269"
  1234. ----961284236552522269
  1235. Content-Type: text/html;
  1236. Content-Transfer-Encoding: 7Bit
  1237. <html></html>
  1238. ----961284236552522269--
  1239. ''')
  1240. def test_boundary_with_leading_space(self):
  1241. eq = self.assertEqual
  1242. msg = email.message_from_string('''\
  1243. MIME-Version: 1.0
  1244. Content-Type: multipart/mixed; boundary=" XXXX"
  1245. -- XXXX
  1246. Content-Type: text/plain
  1247. -- XXXX
  1248. Content-Type: text/plain
  1249. -- XXXX--
  1250. ''')
  1251. self.assertTrue(msg.is_multipart())
  1252. eq(msg.get_boundary(), ' XXXX')
  1253. eq(len(msg.get_payload()), 2)
  1254. def test_boundary_without_trailing_newline(self):
  1255. m = Parser().parsestr("""\
  1256. Content-Type: multipart/mixed; boundary="===============0012394164=="
  1257. MIME-Version: 1.0
  1258. --===============0012394164==
  1259. Content-Type: image/file1.jpg
  1260. MIME-Version: 1.0
  1261. Content-Transfer-Encoding: base64
  1262. YXNkZg==
  1263. --===============0012394164==--""")
  1264. self.assertEqual(m.get_payload(0).get_payload(), 'YXNkZg==')
  1265. # Test some badly formatted messages
  1266. class TestNonConformant(TestEmailBase):
  1267. def test_parse_missing_minor_type(self):
  1268. eq = self.assertEqual
  1269. msg = self._msgobj('msg_14.txt')
  1270. eq(msg.get_content_type(), 'text/plain')
  1271. eq(msg.get_content_maintype(), 'text')
  1272. eq(msg.get_content_subtype(), 'plain')
  1273. def test_same_boundary_inner_outer(self):
  1274. unless = self.assertTrue
  1275. msg = self._msgobj('msg_15.txt')
  1276. # XXX We can probably eventually do better
  1277. inner = msg.get_payload(0)
  1278. unless(hasattr(inner, 'defects'))
  1279. self.assertEqual(len(inner.defects), 1)
  1280. unless(isinstance(inner.defects[0],
  1281. Errors.StartBoundaryNotFoundDefect))
  1282. def test_multipart_no_boundary(self):
  1283. unless = self.assertTrue
  1284. msg = self._msgobj('msg_25.txt')
  1285. unless(isinstance(msg.get_payload(), str))
  1286. self.assertEqual(len(msg.defects), 2)
  1287. unless(isinstance(msg.defects[0], Errors.NoBoundaryInMultipartDefect))
  1288. unless(isinstance(msg.defects[1],
  1289. Errors.MultipartInvariantViolationDefect))
  1290. def test_invalid_content_type(self):
  1291. eq = self.assertEqual
  1292. neq = self.ndiffAssertEqual
  1293. msg = Message()
  1294. # RFC 2045, $5.2 says invalid yields text/plain
  1295. msg['Content-Type'] = 'text'
  1296. eq(msg.get_content_maintype(), 'text')
  1297. eq(msg.get_content_subtype(), 'plain')
  1298. eq(msg.get_content_type(), 'text/plain')
  1299. # Clear the old value and try something /really/ invalid
  1300. del msg['content-type']
  1301. msg['Content-Type'] = 'foo'
  1302. eq(msg.get_content_maintype(), 'text')
  1303. eq(msg.get_content_subtype(), 'plain')
  1304. eq(msg.get_content_type(), 'text/plain')
  1305. # Still, make sure that the message is idempotently generated
  1306. s = StringIO()
  1307. g = Generator(s)
  1308. g.flatten(msg)
  1309. neq(s.getvalue(), 'Content-Type: foo\n\n')
  1310. def test_no_start_boundary(self):
  1311. eq = self.ndiffAssertEqual
  1312. msg = self._msgobj('msg_31.txt')
  1313. eq(msg.get_payload(), """\
  1314. --BOUNDARY
  1315. Content-Type: text/plain
  1316. message 1
  1317. --BOUNDARY
  1318. Content-Type: text/plain
  1319. message 2
  1320. --BOUNDARY--
  1321. """)
  1322. def test_no_separating_blank_line(self):
  1323. eq = self.ndiffAssertEqual
  1324. msg = self._msgobj('msg_35.txt')
  1325. eq(msg.as_string(), """\
  1326. From: aperson@dom.ain
  1327. To: bperson@dom.ain
  1328. Subject: here's something interesting
  1329. counter to RFC 2822, there's no separating newline here
  1330. """)
  1331. def test_lying_multipart(self):
  1332. unless = self.assertTrue
  1333. msg = self._msgobj('msg_41.txt')
  1334. unless(hasattr(msg, 'defects'))
  1335. self.assertEqual(len(msg.defects), 2)
  1336. unless(isinstance(msg.defects[0], Errors.NoBoundaryInMultipartDefect))
  1337. unless(isinstance(msg.defects[1],
  1338. Errors.MultipartInvariantViolationDefect))
  1339. def test_missing_start_boundary(self):
  1340. outer = self._msgobj('msg_42.txt')
  1341. # The message structure is:
  1342. #
  1343. # multipart/mixed
  1344. # text/plain
  1345. # message/rfc822
  1346. # multipart/mixed [*]
  1347. #
  1348. # [*] This message is missing its start boundary
  1349. bad = outer.get_payload(1).get_payload(0)
  1350. self.assertEqual(len(bad.defects), 1)
  1351. self.assertTrue(isinstance(bad.defects[0],
  1352. Errors.StartBoundaryNotFoundDefect))
  1353. def test_first_line_is_continuation_header(self):
  1354. eq = self.assertEqual
  1355. m = ' Line 1\nLine 2\nLine 3'
  1356. msg = email.message_from_string(m)
  1357. eq(msg.keys(), [])
  1358. eq(msg.get_payload(), 'Line 2\nLine 3')
  1359. eq(len(msg.defects), 1)
  1360. self.assertTrue(isinstance(msg.defects[0],
  1361. Errors.FirstHeaderLineIsContinuationDefect))
  1362. eq(msg.defects[0].line, ' Line 1\n')
  1363. # Test RFC 2047 header encoding and decoding
  1364. class TestRFC2047(unittest.TestCase):
  1365. def test_rfc2047_multiline(self):
  1366. eq = self.assertEqual
  1367. s = """Re: =?mac-iceland?q?r=8Aksm=9Arg=8Cs?= baz
  1368. foo bar =?mac-iceland?q?r=8Aksm=9Arg=8Cs?="""
  1369. dh = decode_header(s)
  1370. eq(dh, [
  1371. ('Re:', None),
  1372. ('r\x8aksm\x9arg\x8cs', 'mac-iceland'),
  1373. ('baz foo bar', None),
  1374. ('r\x8aksm\x9arg\x8cs', 'mac-iceland')])
  1375. eq(str(make_header(dh)),
  1376. """Re: =?mac-iceland?q?r=8Aksm=9Arg=8Cs?= baz foo bar
  1377. =?mac-iceland?q?r=8Aksm=9Arg=8Cs?=""")
  1378. def test_whitespace_eater_unicode(self):
  1379. eq = self.assertEqual
  1380. s = '=?ISO-8859-1?Q?Andr=E9?= Pirard <pirard@dom.ain>'
  1381. dh = decode_header(s)
  1382. eq(dh, [('Andr\xe9', 'iso-8859-1'), ('Pirard <pirard@dom.ain>', None)])
  1383. hu = unicode(make_header(dh)).encode('latin-1')
  1384. eq(hu, 'Andr\xe9 Pirard <pirard@dom.ain>')
  1385. def test_whitespace_eater_unicode_2(self):
  1386. eq = self.assertEqual
  1387. s = 'The =?iso-8859-1?b?cXVpY2sgYnJvd24gZm94?= jumped over the =?iso-8859-1?b?bGF6eSBkb2c=?='
  1388. dh = decode_header(s)
  1389. eq(dh, [('The', None), ('quick brown fox', 'iso-8859-1'),
  1390. ('jumped over the', None), ('lazy dog', 'iso-8859-1')])
  1391. hu = make_header(dh).__unicode__()
  1392. eq(hu, u'The quick brown fox jumped over the lazy dog')
  1393. def test_rfc2047_without_whitespace(self):
  1394. s = 'Sm=?ISO-8859-1?B?9g==?=rg=?ISO-8859-1?B?5Q==?=sbord'
  1395. dh = decode_header(s)
  1396. self.assertEqual(dh, [(s, None)])
  1397. def test_rfc2047_with_whitespace(self):
  1398. s = 'Sm =?ISO-8859-1?B?9g==?= rg =?ISO-8859-1?B?5Q==?= sbord'
  1399. dh = decode_header(s)
  1400. self.assertEqual(dh, [('Sm', None), ('\xf6', 'iso-8859-1'),
  1401. ('rg', None), ('\xe5', 'iso-8859-1'),
  1402. ('sbord', None)])
  1403. def test_rfc2047_B_bad_padding(self):
  1404. s = '=?iso-8859-1?B?%s?='
  1405. data = [ # only test complete bytes
  1406. ('dm==', 'v'), ('dm=', 'v'), ('dm', 'v'),
  1407. ('dmk=', 'vi'), ('dmk', 'vi')
  1408. ]
  1409. for q, a in data:
  1410. dh = decode_header(s % q)
  1411. self.assertEqual(dh, [(a, 'iso-8859-1')])
  1412. def test_rfc2047_Q_invalid_digits(self):
  1413. # issue 10004.
  1414. s = '=?iso-8659-1?Q?andr=e9=zz?='
  1415. self.assertEqual(decode_header(s),
  1416. [(b'andr\xe9=zz', 'iso-8659-1')])
  1417. # Test the MIMEMessage class
  1418. class TestMIMEMessage(TestEmailBase):
  1419. def setUp(self):
  1420. fp = openfile('msg_11.txt')
  1421. try:
  1422. self._text = fp.read()
  1423. finally:
  1424. fp.close()
  1425. def test_type_error(self):
  1426. self.assertRaises(TypeError, MIMEMessage, 'a plain string')
  1427. def test_valid_argument(self):
  1428. eq = self.assertEqual
  1429. unless = self.assertTrue
  1430. subject = 'A sub-message'
  1431. m = Message()
  1432. m['Subject'] = subject
  1433. r = MIMEMessage(m)
  1434. eq(r.get_content_type(), 'message/rfc822')
  1435. payload = r.get_payload()
  1436. unless(isinstance(payload, list))
  1437. eq(len(payload), 1)
  1438. subpart = payload[0]
  1439. unless(subpart is m)
  1440. eq(subpart['subject'], subject)
  1441. def test_bad_multipart(self):
  1442. eq = self.assertEqual
  1443. msg1 = Message()
  1444. msg1['Subject'] = 'subpart 1'
  1445. msg2 = Message()
  1446. msg2['Subject'] = 'subpart 2'
  1447. r = MIMEMessage(msg1)
  1448. self.assertRaises(Errors.MultipartConversionError, r.attach, msg2)
  1449. def test_generate(self):
  1450. # First craft the message to be encapsulated
  1451. m = Message()
  1452. m['Subject'] = 'An enclosed message'
  1453. m.set_payload('Here is the body of the message.\n')
  1454. r = MIMEMessage(m)
  1455. r['Subject'] = 'The enclosing message'
  1456. s = StringIO()
  1457. g = Generator(s)
  1458. g.flatten(r)
  1459. self.assertEqual(s.getvalue(), """\
  1460. Content-Type: message/rfc822
  1461. MIME-Version: 1.0
  1462. Subject: The enclosing message
  1463. Subject: An enclosed message
  1464. Here is the body of the message.
  1465. """)
  1466. def test_parse_message_rfc822(self):
  1467. eq = self.assertEqual
  1468. unless = self.assertTrue
  1469. msg = self._msgobj('msg_11.txt')
  1470. eq(msg.get_content_type(), 'message/rfc822')
  1471. payload = msg.get_payload()
  1472. unless(isinstance(payload, list))
  1473. eq(len(payload), 1)
  1474. submsg = payload[0]
  1475. self.assertTrue(isinstance(submsg, Message))
  1476. eq(submsg['subject'], 'An enclosed message')
  1477. eq(submsg.get_payload(), 'Here is the body of the message.\n')
  1478. def test_dsn(self):
  1479. eq = self.assertEqual
  1480. unless = self.assertTrue
  1481. # msg 16 is a Delivery Status Notification, see RFC 1894
  1482. msg = self._msgobj('msg_16.txt')
  1483. eq(msg.get_content_type(), 'multipart/report')
  1484. unless(msg.is_multipart())
  1485. eq(len(msg.get_payload()), 3)
  1486. # Subpart 1 is a text/plain, human readable section
  1487. subpart = msg.get_payload(0)
  1488. eq(subpart.get_content_type(), 'text/plain')
  1489. eq(subpart.get_payload(), """\
  1490. This report relates to a message you sent with the following header fields:
  1491. Message-id: <002001c144a6$8752e060$56104586@oxy.edu>
  1492. Date: Sun, 23 Sep 2001 20:10:55 -0700
  1493. From: "Ian T. Henry" <henryi@oxy.edu>
  1494. To: SoCal Raves <scr@socal-raves.org>
  1495. Subject: [scr] yeah for Ians!!
  1496. Your message cannot be delivered to the following recipients:
  1497. Recipient address: jangel1@cougar.noc.ucla.edu
  1498. Reason: recipient reached disk quota
  1499. """)
  1500. # Subpart 2 contains the machine parsable DSN information. It
  1501. # consists of two blocks of headers, represented by two nested Message
  1502. # objects.
  1503. subpart = msg.get_payload(1)
  1504. eq(subpart.get_content_type(), 'message/delivery-status')
  1505. eq(len(subpart.get_payload()), 2)
  1506. # message/delivery-status should treat each block as a bunch of
  1507. # headers, i.e. a bunch of Message objects.
  1508. dsn1 = subpart.get_payload(0)
  1509. unless(isinstance(dsn1, Message))
  1510. eq(dsn1['original-envelope-id'], '0GK500B4HD0888@cougar.noc.ucla.edu')
  1511. eq(dsn1.get_param('dns', header='reporting-mta'), '')
  1512. # Try a missing one <wink>
  1513. eq(dsn1.get_param('nsd', header='reporting-mta'), None)
  1514. dsn2 = subpart.get_payload(1)
  1515. unless(isinstance(dsn2, Message))
  1516. eq(dsn2['action'], 'failed')
  1517. eq(dsn2.get_params(header='original-recipient'),
  1518. [('rfc822', ''), ('jangel1@cougar.noc.ucla.edu', '')])
  1519. eq(dsn2.get_param('rfc822', header='final-recipient'), '')
  1520. # Subpart 3 is the original message
  1521. subpart = msg.get_payload(2)
  1522. eq(subpart.get_content_type(), 'message/rfc822')
  1523. payload = subpart.get_payload()
  1524. unless(isinstance(payload, list))
  1525. eq(len(payload), 1)
  1526. subsubpart = payload[0]
  1527. unless(isinstance(subsubpart, Message))
  1528. eq(subsubpart.get_content_type(), 'text/plain')
  1529. eq(subsubpart['message-id'],
  1530. '<002001c144a6$8752e060$56104586@oxy.edu>')
  1531. def test_epilogue(self):
  1532. eq = self.ndiffAssertEqual
  1533. fp = openfile('msg_21.txt')
  1534. try:
  1535. text = fp.read()
  1536. finally:
  1537. fp.close()
  1538. msg = Message()
  1539. msg['From'] = 'aperson@dom.ain'
  1540. msg['To'] = 'bperson@dom.ain'
  1541. msg['Subject'] = 'Test'
  1542. msg.preamble = 'MIME message'
  1543. msg.epilogue = 'End of MIME message\n'
  1544. msg1 = MIMEText('One')
  1545. msg2 = MIMEText('Two')
  1546. msg.add_header('Content-Type', 'multipart/mixed', boundary='BOUNDARY')
  1547. msg.attach(msg1)
  1548. msg.attach(msg2)
  1549. sfp = StringIO()
  1550. g = Generator(sfp)
  1551. g.flatten(msg)
  1552. eq(sfp.getvalue(), text)
  1553. def test_no_nl_preamble(self):
  1554. eq = self.ndiffAssertEqual
  1555. msg = Message()
  1556. msg['From'] = 'aperson@dom.ain'
  1557. msg['To'] = 'bperson@dom.ain'
  1558. msg['Subject'] = 'Test'
  1559. msg.preamble = 'MIME message'
  1560. msg.epilogue = ''
  1561. msg1 = MIMEText('One')
  1562. msg2 = MIMEText('Two')
  1563. msg.add_header('Content-Type', 'multipart/mixed', boundary='BOUNDARY')
  1564. msg.attach(msg1)
  1565. msg.attach(msg2)
  1566. eq(msg.as_string(), """\
  1567. From: aperson@dom.ain
  1568. To: bperson@dom.ain
  1569. Subject: Test
  1570. Content-Type: multipart/mixed; boundary="BOUNDARY"
  1571. MIME message
  1572. --BOUNDARY
  1573. Content-Type: text/plain; charset="us-ascii"
  1574. MIME-Version: 1.0
  1575. Content-Transfer-Encoding: 7bit
  1576. One
  1577. --BOUNDARY
  1578. Content-Type: text/plain; charset="us-ascii"
  1579. MIME-Version: 1.0
  1580. Content-Transfer-Encoding: 7bit
  1581. Two
  1582. --BOUNDARY--
  1583. """)
  1584. def test_default_type(self):
  1585. eq = self.assertEqual
  1586. fp = openfile('msg_30.txt')
  1587. try:
  1588. msg = email.message_from_file(fp)
  1589. finally:
  1590. fp.close()
  1591. container1 = msg.get_payload(0)
  1592. eq(container1.get_default_type(), 'message/rfc822')
  1593. eq(container1.get_content_type(), 'message/rfc822')
  1594. container2 = msg.get_payload(1)
  1595. eq(container2.get_default_type(), 'message/rfc822')
  1596. eq(container2.get_content_type(), 'message/rfc822')
  1597. container1a = container1.get_payload(0)
  1598. eq(container1a.get_default_type(), 'text/plain')
  1599. eq(container1a.get_content_type(), 'text/plain')
  1600. container2a = container2.get_payload(0)
  1601. eq(container2a.get_default_type(), 'text/plain')
  1602. eq(container2a.get_content_type(), 'text/plain')
  1603. def test_default_type_with_explicit_container_type(self):
  1604. eq = self.assertEqual
  1605. fp = openfile('msg_28.txt')
  1606. try:
  1607. msg = email.message_from_file(fp)
  1608. finally:
  1609. fp.close()
  1610. container1 = msg.get_payload(0)
  1611. eq(container1.get_default_type(), 'message/rfc822')
  1612. eq(container1.get_content_type(), 'message/rfc822')
  1613. container2 = msg.get_payload(1)
  1614. eq(container2.get_default_type(), 'message/rfc822')
  1615. eq(container2.get_content_type(), 'message/rfc822')
  1616. container1a = container1.get_payload(0)
  1617. eq(container1a.get_default_type(), 'text/plain')
  1618. eq(container1a.get_content_type(), 'text/plain')
  1619. container2a = container2.get_payload(0)
  1620. eq(container2a.get_default_type(), 'text/plain')
  1621. eq(container2a.get_content_type(), 'text/plain')
  1622. def test_default_type_non_parsed(self):
  1623. eq = self.assertEqual
  1624. neq = self.ndiffAssertEqual
  1625. # Set up container
  1626. container = MIMEMultipart('digest', 'BOUNDARY')
  1627. container.epilogue = ''
  1628. # Set up subparts
  1629. subpart1a = MIMEText('message 1\n')
  1630. subpart2a = MIMEText('message 2\n')
  1631. subpart1 = MIMEMessage(subpart1a)
  1632. subpart2 = MIMEMessage(subpart2a)
  1633. container.attach(subpart1)
  1634. container.attach(subpart2)
  1635. eq(subpart1.get_content_type(), 'message/rfc822')
  1636. eq(subpart1.get_default_type(), 'message/rfc822')
  1637. eq(subpart2.get_content_type(), 'message/rfc822')
  1638. eq(subpart2.get_default_type(), 'message/rfc822')
  1639. neq(container.as_string(0), '''\
  1640. Content-Type: multipart/digest; boundary="BOUNDARY"
  1641. MIME-Version: 1.0
  1642. --BOUNDARY
  1643. Content-Type: message/rfc822
  1644. MIME-Version: 1.0
  1645. Content-Type: text/plain; charset="us-ascii"
  1646. MIME-Version: 1.0
  1647. Content-Transfer-Encoding: 7bit
  1648. message 1
  1649. --BOUNDARY
  1650. Content-Type: message/rfc822
  1651. MIME-Version: 1.0
  1652. Content-Type: text/plain; charset="us-ascii"
  1653. MIME-Version: 1.0
  1654. Content-Transfer-Encoding: 7bit
  1655. message 2
  1656. --BOUNDARY--
  1657. ''')
  1658. del subpart1['content-type']
  1659. del subpart1['mime-version']
  1660. del subpart2['content-type']
  1661. del subpart2['mime-version']
  1662. eq(subpart1.get_content_type(), 'message/rfc822')
  1663. eq(subpart1.get_default_type(), 'message/rfc822')
  1664. eq(subpart2.get_content_type(), 'message/rfc822')
  1665. eq(subpart2.get_default_type(), 'message/rfc822')
  1666. neq(container.as_string(0), '''\
  1667. Content-Type: multipart/digest; boundary="BOUNDARY"
  1668. MIME-Version: 1.0
  1669. --BOUNDARY
  1670. Content-Type: text/plain; charset="us-ascii"
  1671. MIME-Version: 1.0
  1672. Content-Transfer-Encoding: 7bit
  1673. message 1
  1674. --BOUNDARY
  1675. Content-Type: text/plain; charset="us-ascii"
  1676. MIME-Version: 1.0
  1677. Content-Transfer-Encoding: 7bit
  1678. message 2
  1679. --BOUNDARY--
  1680. ''')
  1681. def test_mime_attachments_in_constructor(self):
  1682. eq = self.assertEqual
  1683. text1 = MIMEText('')
  1684. text2 = MIMEText('')
  1685. msg = MIMEMultipart(_subparts=(text1, text2))
  1686. eq(len(msg.get_payload()), 2)
  1687. eq(msg.get_payload(0), text1)
  1688. eq(msg.get_payload(1), text2)
  1689. def test_default_multipart_constructor(self):
  1690. msg = MIMEMultipart()
  1691. self.assertTrue(msg.is_multipart())
  1692. # A general test of parser->model->generator idempotency. IOW, read a message
  1693. # in, parse it into a message object tree, then without touching the tree,
  1694. # regenerate the plain text. The original text and the transformed text
  1695. # should be identical. Note: that we ignore the Unix-From since that may
  1696. # contain a changed date.
  1697. class TestIdempotent(TestEmailBase):
  1698. def _msgobj(self, filename):
  1699. fp = openfile(filename)
  1700. try:
  1701. data = fp.read()
  1702. finally:
  1703. fp.close()
  1704. msg = email.message_from_string(data)
  1705. return msg, data
  1706. def _idempotent(self, msg, text):
  1707. eq = self.ndiffAssertEqual
  1708. s = StringIO()
  1709. g = Generator(s, maxheaderlen=0)
  1710. g.flatten(msg)
  1711. eq(text, s.getvalue())
  1712. def test_parse_text_message(self):
  1713. eq = self.assertEqual
  1714. msg, text = self._msgobj('msg_01.txt')
  1715. eq(msg.get_content_type(), 'text/plain')
  1716. eq(msg.get_content_maintype(), 'text')
  1717. eq(msg.get_content_subtype(), 'plain')
  1718. eq(msg.get_params()[1], ('charset', 'us-ascii'))
  1719. eq(msg.get_param('charset'), 'us-ascii')
  1720. eq(msg.preamble, None)
  1721. eq(msg.epilogue, None)
  1722. self._idempotent(msg, text)
  1723. def test_parse_untyped_message(self):
  1724. eq = self.assertEqual
  1725. msg, text = self._msgobj('msg_03.txt')
  1726. eq(msg.get_content_type(), 'text/plain')
  1727. eq(msg.get_params(), None)
  1728. eq(msg.get_param('charset'), None)
  1729. self._idempotent(msg, text)
  1730. def test_simple_multipart(self):
  1731. msg, text = self._msgobj('msg_04.txt')
  1732. self._idempotent(msg, text)
  1733. def test_MIME_digest(self):
  1734. msg, text = self._msgobj('msg_02.txt')
  1735. self._idempotent(msg, text)
  1736. def test_long_header(self):
  1737. msg, text = self._msgobj('msg_27.txt')
  1738. self._idempotent(msg, text)
  1739. def test_MIME_digest_with_part_headers(self):
  1740. msg, text = self._msgobj('msg_28.txt')
  1741. self._idempotent(msg, text)
  1742. def test_mixed_with_image(self):
  1743. msg, text = self._msgobj('msg_06.txt')
  1744. self._idempotent(msg, text)
  1745. def test_multipart_report(self):
  1746. msg, text = self._msgobj('msg_05.txt')
  1747. self._idempotent(msg, text)
  1748. def test_dsn(self):
  1749. msg, text = self._msgobj('msg_16.txt')
  1750. self._idempotent(msg, text)
  1751. def test_preamble_epilogue(self):
  1752. msg, text = self._msgobj('msg_21.txt')
  1753. self._idempotent(msg, text)
  1754. def test_multipart_one_part(self):
  1755. msg, text = self._msgobj('msg_23.txt')
  1756. self._idempotent(msg, text)
  1757. def test_multipart_no_parts(self):
  1758. msg, text = self._msgobj('msg_24.txt')
  1759. self._idempotent(msg, text)
  1760. def test_no_start_boundary(self):
  1761. msg, text = self._msgobj('msg_31.txt')
  1762. self._idempotent(msg, text)
  1763. def test_rfc2231_charset(self):
  1764. msg, text = self._msgobj('msg_32.txt')
  1765. self._idempotent(msg, text)
  1766. def test_more_rfc2231_parameters(self):
  1767. msg, text = self._msgobj('msg_33.txt')
  1768. self._idempotent(msg, text)
  1769. def test_text_plain_in_a_multipart_digest(self):
  1770. msg, text = self._msgobj('msg_34.txt')
  1771. self._idempotent(msg, text)
  1772. def test_nested_multipart_mixeds(self):
  1773. msg, text = self._msgobj('msg_12a.txt')
  1774. self._idempotent(msg, text)
  1775. def test_message_external_body_idempotent(self):
  1776. msg, text = self._msgobj('msg_36.txt')
  1777. self._idempotent(msg, text)
  1778. def test_content_type(self):
  1779. eq = self.assertEqual
  1780. unless = self.assertTrue
  1781. # Get a message object and reset the seek pointer for other tests
  1782. msg, text = self._msgobj('msg_05.txt')
  1783. eq(msg.get_content_type(), 'multipart/report')
  1784. # Test the Content-Type: parameters
  1785. params = {}
  1786. for pk, pv in msg.get_params():
  1787. params[pk] = pv
  1788. eq(params['report-type'], 'delivery-status')
  1789. eq(params['boundary'], 'D1690A7AC1.996856090/mail.example.com')
  1790. eq(msg.preamble, 'This is a MIME-encapsulated message.\n')
  1791. eq(msg.epilogue, '\n')
  1792. eq(len(msg.get_payload()), 3)
  1793. # Make sure the subparts are what we expect
  1794. msg1 = msg.get_payload(0)
  1795. eq(msg1.get_content_type(), 'text/plain')
  1796. eq(msg1.get_payload(), 'Yadda yadda yadda\n')
  1797. msg2 = msg.get_payload(1)
  1798. eq(msg2.get_content_type(), 'text/plain')
  1799. eq(msg2.get_payload(), 'Yadda yadda yadda\n')
  1800. msg3 = msg.get_payload(2)
  1801. eq(msg3.get_content_type(), 'message/rfc822')
  1802. self.assertTrue(isinstance(msg3, Message))
  1803. payload = msg3.get_payload()
  1804. unless(isinstance(payload, list))
  1805. eq(len(payload), 1)
  1806. msg4 = payload[0]
  1807. unless(isinstance(msg4, Message))
  1808. eq(msg4.get_payload(), 'Yadda yadda yadda\n')
  1809. def test_parser(self):
  1810. eq = self.assertEqual
  1811. unless = self.assertTrue
  1812. msg, text = self._msgobj('msg_06.txt')
  1813. # Check some of the outer headers
  1814. eq(msg.get_content_type(), 'message/rfc822')
  1815. # Make sure the payload is a list of exactly one sub-Message, and that
  1816. # that submessage has a type of text/plain
  1817. payload = msg.get_payload()
  1818. unless(isinstance(payload, list))
  1819. eq(len(payload), 1)
  1820. msg1 = payload[0]
  1821. self.assertTrue(isinstance(msg1, Message))
  1822. eq(msg1.get_content_type(), 'text/plain')
  1823. self.assertTrue(isinstance(msg1.get_payload(), str))
  1824. eq(msg1.get_payload(), '\n')
  1825. # Test various other bits of the package's functionality
  1826. class TestMiscellaneous(TestEmailBase):
  1827. def test_message_from_string(self):
  1828. fp = openfile('msg_01.txt')
  1829. try:
  1830. text = fp.read()
  1831. finally:
  1832. fp.close()
  1833. msg = email.message_from_string(text)
  1834. s = StringIO()
  1835. # Don't wrap/continue long headers since we're trying to test
  1836. # idempotency.
  1837. g = Generator(s, maxheaderlen=0)
  1838. g.flatten(msg)
  1839. self.assertEqual(text, s.getvalue())
  1840. def test_message_from_file(self):
  1841. fp = openfile('msg_01.txt')
  1842. try:
  1843. text = fp.read()
  1844. fp.seek(0)
  1845. msg = email.message_from_file(fp)
  1846. s = StringIO()
  1847. # Don't wrap/continue long headers since we're trying to test
  1848. # idempotency.
  1849. g = Generator(s, maxheaderlen=0)
  1850. g.flatten(msg)
  1851. self.assertEqual(text, s.getvalue())
  1852. finally:
  1853. fp.close()
  1854. def test_message_from_string_with_class(self):
  1855. unless = self.assertTrue
  1856. fp = openfile('msg_01.txt')
  1857. try:
  1858. text = fp.read()
  1859. finally:
  1860. fp.close()
  1861. # Create a subclass
  1862. class MyMessage(Message):
  1863. pass
  1864. msg = email.message_from_string(text, MyMessage)
  1865. unless(isinstance(msg, MyMessage))
  1866. # Try something more complicated
  1867. fp = openfile('msg_02.txt')
  1868. try:
  1869. text = fp.read()
  1870. finally:
  1871. fp.close()
  1872. msg = email.message_from_string(text, MyMessage)
  1873. for subpart in msg.walk():
  1874. unless(isinstance(subpart, MyMessage))
  1875. def test_message_from_file_with_class(self):
  1876. unless = self.assertTrue
  1877. # Create a subclass
  1878. class MyMessage(Message):
  1879. pass
  1880. fp = openfile('msg_01.txt')
  1881. try:
  1882. msg = email.message_from_file(fp, MyMessage)
  1883. finally:
  1884. fp.close()
  1885. unless(isinstance(msg, MyMessage))
  1886. # Try something more complicated
  1887. fp = openfile('msg_02.txt')
  1888. try:
  1889. msg = email.message_from_file(fp, MyMessage)
  1890. finally:
  1891. fp.close()
  1892. for subpart in msg.walk():
  1893. unless(isinstance(subpart, MyMessage))
  1894. def test__all__(self):
  1895. module = __import__('email')
  1896. all = module.__all__
  1897. all.sort()
  1898. self.assertEqual(all, [
  1899. # Old names
  1900. 'Charset', 'Encoders', 'Errors', 'Generator',
  1901. 'Header', 'Iterators', 'MIMEAudio', 'MIMEBase',
  1902. 'MIMEImage', 'MIMEMessage', 'MIMEMultipart',
  1903. 'MIMENonMultipart', 'MIMEText', 'Message',
  1904. 'Parser', 'Utils', 'base64MIME',
  1905. # new names
  1906. 'base64mime', 'charset', 'encoders', 'errors', 'generator',
  1907. 'header', 'iterators', 'message', 'message_from_file',
  1908. 'message_from_string', 'mime', 'parser',
  1909. 'quopriMIME', 'quoprimime', 'utils',
  1910. ])
  1911. def test_formatdate(self):
  1912. now = time.time()
  1913. self.assertEqual(Utils.parsedate(Utils.formatdate(now))[:6],
  1914. time.gmtime(now)[:6])
  1915. def test_formatdate_localtime(self):
  1916. now = time.time()
  1917. self.assertEqual(
  1918. Utils.parsedate(Utils.formatdate(now, localtime=True))[:6],
  1919. time.localtime(now)[:6])
  1920. def test_formatdate_usegmt(self):
  1921. now = time.time()
  1922. self.assertEqual(
  1923. Utils.formatdate(now, localtime=False),
  1924. time.strftime('%a, %d %b %Y %H:%M:%S -0000', time.gmtime(now)))
  1925. self.assertEqual(
  1926. Utils.formatdate(now, localtime=False, usegmt=True),
  1927. time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime(now)))
  1928. def test_parsedate_none(self):
  1929. self.assertEqual(Utils.parsedate(''), None)
  1930. def test_parsedate_compact(self):
  1931. # The FWS after the comma is optional
  1932. self.assertEqual(Utils.parsedate('Wed,3 Apr 2002 14:58:26 +0800'),
  1933. Utils.parsedate('Wed, 3 Apr 2002 14:58:26 +0800'))
  1934. def test_parsedate_no_dayofweek(self):
  1935. eq = self.assertEqual
  1936. eq(Utils.parsedate_tz('25 Feb 2003 13:47:26 -0800'),
  1937. (2003, 2, 25, 13, 47, 26, 0, 1, -1, -28800))
  1938. def test_parsedate_compact_no_dayofweek(self):
  1939. eq = self.assertEqual
  1940. eq(Utils.parsedate_tz('5 Feb 2003 13:47:26 -0800'),
  1941. (2003, 2, 5, 13, 47, 26, 0, 1, -1, -28800))
  1942. def test_parsedate_acceptable_to_time_functions(self):
  1943. eq = self.assertEqual
  1944. timetup = Utils.parsedate('5 Feb 2003 13:47:26 -0800')
  1945. t = int(time.mktime(timetup))
  1946. eq(time.localtime(t)[:6], timetup[:6])
  1947. eq(int(time.strftime('%Y', timetup)), 2003)
  1948. timetup = Utils.parsedate_tz('5 Feb 2003 13:47:26 -0800')
  1949. t = int(time.mktime(timetup[:9]))
  1950. eq(time.localtime(t)[:6], timetup[:6])
  1951. eq(int(time.strftime('%Y', timetup[:9])), 2003)
  1952. def test_parsedate_y2k(self):
  1953. """Test for parsing a date with a two-digit year.
  1954. Parsing a date with a two-digit year should return the correct
  1955. four-digit year. RFC822 allows two-digit years, but RFC2822 (which
  1956. obsoletes RFC822) requires four-digit years.
  1957. """
  1958. self.assertEqual(Utils.parsedate_tz('25 Feb 03 13:47:26 -0800'),
  1959. Utils.parsedate_tz('25 Feb 2003 13:47:26 -0800'))
  1960. self.assertEqual(Utils.parsedate_tz('25 Feb 71 13:47:26 -0800'),
  1961. Utils.parsedate_tz('25 Feb 1971 13:47:26 -0800'))
  1962. def test_parseaddr_empty(self):
  1963. self.assertEqual(Utils.parseaddr('<>'), ('', ''))
  1964. self.assertEqual(Utils.formataddr(Utils.parseaddr('<>')), '')
  1965. def test_noquote_dump(self):
  1966. self.assertEqual(
  1967. Utils.formataddr(('A Silly Person', 'person@dom.ain')),
  1968. 'A Silly Person <person@dom.ain>')
  1969. def test_escape_dump(self):
  1970. self.assertEqual(
  1971. Utils.formataddr(('A (Very) Silly Person', 'person@dom.ain')),
  1972. r'"A \(Very\) Silly Person" <person@dom.ain>')
  1973. a = r'A \(Special\) Person'
  1974. b = 'person@dom.ain'
  1975. self.assertEqual(Utils.parseaddr(Utils.formataddr((a, b))), (a, b))
  1976. def test_escape_backslashes(self):
  1977. self.assertEqual(
  1978. Utils.formataddr(('Arthur \Backslash\ Foobar', 'person@dom.ain')),
  1979. r'"Arthur \\Backslash\\ Foobar" <person@dom.ain>')
  1980. a = r'Arthur \Backslash\ Foobar'
  1981. b = 'person@dom.ain'
  1982. self.assertEqual(Utils.parseaddr(Utils.formataddr((a, b))), (a, b))
  1983. def test_name_with_dot(self):
  1984. x = 'John X. Doe <jxd@example.com>'
  1985. y = '"John X. Doe" <jxd@example.com>'
  1986. a, b = ('John X. Doe', 'jxd@example.com')
  1987. self.assertEqual(Utils.parseaddr(x), (a, b))
  1988. self.assertEqual(Utils.parseaddr(y), (a, b))
  1989. # formataddr() quotes the name if there's a dot in it
  1990. self.assertEqual(Utils.formataddr((a, b)), y)
  1991. def test_parseaddr_preserves_quoted_pairs_in_addresses(self):
  1992. # issue 10005. Note that in the third test the second pair of
  1993. # backslashes is not actually a quoted pair because it is not inside a
  1994. # comment or quoted string: the address being parsed has a quoted
  1995. # string containing a quoted backslash, followed by 'example' and two
  1996. # backslashes, followed by another quoted string containing a space and
  1997. # the word 'example'. parseaddr copies those two backslashes
  1998. # literally. Per rfc5322 this is not technically correct since a \ may
  1999. # not appear in an address outside of a quoted string. It is probably
  2000. # a sensible Postel interpretation, though.
  2001. eq = self.assertEqual
  2002. eq(Utils.parseaddr('""example" example"@example.com'),
  2003. ('', '""example" example"@example.com'))
  2004. eq(Utils.parseaddr('"\\"example\\" example"@example.com'),
  2005. ('', '"\\"example\\" example"@example.com'))
  2006. eq(Utils.parseaddr('"\\\\"example\\\\" example"@example.com'),
  2007. ('', '"\\\\"example\\\\" example"@example.com'))
  2008. def test_multiline_from_comment(self):
  2009. x = """\
  2010. Foo
  2011. \tBar <foo@example.com>"""
  2012. self.assertEqual(Utils.parseaddr(x), ('Foo Bar', 'foo@example.com'))
  2013. def test_quote_dump(self):
  2014. self.assertEqual(
  2015. Utils.formataddr(('A Silly; Person', 'person@dom.ain')),
  2016. r'"A Silly; Person" <person@dom.ain>')
  2017. def test_fix_eols(self):
  2018. eq = self.assertEqual
  2019. eq(Utils.fix_eols('hello'), 'hello')
  2020. eq(Utils.fix_eols('hello\n'), 'hello\r\n')
  2021. eq(Utils.fix_eols('hello\r'), 'hello\r\n')
  2022. eq(Utils.fix_eols('hello\r\n'), 'hello\r\n')
  2023. eq(Utils.fix_eols('hello\n\r'), 'hello\r\n\r\n')
  2024. def test_charset_richcomparisons(self):
  2025. eq = self.assertEqual
  2026. ne = self.assertNotEqual
  2027. cset1 = Charset()
  2028. cset2 = Charset()
  2029. eq(cset1, 'us-ascii')
  2030. eq(cset1, 'US-ASCII')
  2031. eq(cset1, 'Us-AsCiI')
  2032. eq('us-ascii', cset1)
  2033. eq('US-ASCII', cset1)
  2034. eq('Us-AsCiI', cset1)
  2035. ne(cset1, 'usascii')
  2036. ne(cset1, 'USASCII')
  2037. ne(cset1, 'UsAsCiI')
  2038. ne('usascii', cset1)
  2039. ne('USASCII', cset1)
  2040. ne('UsAsCiI', cset1)
  2041. eq(cset1, cset2)
  2042. eq(cset2, cset1)
  2043. def test_getaddresses(self):
  2044. eq = self.assertEqual
  2045. eq(Utils.getaddresses(['aperson@dom.ain (Al Person)',
  2046. 'Bud Person <bperson@dom.ain>']),
  2047. [('Al Person', 'aperson@dom.ain'),
  2048. ('Bud Person', 'bperson@dom.ain')])
  2049. def test_getaddresses_nasty(self):
  2050. eq = self.assertEqual
  2051. eq(Utils.getaddresses(['foo: ;']), [('', '')])
  2052. eq(Utils.getaddresses(
  2053. ['[]*-- =~$']),
  2054. [('', ''), ('', ''), ('', '*--')])
  2055. eq(Utils.getaddresses(
  2056. ['foo: ;', '"Jason R. Mastaler" <jason@dom.ain>']),
  2057. [('', ''), ('Jason R. Mastaler', 'jason@dom.ain')])
  2058. def test_getaddresses_embedded_comment(self):
  2059. """Test proper handling of a nested comment"""
  2060. eq = self.assertEqual
  2061. addrs = Utils.getaddresses(['User ((nested comment)) <foo@bar.com>'])
  2062. eq(addrs[0][1], 'foo@bar.com')
  2063. def test_utils_quote_unquote(self):
  2064. eq = self.assertEqual
  2065. msg = Message()
  2066. msg.add_header('content-disposition', 'attachment',
  2067. filename='foo\\wacky"name')
  2068. eq(msg.get_filename(), 'foo\\wacky"name')
  2069. def test_get_body_encoding_with_bogus_charset(self):
  2070. charset = Charset('not a charset')
  2071. self.assertEqual(charset.get_body_encoding(), 'base64')
  2072. def test_get_body_encoding_with_uppercase_charset(self):
  2073. eq = self.assertEqual
  2074. msg = Message()
  2075. msg['Content-Type'] = 'text/plain; charset=UTF-8'
  2076. eq(msg['content-type'], 'text/plain; charset=UTF-8')
  2077. charsets = msg.get_charsets()
  2078. eq(len(charsets), 1)
  2079. eq(charsets[0], 'utf-8')
  2080. charset = Charset(charsets[0])
  2081. eq(charset.get_body_encoding(), 'base64')
  2082. msg.set_payload('hello world', charset=charset)
  2083. eq(msg.get_payload(), 'aGVsbG8gd29ybGQ=\n')
  2084. eq(msg.get_payload(decode=True), 'hello world')
  2085. eq(msg['content-transfer-encoding'], 'base64')
  2086. # Try another one
  2087. msg = Message()
  2088. msg['Content-Type'] = 'text/plain; charset="US-ASCII"'
  2089. charsets = msg.get_charsets()
  2090. eq(len(charsets), 1)
  2091. eq(charsets[0], 'us-ascii')
  2092. charset = Charset(charsets[0])
  2093. eq(charset.get_body_encoding(), Encoders.encode_7or8bit)
  2094. msg.set_payload('hello world', charset=charset)
  2095. eq(msg.get_payload(), 'hello world')
  2096. eq(msg['content-transfer-encoding'], '7bit')
  2097. def test_charsets_case_insensitive(self):
  2098. lc = Charset('us-ascii')
  2099. uc = Charset('US-ASCII')
  2100. self.assertEqual(lc.get_body_encoding(), uc.get_body_encoding())
  2101. def test_partial_falls_inside_message_delivery_status(self):
  2102. eq = self.ndiffAssertEqual
  2103. # The Parser interface provides chunks of data to FeedParser in 8192
  2104. # byte gulps. SF bug #1076485 found one of those chunks inside
  2105. # message/delivery-status header block, which triggered an
  2106. # unreadline() of NeedMoreData.
  2107. msg = self._msgobj('msg_43.txt')
  2108. sfp = StringIO()
  2109. Iterators._structure(msg, sfp)
  2110. eq(sfp.getvalue(), """\
  2111. multipart/report
  2112. text/plain
  2113. message/delivery-status
  2114. text/plain
  2115. text/plain
  2116. text/plain
  2117. text/plain
  2118. text/plain
  2119. text/plain
  2120. text/plain
  2121. text/plain
  2122. text/plain
  2123. text/plain
  2124. text/plain
  2125. text/plain
  2126. text/plain
  2127. text/plain
  2128. text/plain
  2129. text/plain
  2130. text/plain
  2131. text/plain
  2132. text/plain
  2133. text/plain
  2134. text/plain
  2135. text/plain
  2136. text/plain
  2137. text/plain
  2138. text/plain
  2139. text/plain
  2140. text/rfc822-headers
  2141. """)
  2142. # Test the iterator/generators
  2143. class TestIterators(TestEmailBase):
  2144. def test_body_line_iterator(self):
  2145. eq = self.assertEqual
  2146. neq = self.ndiffAssertEqual
  2147. # First a simple non-multipart message
  2148. msg = self._msgobj('msg_01.txt')
  2149. it = Iterators.body_line_iterator(msg)
  2150. lines = list(it)
  2151. eq(len(lines), 6)
  2152. neq(EMPTYSTRING.join(lines), msg.get_payload())
  2153. # Now a more complicated multipart
  2154. msg = self._msgobj('msg_02.txt')
  2155. it = Iterators.body_line_iterator(msg)
  2156. lines = list(it)
  2157. eq(len(lines), 43)
  2158. fp = openfile('msg_19.txt')
  2159. try:
  2160. neq(EMPTYSTRING.join(lines), fp.read())
  2161. finally:
  2162. fp.close()
  2163. def test_typed_subpart_iterator(self):
  2164. eq = self.assertEqual
  2165. msg = self._msgobj('msg_04.txt')
  2166. it = Iterators.typed_subpart_iterator(msg, 'text')
  2167. lines = []
  2168. subparts = 0
  2169. for subpart in it:
  2170. subparts += 1
  2171. lines.append(subpart.get_payload())
  2172. eq(subparts, 2)
  2173. eq(EMPTYSTRING.join(lines), """\
  2174. a simple kind of mirror
  2175. to reflect upon our own
  2176. a simple kind of mirror
  2177. to reflect upon our own
  2178. """)
  2179. def test_typed_subpart_iterator_default_type(self):
  2180. eq = self.assertEqual
  2181. msg = self._msgobj('msg_03.txt')
  2182. it = Iterators.typed_subpart_iterator(msg, 'text', 'plain')
  2183. lines = []
  2184. subparts = 0
  2185. for subpart in it:
  2186. subparts += 1
  2187. lines.append(subpart.get_payload())
  2188. eq(subparts, 1)
  2189. eq(EMPTYSTRING.join(lines), """\
  2190. Hi,
  2191. Do you like this message?
  2192. -Me
  2193. """)
  2194. def test_pushCR_LF(self):
  2195. '''FeedParser BufferedSubFile.push() assumed it received complete
  2196. line endings. A CR ending one push() followed by a LF starting
  2197. the next push() added an empty line.
  2198. '''
  2199. imt = [
  2200. ("a\r \n", 2),
  2201. ("b", 0),
  2202. ("c\n", 1),
  2203. ("", 0),
  2204. ("d\r\n", 1),
  2205. ("e\r", 0),
  2206. ("\nf", 1),
  2207. ("\r\n", 1),
  2208. ]
  2209. from email.feedparser import BufferedSubFile, NeedMoreData
  2210. bsf = BufferedSubFile()
  2211. om = []
  2212. nt = 0
  2213. for il, n in imt:
  2214. bsf.push(il)
  2215. nt += n
  2216. n1 = 0
  2217. while True:
  2218. ol = bsf.readline()
  2219. if ol == NeedMoreData:
  2220. break
  2221. om.append(ol)
  2222. n1 += 1
  2223. self.assertTrue(n == n1)
  2224. self.assertTrue(len(om) == nt)
  2225. self.assertTrue(''.join([il for il, n in imt]) == ''.join(om))
  2226. class TestParsers(TestEmailBase):
  2227. def test_header_parser(self):
  2228. eq = self.assertEqual
  2229. # Parse only the headers of a complex multipart MIME document
  2230. fp = openfile('msg_02.txt')
  2231. try:
  2232. msg = HeaderParser().parse(fp)
  2233. finally:
  2234. fp.close()
  2235. eq(msg['from'], 'ppp-request@zzz.org')
  2236. eq(msg['to'], 'ppp@zzz.org')
  2237. eq(msg.get_content_type(), 'multipart/mixed')
  2238. self.assertFalse(msg.is_multipart())
  2239. self.assertTrue(isinstance(msg.get_payload(), str))
  2240. def test_whitespace_continuation(self):
  2241. eq = self.assertEqual
  2242. # This message contains a line after the Subject: header that has only
  2243. # whitespace, but it is not empty!
  2244. msg = email.message_from_string("""\
  2245. From: aperson@dom.ain
  2246. To: bperson@dom.ain
  2247. Subject: the next line has a space on it
  2248. \x20
  2249. Date: Mon, 8 Apr 2002 15:09:19 -0400
  2250. Message-ID: spam
  2251. Here's the message body
  2252. """)
  2253. eq(msg['subject'], 'the next line has a space on it\n ')
  2254. eq(msg['message-id'], 'spam')
  2255. eq(msg.get_payload(), "Here's the message body\n")
  2256. def test_whitespace_continuation_last_header(self):
  2257. eq = self.assertEqual
  2258. # Like the previous test, but the subject line is the last
  2259. # header.
  2260. msg = email.message_from_string("""\
  2261. From: aperson@dom.ain
  2262. To: bperson@dom.ain
  2263. Date: Mon, 8 Apr 2002 15:09:19 -0400
  2264. Message-ID: spam
  2265. Subject: the next line has a space on it
  2266. \x20
  2267. Here's the message body
  2268. """)
  2269. eq(msg['subject'], 'the next line has a space on it\n ')
  2270. eq(msg['message-id'], 'spam')
  2271. eq(msg.get_payload(), "Here's the message body\n")
  2272. def test_crlf_separation(self):
  2273. eq = self.assertEqual
  2274. fp = openfile('msg_26.txt', mode='rb')
  2275. try:
  2276. msg = Parser().parse(fp)
  2277. finally:
  2278. fp.close()
  2279. eq(len(msg.get_payload()), 2)
  2280. part1 = msg.get_payload(0)
  2281. eq(part1.get_content_type(), 'text/plain')
  2282. eq(part1.get_payload(), 'Simple email with attachment.\r\n\r\n')
  2283. part2 = msg.get_payload(1)
  2284. eq(part2.get_content_type(), 'application/riscos')
  2285. def test_multipart_digest_with_extra_mime_headers(self):
  2286. eq = self.assertEqual
  2287. neq = self.ndiffAssertEqual
  2288. fp = openfile('msg_28.txt')
  2289. try:
  2290. msg = email.message_from_file(fp)
  2291. finally:
  2292. fp.close()
  2293. # Structure is:
  2294. # multipart/digest
  2295. # message/rfc822
  2296. # text/plain
  2297. # message/rfc822
  2298. # text/plain
  2299. eq(msg.is_multipart(), 1)
  2300. eq(len(msg.get_payload()), 2)
  2301. part1 = msg.get_payload(0)
  2302. eq(part1.get_content_type(), 'message/rfc822')
  2303. eq(part1.is_multipart(), 1)
  2304. eq(len(part1.get_payload()), 1)
  2305. part1a = part1.get_payload(0)
  2306. eq(part1a.is_multipart(), 0)
  2307. eq(part1a.get_content_type(), 'text/plain')
  2308. neq(part1a.get_payload(), 'message 1\n')
  2309. # next message/rfc822
  2310. part2 = msg.get_payload(1)
  2311. eq(part2.get_content_type(), 'message/rfc822')
  2312. eq(part2.is_multipart(), 1)
  2313. eq(len(part2.get_payload()), 1)
  2314. part2a = part2.get_payload(0)
  2315. eq(part2a.is_multipart(), 0)
  2316. eq(part2a.get_content_type(), 'text/plain')
  2317. neq(part2a.get_payload(), 'message 2\n')
  2318. def test_three_lines(self):
  2319. # A bug report by Andrew McNamara
  2320. lines = ['From: Andrew Person <aperson@dom.ain',
  2321. 'Subject: Test',
  2322. 'Date: Tue, 20 Aug 2002 16:43:45 +1000']
  2323. msg = email.message_from_string(NL.join(lines))
  2324. self.assertEqual(msg['date'], 'Tue, 20 Aug 2002 16:43:45 +1000')
  2325. def test_strip_line_feed_and_carriage_return_in_headers(self):
  2326. eq = self.assertEqual
  2327. # For [ 1002475 ] email message parser doesn't handle \r\n correctly
  2328. value1 = 'text'
  2329. value2 = 'more text'
  2330. m = 'Header: %s\r\nNext-Header: %s\r\n\r\nBody\r\n\r\n' % (
  2331. value1, value2)
  2332. msg = email.message_from_string(m)
  2333. eq(msg.get('Header'), value1)
  2334. eq(msg.get('Next-Header'), value2)
  2335. def test_rfc2822_header_syntax(self):
  2336. eq = self.assertEqual
  2337. m = '>From: foo\nFrom: bar\n!"#QUX;~: zoo\n\nbody'
  2338. msg = email.message_from_string(m)
  2339. eq(len(msg.keys()), 3)
  2340. keys = msg.keys()
  2341. keys.sort()
  2342. eq(keys, ['!"#QUX;~', '>From', 'From'])
  2343. eq(msg.get_payload(), 'body')
  2344. def test_rfc2822_space_not_allowed_in_header(self):
  2345. eq = self.assertEqual
  2346. m = '>From foo@example.com 11:25:53\nFrom: bar\n!"#QUX;~: zoo\n\nbody'
  2347. msg = email.message_from_string(m)
  2348. eq(len(msg.keys()), 0)
  2349. def test_rfc2822_one_character_header(self):
  2350. eq = self.assertEqual
  2351. m = 'A: first header\nB: second header\nCC: third header\n\nbody'
  2352. msg = email.message_from_string(m)
  2353. headers = msg.keys()
  2354. headers.sort()
  2355. eq(headers, ['A', 'B', 'CC'])
  2356. eq(msg.get_payload(), 'body')
  2357. def test_CRLFLF_at_end_of_part(self):
  2358. # issue 5610: feedparser should not eat two chars from body part ending
  2359. # with "\r\n\n".
  2360. m = (
  2361. "From: foo@bar.com\n"
  2362. "To: baz\n"
  2363. "Mime-Version: 1.0\n"
  2364. "Content-Type: multipart/mixed; boundary=BOUNDARY\n"
  2365. "\n"
  2366. "--BOUNDARY\n"
  2367. "Content-Type: text/plain\n"
  2368. "\n"
  2369. "body ending with CRLF newline\r\n"
  2370. "\n"
  2371. "--BOUNDARY--\n"
  2372. )
  2373. msg = email.message_from_string(m)
  2374. self.assertTrue(msg.get_payload(0).get_payload().endswith('\r\n'))
  2375. class TestBase64(unittest.TestCase):
  2376. def test_len(self):
  2377. eq = self.assertEqual
  2378. eq(base64MIME.base64_len('hello'),
  2379. len(base64MIME.encode('hello', eol='')))
  2380. for size in range(15):
  2381. if size == 0 : bsize = 0
  2382. elif size <= 3 : bsize = 4
  2383. elif size <= 6 : bsize = 8
  2384. elif size <= 9 : bsize = 12
  2385. elif size <= 12: bsize = 16
  2386. else : bsize = 20
  2387. eq(base64MIME.base64_len('x'*size), bsize)
  2388. def test_decode(self):
  2389. eq = self.assertEqual
  2390. eq(base64MIME.decode(''), '')
  2391. eq(base64MIME.decode('aGVsbG8='), 'hello')
  2392. eq(base64MIME.decode('aGVsbG8=', 'X'), 'hello')
  2393. eq(base64MIME.decode('aGVsbG8NCndvcmxk\n', 'X'), 'helloXworld')
  2394. def test_encode(self):
  2395. eq = self.assertEqual
  2396. eq(base64MIME.encode(''), '')
  2397. eq(base64MIME.encode('hello'), 'aGVsbG8=\n')
  2398. # Test the binary flag
  2399. eq(base64MIME.encode('hello\n'), 'aGVsbG8K\n')
  2400. eq(base64MIME.encode('hello\n', 0), 'aGVsbG8NCg==\n')
  2401. # Test the maxlinelen arg
  2402. eq(base64MIME.encode('xxxx ' * 20, maxlinelen=40), """\
  2403. eHh4eCB4eHh4IHh4eHggeHh4eCB4eHh4IHh4eHgg
  2404. eHh4eCB4eHh4IHh4eHggeHh4eCB4eHh4IHh4eHgg
  2405. eHh4eCB4eHh4IHh4eHggeHh4eCB4eHh4IHh4eHgg
  2406. eHh4eCB4eHh4IA==
  2407. """)
  2408. # Test the eol argument
  2409. eq(base64MIME.encode('xxxx ' * 20, maxlinelen=40, eol='\r\n'), """\
  2410. eHh4eCB4eHh4IHh4eHggeHh4eCB4eHh4IHh4eHgg\r
  2411. eHh4eCB4eHh4IHh4eHggeHh4eCB4eHh4IHh4eHgg\r
  2412. eHh4eCB4eHh4IHh4eHggeHh4eCB4eHh4IHh4eHgg\r
  2413. eHh4eCB4eHh4IA==\r
  2414. """)
  2415. def test_header_encode(self):
  2416. eq = self.assertEqual
  2417. he = base64MIME.header_encode
  2418. eq(he('hello'), '=?iso-8859-1?b?aGVsbG8=?=')
  2419. eq(he('hello\nworld'), '=?iso-8859-1?b?aGVsbG8NCndvcmxk?=')
  2420. # Test the charset option
  2421. eq(he('hello', charset='iso-8859-2'), '=?iso-8859-2?b?aGVsbG8=?=')
  2422. # Test the keep_eols flag
  2423. eq(he('hello\nworld', keep_eols=True),
  2424. '=?iso-8859-1?b?aGVsbG8Kd29ybGQ=?=')
  2425. # Test the maxlinelen argument
  2426. eq(he('xxxx ' * 20, maxlinelen=40), """\
  2427. =?iso-8859-1?b?eHh4eCB4eHh4IHh4eHggeHg=?=
  2428. =?iso-8859-1?b?eHggeHh4eCB4eHh4IHh4eHg=?=
  2429. =?iso-8859-1?b?IHh4eHggeHh4eCB4eHh4IHg=?=
  2430. =?iso-8859-1?b?eHh4IHh4eHggeHh4eCB4eHg=?=
  2431. =?iso-8859-1?b?eCB4eHh4IHh4eHggeHh4eCA=?=
  2432. =?iso-8859-1?b?eHh4eCB4eHh4IHh4eHgg?=""")
  2433. # Test the eol argument
  2434. eq(he('xxxx ' * 20, maxlinelen=40, eol='\r\n'), """\
  2435. =?iso-8859-1?b?eHh4eCB4eHh4IHh4eHggeHg=?=\r
  2436. =?iso-8859-1?b?eHggeHh4eCB4eHh4IHh4eHg=?=\r
  2437. =?iso-8859-1?b?IHh4eHggeHh4eCB4eHh4IHg=?=\r
  2438. =?iso-8859-1?b?eHh4IHh4eHggeHh4eCB4eHg=?=\r
  2439. =?iso-8859-1?b?eCB4eHh4IHh4eHggeHh4eCA=?=\r
  2440. =?iso-8859-1?b?eHh4eCB4eHh4IHh4eHgg?=""")
  2441. class TestQuopri(unittest.TestCase):
  2442. def setUp(self):
  2443. self.hlit = [chr(x) for x in range(ord('a'), ord('z')+1)] + \
  2444. [chr(x) for x in range(ord('A'), ord('Z')+1)] + \
  2445. [chr(x) for x in range(ord('0'), ord('9')+1)] + \
  2446. ['!', '*', '+', '-', '/', ' ']
  2447. self.hnon = [chr(x) for x in range(256) if chr(x) not in self.hlit]
  2448. assert len(self.hlit) + len(self.hnon) == 256
  2449. self.blit = [chr(x) for x in range(ord(' '), ord('~')+1)] + ['\t']
  2450. self.blit.remove('=')
  2451. self.bnon = [chr(x) for x in range(256) if chr(x) not in self.blit]
  2452. assert len(self.blit) + len(self.bnon) == 256
  2453. def test_header_quopri_check(self):
  2454. for c in self.hlit:
  2455. self.assertFalse(quopriMIME.header_quopri_check(c))
  2456. for c in self.hnon:
  2457. self.assertTrue(quopriMIME.header_quopri_check(c))
  2458. def test_body_quopri_check(self):
  2459. for c in self.blit:
  2460. self.assertFalse(quopriMIME.body_quopri_check(c))
  2461. for c in self.bnon:
  2462. self.assertTrue(quopriMIME.body_quopri_check(c))
  2463. def test_header_quopri_len(self):
  2464. eq = self.assertEqual
  2465. hql = quopriMIME.header_quopri_len
  2466. enc = quopriMIME.header_encode
  2467. for s in ('hello', 'h@e@l@l@o@'):
  2468. # Empty charset and no line-endings. 7 == RFC chrome
  2469. eq(hql(s), len(enc(s, charset='', eol=''))-7)
  2470. for c in self.hlit:
  2471. eq(hql(c), 1)
  2472. for c in self.hnon:
  2473. eq(hql(c), 3)
  2474. def test_body_quopri_len(self):
  2475. eq = self.assertEqual
  2476. bql = quopriMIME.body_quopri_len
  2477. for c in self.blit:
  2478. eq(bql(c), 1)
  2479. for c in self.bnon:
  2480. eq(bql(c), 3)
  2481. def test_quote_unquote_idempotent(self):
  2482. for x in range(256):
  2483. c = chr(x)
  2484. self.assertEqual(quopriMIME.unquote(quopriMIME.quote(c)), c)
  2485. def test_header_encode(self):
  2486. eq = self.assertEqual
  2487. he = quopriMIME.header_encode
  2488. eq(he('hello'), '=?iso-8859-1?q?hello?=')
  2489. eq(he('hello\nworld'), '=?iso-8859-1?q?hello=0D=0Aworld?=')
  2490. # Test the charset option
  2491. eq(he('hello', charset='iso-8859-2'), '=?iso-8859-2?q?hello?=')
  2492. # Test the keep_eols flag
  2493. eq(he('hello\nworld', keep_eols=True), '=?iso-8859-1?q?hello=0Aworld?=')
  2494. # Test a non-ASCII character
  2495. eq(he('hello\xc7there'), '=?iso-8859-1?q?hello=C7there?=')
  2496. # Test the maxlinelen argument
  2497. eq(he('xxxx ' * 20, maxlinelen=40), """\
  2498. =?iso-8859-1?q?xxxx_xxxx_xxxx_xxxx_xx?=
  2499. =?iso-8859-1?q?xx_xxxx_xxxx_xxxx_xxxx?=
  2500. =?iso-8859-1?q?_xxxx_xxxx_xxxx_xxxx_x?=
  2501. =?iso-8859-1?q?xxx_xxxx_xxxx_xxxx_xxx?=
  2502. =?iso-8859-1?q?x_xxxx_xxxx_?=""")
  2503. # Test the eol argument
  2504. eq(he('xxxx ' * 20, maxlinelen=40, eol='\r\n'), """\
  2505. =?iso-8859-1?q?xxxx_xxxx_xxxx_xxxx_xx?=\r
  2506. =?iso-8859-1?q?xx_xxxx_xxxx_xxxx_xxxx?=\r
  2507. =?iso-8859-1?q?_xxxx_xxxx_xxxx_xxxx_x?=\r
  2508. =?iso-8859-1?q?xxx_xxxx_xxxx_xxxx_xxx?=\r
  2509. =?iso-8859-1?q?x_xxxx_xxxx_?=""")
  2510. def test_decode(self):
  2511. eq = self.assertEqual
  2512. eq(quopriMIME.decode(''), '')
  2513. eq(quopriMIME.decode('hello'), 'hello')
  2514. eq(quopriMIME.decode('hello', 'X'), 'hello')
  2515. eq(quopriMIME.decode('hello\nworld', 'X'), 'helloXworld')
  2516. def test_encode(self):
  2517. eq = self.assertEqual
  2518. eq(quopriMIME.encode(''), '')
  2519. eq(quopriMIME.encode('hello'), 'hello')
  2520. # Test the binary flag
  2521. eq(quopriMIME.encode('hello\r\nworld'), 'hello\nworld')
  2522. eq(quopriMIME.encode('hello\r\nworld', 0), 'hello\nworld')
  2523. # Test the maxlinelen arg
  2524. eq(quopriMIME.encode('xxxx ' * 20, maxlinelen=40), """\
  2525. xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx=
  2526. xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxx=
  2527. x xxxx xxxx xxxx xxxx=20""")
  2528. # Test the eol argument
  2529. eq(quopriMIME.encode('xxxx ' * 20, maxlinelen=40, eol='\r\n'), """\
  2530. xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx=\r
  2531. xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxx=\r
  2532. x xxxx xxxx xxxx xxxx=20""")
  2533. eq(quopriMIME.encode("""\
  2534. one line
  2535. two line"""), """\
  2536. one line
  2537. two line""")
  2538. # Test the Charset class
  2539. class TestCharset(unittest.TestCase):
  2540. def tearDown(self):
  2541. from email import Charset as CharsetModule
  2542. try:
  2543. del CharsetModule.CHARSETS['fake']
  2544. except KeyError:
  2545. pass
  2546. def test_idempotent(self):
  2547. eq = self.assertEqual
  2548. # Make sure us-ascii = no Unicode conversion
  2549. c = Charset('us-ascii')
  2550. s = 'Hello World!'
  2551. sp = c.to_splittable(s)
  2552. eq(s, c.from_splittable(sp))
  2553. # test 8-bit idempotency with us-ascii
  2554. s = '\xa4\xa2\xa4\xa4\xa4\xa6\xa4\xa8\xa4\xaa'
  2555. sp = c.to_splittable(s)
  2556. eq(s, c.from_splittable(sp))
  2557. def test_body_encode(self):
  2558. eq = self.assertEqual
  2559. # Try a charset with QP body encoding
  2560. c = Charset('iso-8859-1')
  2561. eq('hello w=F6rld', c.body_encode('hello w\xf6rld'))
  2562. # Try a charset with Base64 body encoding
  2563. c = Charset('utf-8')
  2564. eq('aGVsbG8gd29ybGQ=\n', c.body_encode('hello world'))
  2565. # Try a charset with None body encoding
  2566. c = Charset('us-ascii')
  2567. eq('hello world', c.body_encode('hello world'))
  2568. # Try the convert argument, where input codec != output codec
  2569. c = Charset('euc-jp')
  2570. # With apologies to Tokio Kikuchi ;)
  2571. try:
  2572. eq('\x1b$B5FCO;~IW\x1b(B',
  2573. c.body_encode('\xb5\xc6\xc3\xcf\xbb\xfe\xc9\xd7'))
  2574. eq('\xb5\xc6\xc3\xcf\xbb\xfe\xc9\xd7',
  2575. c.body_encode('\xb5\xc6\xc3\xcf\xbb\xfe\xc9\xd7', False))
  2576. except LookupError:
  2577. # We probably don't have the Japanese codecs installed
  2578. pass
  2579. # Testing SF bug #625509, which we have to fake, since there are no
  2580. # built-in encodings where the header encoding is QP but the body
  2581. # encoding is not.
  2582. from email import Charset as CharsetModule
  2583. CharsetModule.add_charset('fake', CharsetModule.QP, None)
  2584. c = Charset('fake')
  2585. eq('hello w\xf6rld', c.body_encode('hello w\xf6rld'))
  2586. def test_unicode_charset_name(self):
  2587. charset = Charset(u'us-ascii')
  2588. self.assertEqual(str(charset), 'us-ascii')
  2589. self.assertRaises(Errors.CharsetError, Charset, 'asc\xffii')
  2590. def test_codecs_aliases_accepted(self):
  2591. charset = Charset('utf8')
  2592. self.assertEqual(str(charset), 'utf-8')
  2593. # Test multilingual MIME headers.
  2594. class TestHeader(TestEmailBase):
  2595. def test_simple(self):
  2596. eq = self.ndiffAssertEqual
  2597. h = Header('Hello World!')
  2598. eq(h.encode(), 'Hello World!')
  2599. h.append(' Goodbye World!')
  2600. eq(h.encode(), 'Hello World! Goodbye World!')
  2601. def test_simple_surprise(self):
  2602. eq = self.ndiffAssertEqual
  2603. h = Header('Hello World!')
  2604. eq(h.encode(), 'Hello World!')
  2605. h.append('Goodbye World!')
  2606. eq(h.encode(), 'Hello World! Goodbye World!')
  2607. def test_header_needs_no_decoding(self):
  2608. h = 'no decoding needed'
  2609. self.assertEqual(decode_header(h), [(h, None)])
  2610. def test_long(self):
  2611. 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.",
  2612. maxlinelen=76)
  2613. for l in h.encode(splitchars=' ').split('\n '):
  2614. self.assertTrue(len(l) <= 76)
  2615. def test_multilingual(self):
  2616. eq = self.ndiffAssertEqual
  2617. g = Charset("iso-8859-1")
  2618. cz = Charset("iso-8859-2")
  2619. utf8 = Charset("utf-8")
  2620. g_head = "Die Mieter treten hier ein werden mit einem Foerderband komfortabel den Korridor entlang, an s\xfcdl\xfcndischen Wandgem\xe4lden vorbei, gegen die rotierenden Klingen bef\xf6rdert. "
  2621. cz_head = "Finan\xe8ni metropole se hroutily pod tlakem jejich d\xf9vtipu.. "
  2622. utf8_head = u"\u6b63\u78ba\u306b\u8a00\u3046\u3068\u7ffb\u8a33\u306f\u3055\u308c\u3066\u3044\u307e\u305b\u3093\u3002\u4e00\u90e8\u306f\u30c9\u30a4\u30c4\u8a9e\u3067\u3059\u304c\u3001\u3042\u3068\u306f\u3067\u305f\u3089\u3081\u3067\u3059\u3002\u5b9f\u969b\u306b\u306f\u300cWenn ist das Nunstuck git und Slotermeyer? Ja! Beiherhund das Oder die Flipperwaldt gersput.\u300d\u3068\u8a00\u3063\u3066\u3044\u307e\u3059\u3002".encode("utf-8")
  2623. h = Header(g_head, g)
  2624. h.append(cz_head, cz)
  2625. h.append(utf8_head, utf8)
  2626. enc = h.encode()
  2627. eq(enc, """\
  2628. =?iso-8859-1?q?Die_Mieter_treten_hier_ein_werden_mit_einem_Foerderband_ko?=
  2629. =?iso-8859-1?q?mfortabel_den_Korridor_entlang=2C_an_s=FCdl=FCndischen_Wan?=
  2630. =?iso-8859-1?q?dgem=E4lden_vorbei=2C_gegen_die_rotierenden_Klingen_bef=F6?=
  2631. =?iso-8859-1?q?rdert=2E_?= =?iso-8859-2?q?Finan=E8ni_metropole_se_hroutily?=
  2632. =?iso-8859-2?q?_pod_tlakem_jejich_d=F9vtipu=2E=2E_?= =?utf-8?b?5q2j56K6?=
  2633. =?utf-8?b?44Gr6KiA44GG44Go57+76Kiz44Gv44GV44KM44Gm44GE44G+44Gb44KT44CC?=
  2634. =?utf-8?b?5LiA6YOo44Gv44OJ44Kk44OE6Kqe44Gn44GZ44GM44CB44GC44Go44Gv44Gn?=
  2635. =?utf-8?b?44Gf44KJ44KB44Gn44GZ44CC5a6f6Zqb44Gr44Gv44CMV2VubiBpc3QgZGFz?=
  2636. =?utf-8?q?_Nunstuck_git_und_Slotermeyer=3F_Ja!_Beiherhund_das_Oder_die_Fl?=
  2637. =?utf-8?b?aXBwZXJ3YWxkdCBnZXJzcHV0LuOAjeOBqOiogOOBo+OBpuOBhOOBvuOBmQ==?=
  2638. =?utf-8?b?44CC?=""")
  2639. eq(decode_header(enc),
  2640. [(g_head, "iso-8859-1"), (cz_head, "iso-8859-2"),
  2641. (utf8_head, "utf-8")])
  2642. ustr = unicode(h)
  2643. eq(ustr.encode('utf-8'),
  2644. 'Die Mieter treten hier ein werden mit einem Foerderband '
  2645. 'komfortabel den Korridor entlang, an s\xc3\xbcdl\xc3\xbcndischen '
  2646. 'Wandgem\xc3\xa4lden vorbei, gegen die rotierenden Klingen '
  2647. 'bef\xc3\xb6rdert. Finan\xc4\x8dni metropole se hroutily pod '
  2648. 'tlakem jejich d\xc5\xafvtipu.. \xe6\xad\xa3\xe7\xa2\xba\xe3\x81'
  2649. '\xab\xe8\xa8\x80\xe3\x81\x86\xe3\x81\xa8\xe7\xbf\xbb\xe8\xa8\xb3'
  2650. '\xe3\x81\xaf\xe3\x81\x95\xe3\x82\x8c\xe3\x81\xa6\xe3\x81\x84\xe3'
  2651. '\x81\xbe\xe3\x81\x9b\xe3\x82\x93\xe3\x80\x82\xe4\xb8\x80\xe9\x83'
  2652. '\xa8\xe3\x81\xaf\xe3\x83\x89\xe3\x82\xa4\xe3\x83\x84\xe8\xaa\x9e'
  2653. '\xe3\x81\xa7\xe3\x81\x99\xe3\x81\x8c\xe3\x80\x81\xe3\x81\x82\xe3'
  2654. '\x81\xa8\xe3\x81\xaf\xe3\x81\xa7\xe3\x81\x9f\xe3\x82\x89\xe3\x82'
  2655. '\x81\xe3\x81\xa7\xe3\x81\x99\xe3\x80\x82\xe5\xae\x9f\xe9\x9a\x9b'
  2656. '\xe3\x81\xab\xe3\x81\xaf\xe3\x80\x8cWenn ist das Nunstuck git '
  2657. 'und Slotermeyer? Ja! Beiherhund das Oder die Flipperwaldt '
  2658. 'gersput.\xe3\x80\x8d\xe3\x81\xa8\xe8\xa8\x80\xe3\x81\xa3\xe3\x81'
  2659. '\xa6\xe3\x81\x84\xe3\x81\xbe\xe3\x81\x99\xe3\x80\x82')
  2660. # Test make_header()
  2661. newh = make_header(decode_header(enc))
  2662. eq(newh, enc)
  2663. def test_header_ctor_default_args(self):
  2664. eq = self.ndiffAssertEqual
  2665. h = Header()
  2666. eq(h, '')
  2667. h.append('foo', Charset('iso-8859-1'))
  2668. eq(h, '=?iso-8859-1?q?foo?=')
  2669. def test_explicit_maxlinelen(self):
  2670. eq = self.ndiffAssertEqual
  2671. hstr = 'A very long line that must get split to something other than at the 76th character boundary to test the non-default behavior'
  2672. h = Header(hstr)
  2673. eq(h.encode(), '''\
  2674. A very long line that must get split to something other than at the 76th
  2675. character boundary to test the non-default behavior''')
  2676. h = Header(hstr, header_name='Subject')
  2677. eq(h.encode(), '''\
  2678. A very long line that must get split to something other than at the
  2679. 76th character boundary to test the non-default behavior''')
  2680. h = Header(hstr, maxlinelen=1024, header_name='Subject')
  2681. eq(h.encode(), hstr)
  2682. def test_us_ascii_header(self):
  2683. eq = self.assertEqual
  2684. s = 'hello'
  2685. x = decode_header(s)
  2686. eq(x, [('hello', None)])
  2687. h = make_header(x)
  2688. eq(s, h.encode())
  2689. def test_string_charset(self):
  2690. eq = self.assertEqual
  2691. h = Header()
  2692. h.append('hello', 'iso-8859-1')
  2693. eq(h, '=?iso-8859-1?q?hello?=')
  2694. ## def test_unicode_error(self):
  2695. ## raises = self.assertRaises
  2696. ## raises(UnicodeError, Header, u'[P\xf6stal]', 'us-ascii')
  2697. ## raises(UnicodeError, Header, '[P\xf6stal]', 'us-ascii')
  2698. ## h = Header()
  2699. ## raises(UnicodeError, h.append, u'[P\xf6stal]', 'us-ascii')
  2700. ## raises(UnicodeError, h.append, '[P\xf6stal]', 'us-ascii')
  2701. ## raises(UnicodeError, Header, u'\u83ca\u5730\u6642\u592b', 'iso-8859-1')
  2702. def test_utf8_shortest(self):
  2703. eq = self.assertEqual
  2704. h = Header(u'p\xf6stal', 'utf-8')
  2705. eq(h.encode(), '=?utf-8?q?p=C3=B6stal?=')
  2706. h = Header(u'\u83ca\u5730\u6642\u592b', 'utf-8')
  2707. eq(h.encode(), '=?utf-8?b?6I+K5Zyw5pmC5aSr?=')
  2708. def test_bad_8bit_header(self):
  2709. raises = self.assertRaises
  2710. eq = self.assertEqual
  2711. x = 'Ynwp4dUEbay Auction Semiar- No Charge \x96 Earn Big'
  2712. raises(UnicodeError, Header, x)
  2713. h = Header()
  2714. raises(UnicodeError, h.append, x)
  2715. eq(str(Header(x, errors='replace')), x)
  2716. h.append(x, errors='replace')
  2717. eq(str(h), x)
  2718. def test_encoded_adjacent_nonencoded(self):
  2719. eq = self.assertEqual
  2720. h = Header()
  2721. h.append('hello', 'iso-8859-1')
  2722. h.append('world')
  2723. s = h.encode()
  2724. eq(s, '=?iso-8859-1?q?hello?= world')
  2725. h = make_header(decode_header(s))
  2726. eq(h.encode(), s)
  2727. def test_whitespace_eater(self):
  2728. eq = self.assertEqual
  2729. s = 'Subject: =?koi8-r?b?8NLP18XSy8EgzsEgxsnOwczYztk=?= =?koi8-r?q?=CA?= zz.'
  2730. parts = decode_header(s)
  2731. eq(parts, [('Subject:', None), ('\xf0\xd2\xcf\xd7\xc5\xd2\xcb\xc1 \xce\xc1 \xc6\xc9\xce\xc1\xcc\xd8\xce\xd9\xca', 'koi8-r'), ('zz.', None)])
  2732. hdr = make_header(parts)
  2733. eq(hdr.encode(),
  2734. 'Subject: =?koi8-r?b?8NLP18XSy8EgzsEgxsnOwczYztnK?= zz.')
  2735. def test_broken_base64_header(self):
  2736. raises = self.assertRaises
  2737. s = 'Subject: =?EUC-KR?B?CSixpLDtKSC/7Liuvsax4iC6uLmwMcijIKHaILzSwd/H0SC8+LCjwLsgv7W/+Mj3I ?='
  2738. raises(Errors.HeaderParseError, decode_header, s)
  2739. # Issue 1078919
  2740. def test_ascii_add_header(self):
  2741. msg = Message()
  2742. msg.add_header('Content-Disposition', 'attachment',
  2743. filename='bud.gif')
  2744. self.assertEqual('attachment; filename="bud.gif"',
  2745. msg['Content-Disposition'])
  2746. def test_nonascii_add_header_via_triple(self):
  2747. msg = Message()
  2748. msg.add_header('Content-Disposition', 'attachment',
  2749. filename=('iso-8859-1', '', 'Fu\xdfballer.ppt'))
  2750. self.assertEqual(
  2751. 'attachment; filename*="iso-8859-1\'\'Fu%DFballer.ppt"',
  2752. msg['Content-Disposition'])
  2753. def test_encode_unaliased_charset(self):
  2754. # Issue 1379416: when the charset has no output conversion,
  2755. # output was accidentally getting coerced to unicode.
  2756. res = Header('abc','iso-8859-2').encode()
  2757. self.assertEqual(res, '=?iso-8859-2?q?abc?=')
  2758. self.assertIsInstance(res, str)
  2759. # Test RFC 2231 header parameters (en/de)coding
  2760. class TestRFC2231(TestEmailBase):
  2761. def test_get_param(self):
  2762. eq = self.assertEqual
  2763. msg = self._msgobj('msg_29.txt')
  2764. eq(msg.get_param('title'),
  2765. ('us-ascii', 'en', 'This is even more ***fun*** isn\'t it!'))
  2766. eq(msg.get_param('title', unquote=False),
  2767. ('us-ascii', 'en', '"This is even more ***fun*** isn\'t it!"'))
  2768. def test_set_param(self):
  2769. eq = self.assertEqual
  2770. msg = Message()
  2771. msg.set_param('title', 'This is even more ***fun*** isn\'t it!',
  2772. charset='us-ascii')
  2773. eq(msg.get_param('title'),
  2774. ('us-ascii', '', 'This is even more ***fun*** isn\'t it!'))
  2775. msg.set_param('title', 'This is even more ***fun*** isn\'t it!',
  2776. charset='us-ascii', language='en')
  2777. eq(msg.get_param('title'),
  2778. ('us-ascii', 'en', 'This is even more ***fun*** isn\'t it!'))
  2779. msg = self._msgobj('msg_01.txt')
  2780. msg.set_param('title', 'This is even more ***fun*** isn\'t it!',
  2781. charset='us-ascii', language='en')
  2782. self.ndiffAssertEqual(msg.as_string(), """\
  2783. Return-Path: <bbb@zzz.org>
  2784. Delivered-To: bbb@zzz.org
  2785. Received: by mail.zzz.org (Postfix, from userid 889)
  2786. id 27CEAD38CC; Fri, 4 May 2001 14:05:44 -0400 (EDT)
  2787. MIME-Version: 1.0
  2788. Content-Transfer-Encoding: 7bit
  2789. Message-ID: <15090.61304.110929.45684@aaa.zzz.org>
  2790. From: bbb@ddd.com (John X. Doe)
  2791. To: bbb@zzz.org
  2792. Subject: This is a test message
  2793. Date: Fri, 4 May 2001 14:05:44 -0400
  2794. Content-Type: text/plain; charset=us-ascii;
  2795. title*="us-ascii'en'This%20is%20even%20more%20%2A%2A%2Afun%2A%2A%2A%20isn%27t%20it%21"
  2796. Hi,
  2797. Do you like this message?
  2798. -Me
  2799. """)
  2800. def test_del_param(self):
  2801. eq = self.ndiffAssertEqual
  2802. msg = self._msgobj('msg_01.txt')
  2803. msg.set_param('foo', 'bar', charset='us-ascii', language='en')
  2804. msg.set_param('title', 'This is even more ***fun*** isn\'t it!',
  2805. charset='us-ascii', language='en')
  2806. msg.del_param('foo', header='Content-Type')
  2807. eq(msg.as_string(), """\
  2808. Return-Path: <bbb@zzz.org>
  2809. Delivered-To: bbb@zzz.org
  2810. Received: by mail.zzz.org (Postfix, from userid 889)
  2811. id 27CEAD38CC; Fri, 4 May 2001 14:05:44 -0400 (EDT)
  2812. MIME-Version: 1.0
  2813. Content-Transfer-Encoding: 7bit
  2814. Message-ID: <15090.61304.110929.45684@aaa.zzz.org>
  2815. From: bbb@ddd.com (John X. Doe)
  2816. To: bbb@zzz.org
  2817. Subject: This is a test message
  2818. Date: Fri, 4 May 2001 14:05:44 -0400
  2819. Content-Type: text/plain; charset="us-ascii";
  2820. title*="us-ascii'en'This%20is%20even%20more%20%2A%2A%2Afun%2A%2A%2A%20isn%27t%20it%21"
  2821. Hi,
  2822. Do you like this message?
  2823. -Me
  2824. """)
  2825. def test_rfc2231_get_content_charset(self):
  2826. eq = self.assertEqual
  2827. msg = self._msgobj('msg_32.txt')
  2828. eq(msg.get_content_charset(), 'us-ascii')
  2829. def test_rfc2231_no_language_or_charset(self):
  2830. m = '''\
  2831. Content-Transfer-Encoding: 8bit
  2832. Content-Disposition: inline; filename="file____C__DOCUMENTS_20AND_20SETTINGS_FABIEN_LOCAL_20SETTINGS_TEMP_nsmail.htm"
  2833. Content-Type: text/html; NAME*0=file____C__DOCUMENTS_20AND_20SETTINGS_FABIEN_LOCAL_20SETTINGS_TEM; NAME*1=P_nsmail.htm
  2834. '''
  2835. msg = email.message_from_string(m)
  2836. param = msg.get_param('NAME')
  2837. self.assertFalse(isinstance(param, tuple))
  2838. self.assertEqual(
  2839. param,
  2840. 'file____C__DOCUMENTS_20AND_20SETTINGS_FABIEN_LOCAL_20SETTINGS_TEMP_nsmail.htm')
  2841. def test_rfc2231_no_language_or_charset_in_filename(self):
  2842. m = '''\
  2843. Content-Disposition: inline;
  2844. \tfilename*0*="''This%20is%20even%20more%20";
  2845. \tfilename*1*="%2A%2A%2Afun%2A%2A%2A%20";
  2846. \tfilename*2="is it not.pdf"
  2847. '''
  2848. msg = email.message_from_string(m)
  2849. self.assertEqual(msg.get_filename(),
  2850. 'This is even more ***fun*** is it not.pdf')
  2851. def test_rfc2231_no_language_or_charset_in_filename_encoded(self):
  2852. m = '''\
  2853. Content-Disposition: inline;
  2854. \tfilename*0*="''This%20is%20even%20more%20";
  2855. \tfilename*1*="%2A%2A%2Afun%2A%2A%2A%20";
  2856. \tfilename*2="is it not.pdf"
  2857. '''
  2858. msg = email.message_from_string(m)
  2859. self.assertEqual(msg.get_filename(),
  2860. 'This is even more ***fun*** is it not.pdf')
  2861. def test_rfc2231_partly_encoded(self):
  2862. m = '''\
  2863. Content-Disposition: inline;
  2864. \tfilename*0="''This%20is%20even%20more%20";
  2865. \tfilename*1*="%2A%2A%2Afun%2A%2A%2A%20";
  2866. \tfilename*2="is it not.pdf"
  2867. '''
  2868. msg = email.message_from_string(m)
  2869. self.assertEqual(
  2870. msg.get_filename(),
  2871. 'This%20is%20even%20more%20***fun*** is it not.pdf')
  2872. def test_rfc2231_partly_nonencoded(self):
  2873. m = '''\
  2874. Content-Disposition: inline;
  2875. \tfilename*0="This%20is%20even%20more%20";
  2876. \tfilename*1="%2A%2A%2Afun%2A%2A%2A%20";
  2877. \tfilename*2="is it not.pdf"
  2878. '''
  2879. msg = email.message_from_string(m)
  2880. self.assertEqual(
  2881. msg.get_filename(),
  2882. 'This%20is%20even%20more%20%2A%2A%2Afun%2A%2A%2A%20is it not.pdf')
  2883. def test_rfc2231_no_language_or_charset_in_boundary(self):
  2884. m = '''\
  2885. Content-Type: multipart/alternative;
  2886. \tboundary*0*="''This%20is%20even%20more%20";
  2887. \tboundary*1*="%2A%2A%2Afun%2A%2A%2A%20";
  2888. \tboundary*2="is it not.pdf"
  2889. '''
  2890. msg = email.message_from_string(m)
  2891. self.assertEqual(msg.get_boundary(),
  2892. 'This is even more ***fun*** is it not.pdf')
  2893. def test_rfc2231_no_language_or_charset_in_charset(self):
  2894. # This is a nonsensical charset value, but tests the code anyway
  2895. m = '''\
  2896. Content-Type: text/plain;
  2897. \tcharset*0*="This%20is%20even%20more%20";
  2898. \tcharset*1*="%2A%2A%2Afun%2A%2A%2A%20";
  2899. \tcharset*2="is it not.pdf"
  2900. '''
  2901. msg = email.message_from_string(m)
  2902. self.assertEqual(msg.get_content_charset(),
  2903. 'this is even more ***fun*** is it not.pdf')
  2904. def test_rfc2231_bad_encoding_in_filename(self):
  2905. m = '''\
  2906. Content-Disposition: inline;
  2907. \tfilename*0*="bogus'xx'This%20is%20even%20more%20";
  2908. \tfilename*1*="%2A%2A%2Afun%2A%2A%2A%20";
  2909. \tfilename*2="is it not.pdf"
  2910. '''
  2911. msg = email.message_from_string(m)
  2912. self.assertEqual(msg.get_filename(),
  2913. 'This is even more ***fun*** is it not.pdf')
  2914. def test_rfc2231_bad_encoding_in_charset(self):
  2915. m = """\
  2916. Content-Type: text/plain; charset*=bogus''utf-8%E2%80%9D
  2917. """
  2918. msg = email.message_from_string(m)
  2919. # This should return None because non-ascii characters in the charset
  2920. # are not allowed.
  2921. self.assertEqual(msg.get_content_charset(), None)
  2922. def test_rfc2231_bad_character_in_charset(self):
  2923. m = """\
  2924. Content-Type: text/plain; charset*=ascii''utf-8%E2%80%9D
  2925. """
  2926. msg = email.message_from_string(m)
  2927. # This should return None because non-ascii characters in the charset
  2928. # are not allowed.
  2929. self.assertEqual(msg.get_content_charset(), None)
  2930. def test_rfc2231_bad_character_in_filename(self):
  2931. m = '''\
  2932. Content-Disposition: inline;
  2933. \tfilename*0*="ascii'xx'This%20is%20even%20more%20";
  2934. \tfilename*1*="%2A%2A%2Afun%2A%2A%2A%20";
  2935. \tfilename*2*="is it not.pdf%E2"
  2936. '''
  2937. msg = email.message_from_string(m)
  2938. self.assertEqual(msg.get_filename(),
  2939. u'This is even more ***fun*** is it not.pdf\ufffd')
  2940. def test_rfc2231_unknown_encoding(self):
  2941. m = """\
  2942. Content-Transfer-Encoding: 8bit
  2943. Content-Disposition: inline; filename*=X-UNKNOWN''myfile.txt
  2944. """
  2945. msg = email.message_from_string(m)
  2946. self.assertEqual(msg.get_filename(), 'myfile.txt')
  2947. def test_rfc2231_single_tick_in_filename_extended(self):
  2948. eq = self.assertEqual
  2949. m = """\
  2950. Content-Type: application/x-foo;
  2951. \tname*0*=\"Frank's\"; name*1*=\" Document\"
  2952. """
  2953. msg = email.message_from_string(m)
  2954. charset, language, s = msg.get_param('name')
  2955. eq(charset, None)
  2956. eq(language, None)
  2957. eq(s, "Frank's Document")
  2958. def test_rfc2231_single_tick_in_filename(self):
  2959. m = """\
  2960. Content-Type: application/x-foo; name*0=\"Frank's\"; name*1=\" Document\"
  2961. """
  2962. msg = email.message_from_string(m)
  2963. param = msg.get_param('name')
  2964. self.assertFalse(isinstance(param, tuple))
  2965. self.assertEqual(param, "Frank's Document")
  2966. def test_rfc2231_tick_attack_extended(self):
  2967. eq = self.assertEqual
  2968. m = """\
  2969. Content-Type: application/x-foo;
  2970. \tname*0*=\"us-ascii'en-us'Frank's\"; name*1*=\" Document\"
  2971. """
  2972. msg = email.message_from_string(m)
  2973. charset, language, s = msg.get_param('name')
  2974. eq(charset, 'us-ascii')
  2975. eq(language, 'en-us')
  2976. eq(s, "Frank's Document")
  2977. def test_rfc2231_tick_attack(self):
  2978. m = """\
  2979. Content-Type: application/x-foo;
  2980. \tname*0=\"us-ascii'en-us'Frank's\"; name*1=\" Document\"
  2981. """
  2982. msg = email.message_from_string(m)
  2983. param = msg.get_param('name')
  2984. self.assertFalse(isinstance(param, tuple))
  2985. self.assertEqual(param, "us-ascii'en-us'Frank's Document")
  2986. def test_rfc2231_no_extended_values(self):
  2987. eq = self.assertEqual
  2988. m = """\
  2989. Content-Type: application/x-foo; name=\"Frank's Document\"
  2990. """
  2991. msg = email.message_from_string(m)
  2992. eq(msg.get_param('name'), "Frank's Document")
  2993. def test_rfc2231_encoded_then_unencoded_segments(self):
  2994. eq = self.assertEqual
  2995. m = """\
  2996. Content-Type: application/x-foo;
  2997. \tname*0*=\"us-ascii'en-us'My\";
  2998. \tname*1=\" Document\";
  2999. \tname*2*=\" For You\"
  3000. """
  3001. msg = email.message_from_string(m)
  3002. charset, language, s = msg.get_param('name')
  3003. eq(charset, 'us-ascii')
  3004. eq(language, 'en-us')
  3005. eq(s, 'My Document For You')
  3006. def test_rfc2231_unencoded_then_encoded_segments(self):
  3007. eq = self.assertEqual
  3008. m = """\
  3009. Content-Type: application/x-foo;
  3010. \tname*0=\"us-ascii'en-us'My\";
  3011. \tname*1*=\" Document\";
  3012. \tname*2*=\" For You\"
  3013. """
  3014. msg = email.message_from_string(m)
  3015. charset, language, s = msg.get_param('name')
  3016. eq(charset, 'us-ascii')
  3017. eq(language, 'en-us')
  3018. eq(s, 'My Document For You')
  3019. # Tests to ensure that signed parts of an email are completely preserved, as
  3020. # required by RFC1847 section 2.1. Note that these are incomplete, because the
  3021. # email package does not currently always preserve the body. See issue 1670765.
  3022. class TestSigned(TestEmailBase):
  3023. def _msg_and_obj(self, filename):
  3024. fp = openfile(findfile(filename))
  3025. try:
  3026. original = fp.read()
  3027. msg = email.message_from_string(original)
  3028. finally:
  3029. fp.close()
  3030. return original, msg
  3031. def _signed_parts_eq(self, original, result):
  3032. # Extract the first mime part of each message
  3033. import re
  3034. repart = re.compile(r'^--([^\n]+)\n(.*?)\n--\1$', re.S | re.M)
  3035. inpart = repart.search(original).group(2)
  3036. outpart = repart.search(result).group(2)
  3037. self.assertEqual(outpart, inpart)
  3038. def test_long_headers_as_string(self):
  3039. original, msg = self._msg_and_obj('msg_45.txt')
  3040. result = msg.as_string()
  3041. self._signed_parts_eq(original, result)
  3042. def test_long_headers_flatten(self):
  3043. original, msg = self._msg_and_obj('msg_45.txt')
  3044. fp = StringIO()
  3045. Generator(fp).flatten(msg)
  3046. result = fp.getvalue()
  3047. self._signed_parts_eq(original, result)
  3048. def _testclasses():
  3049. mod = sys.modules[__name__]
  3050. return [getattr(mod, name) for name in dir(mod) if name.startswith('Test')]
  3051. def suite():
  3052. suite = unittest.TestSuite()
  3053. for testclass in _testclasses():
  3054. suite.addTest(unittest.makeSuite(testclass))
  3055. return suite
  3056. def test_main():
  3057. for testclass in _testclasses():
  3058. run_unittest(testclass)
  3059. if __name__ == '__main__':
  3060. unittest.main(defaultTest='suite')