tests.py 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474
  1. import asyncore
  2. import base64
  3. import mimetypes
  4. import os
  5. import shutil
  6. import smtpd
  7. import socket
  8. import sys
  9. import tempfile
  10. import threading
  11. from email import message_from_binary_file, message_from_bytes
  12. from email.header import Header
  13. from email.mime.text import MIMEText
  14. from email.utils import parseaddr
  15. from io import StringIO
  16. from smtplib import SMTP, SMTPAuthenticationError, SMTPException
  17. from ssl import SSLError
  18. from django.core import mail
  19. from django.core.mail import (
  20. EmailMessage, EmailMultiAlternatives, mail_admins, mail_managers,
  21. send_mail, send_mass_mail,
  22. )
  23. from django.core.mail.backends import console, dummy, filebased, locmem, smtp
  24. from django.core.mail.message import BadHeaderError, sanitize_address
  25. from django.test import SimpleTestCase, override_settings
  26. from django.test.utils import requires_tz_support
  27. from django.utils.encoding import force_bytes, force_text
  28. from django.utils.translation import ugettext_lazy
  29. class HeadersCheckMixin:
  30. def assertMessageHasHeaders(self, message, headers):
  31. """
  32. Asserts that the `message` has all `headers`.
  33. message: can be an instance of an email.Message subclass or a string
  34. with the contents of an email message.
  35. headers: should be a set of (header-name, header-value) tuples.
  36. """
  37. if isinstance(message, bytes):
  38. message = message_from_bytes(message)
  39. msg_headers = set(message.items())
  40. self.assertTrue(headers.issubset(msg_headers), msg='Message is missing '
  41. 'the following headers: %s' % (headers - msg_headers),)
  42. class MailTests(HeadersCheckMixin, SimpleTestCase):
  43. """
  44. Non-backend specific tests.
  45. """
  46. def get_decoded_attachments(self, django_message):
  47. """
  48. Encode the specified django.core.mail.message.EmailMessage, then decode
  49. it using Python's email.parser module and, for each attachment of the
  50. message, return a list of tuples with (filename, content, mimetype).
  51. """
  52. msg_bytes = django_message.message().as_bytes()
  53. email_message = message_from_bytes(msg_bytes)
  54. def iter_attachments():
  55. for i in email_message.walk():
  56. # Once support for Python<3.5 has been dropped, we can use
  57. # i.get_content_disposition() here instead.
  58. content_disposition = i.get('content-disposition', '').split(';')[0].lower()
  59. if content_disposition == 'attachment':
  60. filename = i.get_filename()
  61. content = i.get_payload(decode=True)
  62. mimetype = i.get_content_type()
  63. yield filename, content, mimetype
  64. return list(iter_attachments())
  65. def test_ascii(self):
  66. email = EmailMessage('Subject', 'Content', 'from@example.com', ['to@example.com'])
  67. message = email.message()
  68. self.assertEqual(message['Subject'], 'Subject')
  69. self.assertEqual(message.get_payload(), 'Content')
  70. self.assertEqual(message['From'], 'from@example.com')
  71. self.assertEqual(message['To'], 'to@example.com')
  72. def test_multiple_recipients(self):
  73. email = EmailMessage('Subject', 'Content', 'from@example.com', ['to@example.com', 'other@example.com'])
  74. message = email.message()
  75. self.assertEqual(message['Subject'], 'Subject')
  76. self.assertEqual(message.get_payload(), 'Content')
  77. self.assertEqual(message['From'], 'from@example.com')
  78. self.assertEqual(message['To'], 'to@example.com, other@example.com')
  79. def test_recipients_with_empty_strings(self):
  80. """
  81. Empty strings in various recipient arguments are always stripped
  82. off the final recipient list.
  83. """
  84. email = EmailMessage(
  85. 'Subject', 'Content', 'from@example.com', ['to@example.com', ''],
  86. cc=['cc@example.com', ''],
  87. bcc=['', 'bcc@example.com'],
  88. reply_to=['', None],
  89. )
  90. self.assertEqual(
  91. email.recipients(),
  92. ['to@example.com', 'cc@example.com', 'bcc@example.com']
  93. )
  94. def test_cc(self):
  95. """Regression test for #7722"""
  96. email = EmailMessage('Subject', 'Content', 'from@example.com', ['to@example.com'], cc=['cc@example.com'])
  97. message = email.message()
  98. self.assertEqual(message['Cc'], 'cc@example.com')
  99. self.assertEqual(email.recipients(), ['to@example.com', 'cc@example.com'])
  100. # Test multiple CC with multiple To
  101. email = EmailMessage(
  102. 'Subject', 'Content', 'from@example.com', ['to@example.com', 'other@example.com'],
  103. cc=['cc@example.com', 'cc.other@example.com']
  104. )
  105. message = email.message()
  106. self.assertEqual(message['Cc'], 'cc@example.com, cc.other@example.com')
  107. self.assertEqual(
  108. email.recipients(),
  109. ['to@example.com', 'other@example.com', 'cc@example.com', 'cc.other@example.com']
  110. )
  111. # Testing with Bcc
  112. email = EmailMessage(
  113. 'Subject', 'Content', 'from@example.com', ['to@example.com', 'other@example.com'],
  114. cc=['cc@example.com', 'cc.other@example.com'], bcc=['bcc@example.com']
  115. )
  116. message = email.message()
  117. self.assertEqual(message['Cc'], 'cc@example.com, cc.other@example.com')
  118. self.assertEqual(
  119. email.recipients(),
  120. ['to@example.com', 'other@example.com', 'cc@example.com', 'cc.other@example.com', 'bcc@example.com']
  121. )
  122. def test_reply_to(self):
  123. email = EmailMessage(
  124. 'Subject', 'Content', 'from@example.com', ['to@example.com'],
  125. reply_to=['reply_to@example.com'],
  126. )
  127. message = email.message()
  128. self.assertEqual(message['Reply-To'], 'reply_to@example.com')
  129. email = EmailMessage(
  130. 'Subject', 'Content', 'from@example.com', ['to@example.com'],
  131. reply_to=['reply_to1@example.com', 'reply_to2@example.com']
  132. )
  133. message = email.message()
  134. self.assertEqual(message['Reply-To'], 'reply_to1@example.com, reply_to2@example.com')
  135. def test_recipients_as_tuple(self):
  136. email = EmailMessage(
  137. 'Subject', 'Content', 'from@example.com', ('to@example.com', 'other@example.com'),
  138. cc=('cc@example.com', 'cc.other@example.com'), bcc=('bcc@example.com',)
  139. )
  140. message = email.message()
  141. self.assertEqual(message['Cc'], 'cc@example.com, cc.other@example.com')
  142. self.assertEqual(
  143. email.recipients(),
  144. ['to@example.com', 'other@example.com', 'cc@example.com', 'cc.other@example.com', 'bcc@example.com']
  145. )
  146. def test_recipients_as_string(self):
  147. with self.assertRaisesMessage(TypeError, '"to" argument must be a list or tuple'):
  148. EmailMessage(to='foo@example.com')
  149. with self.assertRaisesMessage(TypeError, '"cc" argument must be a list or tuple'):
  150. EmailMessage(cc='foo@example.com')
  151. with self.assertRaisesMessage(TypeError, '"bcc" argument must be a list or tuple'):
  152. EmailMessage(bcc='foo@example.com')
  153. with self.assertRaisesMessage(TypeError, '"reply_to" argument must be a list or tuple'):
  154. EmailMessage(reply_to='reply_to@example.com')
  155. def test_header_injection(self):
  156. email = EmailMessage('Subject\nInjection Test', 'Content', 'from@example.com', ['to@example.com'])
  157. with self.assertRaises(BadHeaderError):
  158. email.message()
  159. email = EmailMessage(
  160. ugettext_lazy('Subject\nInjection Test'), 'Content', 'from@example.com', ['to@example.com']
  161. )
  162. with self.assertRaises(BadHeaderError):
  163. email.message()
  164. def test_space_continuation(self):
  165. """
  166. Test for space continuation character in long (ASCII) subject headers (#7747)
  167. """
  168. email = EmailMessage(
  169. 'Long subject lines that get wrapped should contain a space '
  170. 'continuation character to get expected behavior in Outlook and Thunderbird',
  171. 'Content', 'from@example.com', ['to@example.com']
  172. )
  173. message = email.message()
  174. self.assertEqual(
  175. message['Subject'].encode(),
  176. b'Long subject lines that get wrapped should contain a space continuation\n'
  177. b' character to get expected behavior in Outlook and Thunderbird'
  178. )
  179. def test_message_header_overrides(self):
  180. """
  181. Specifying dates or message-ids in the extra headers overrides the
  182. default values (#9233)
  183. """
  184. headers = {"date": "Fri, 09 Nov 2001 01:08:47 -0000", "Message-ID": "foo"}
  185. email = EmailMessage('subject', 'content', 'from@example.com', ['to@example.com'], headers=headers)
  186. self.assertMessageHasHeaders(email.message(), {
  187. ('Content-Transfer-Encoding', '7bit'),
  188. ('Content-Type', 'text/plain; charset="utf-8"'),
  189. ('From', 'from@example.com'),
  190. ('MIME-Version', '1.0'),
  191. ('Message-ID', 'foo'),
  192. ('Subject', 'subject'),
  193. ('To', 'to@example.com'),
  194. ('date', 'Fri, 09 Nov 2001 01:08:47 -0000'),
  195. })
  196. def test_from_header(self):
  197. """
  198. Make sure we can manually set the From header (#9214)
  199. """
  200. email = EmailMessage(
  201. 'Subject', 'Content', 'bounce@example.com', ['to@example.com'],
  202. headers={'From': 'from@example.com'},
  203. )
  204. message = email.message()
  205. self.assertEqual(message['From'], 'from@example.com')
  206. def test_to_header(self):
  207. """
  208. Make sure we can manually set the To header (#17444)
  209. """
  210. email = EmailMessage('Subject', 'Content', 'bounce@example.com',
  211. ['list-subscriber@example.com', 'list-subscriber2@example.com'],
  212. headers={'To': 'mailing-list@example.com'})
  213. message = email.message()
  214. self.assertEqual(message['To'], 'mailing-list@example.com')
  215. self.assertEqual(email.to, ['list-subscriber@example.com', 'list-subscriber2@example.com'])
  216. # If we don't set the To header manually, it should default to the `to` argument to the constructor
  217. email = EmailMessage('Subject', 'Content', 'bounce@example.com',
  218. ['list-subscriber@example.com', 'list-subscriber2@example.com'])
  219. message = email.message()
  220. self.assertEqual(message['To'], 'list-subscriber@example.com, list-subscriber2@example.com')
  221. self.assertEqual(email.to, ['list-subscriber@example.com', 'list-subscriber2@example.com'])
  222. def test_reply_to_header(self):
  223. """
  224. Specifying 'Reply-To' in headers should override reply_to.
  225. """
  226. email = EmailMessage(
  227. 'Subject', 'Content', 'bounce@example.com', ['to@example.com'],
  228. reply_to=['foo@example.com'], headers={'Reply-To': 'override@example.com'},
  229. )
  230. message = email.message()
  231. self.assertEqual(message['Reply-To'], 'override@example.com')
  232. def test_multiple_message_call(self):
  233. """
  234. Regression for #13259 - Make sure that headers are not changed when
  235. calling EmailMessage.message()
  236. """
  237. email = EmailMessage(
  238. 'Subject', 'Content', 'bounce@example.com', ['to@example.com'],
  239. headers={'From': 'from@example.com'},
  240. )
  241. message = email.message()
  242. self.assertEqual(message['From'], 'from@example.com')
  243. message = email.message()
  244. self.assertEqual(message['From'], 'from@example.com')
  245. def test_unicode_address_header(self):
  246. """
  247. Regression for #11144 - When a to/from/cc header contains unicode,
  248. make sure the email addresses are parsed correctly (especially with
  249. regards to commas)
  250. """
  251. email = EmailMessage(
  252. 'Subject', 'Content', 'from@example.com',
  253. ['"Firstname Sürname" <to@example.com>', 'other@example.com'],
  254. )
  255. self.assertEqual(
  256. email.message()['To'],
  257. '=?utf-8?q?Firstname_S=C3=BCrname?= <to@example.com>, other@example.com'
  258. )
  259. email = EmailMessage(
  260. 'Subject', 'Content', 'from@example.com',
  261. ['"Sürname, Firstname" <to@example.com>', 'other@example.com'],
  262. )
  263. self.assertEqual(
  264. email.message()['To'],
  265. '=?utf-8?q?S=C3=BCrname=2C_Firstname?= <to@example.com>, other@example.com'
  266. )
  267. def test_unicode_headers(self):
  268. email = EmailMessage("Gżegżółka", "Content", "from@example.com", ["to@example.com"],
  269. headers={"Sender": '"Firstname Sürname" <sender@example.com>',
  270. "Comments": 'My Sürname is non-ASCII'})
  271. message = email.message()
  272. self.assertEqual(message['Subject'], '=?utf-8?b?R8W8ZWfFvMOzxYJrYQ==?=')
  273. self.assertEqual(message['Sender'], '=?utf-8?q?Firstname_S=C3=BCrname?= <sender@example.com>')
  274. self.assertEqual(message['Comments'], '=?utf-8?q?My_S=C3=BCrname_is_non-ASCII?=')
  275. def test_safe_mime_multipart(self):
  276. """
  277. Make sure headers can be set with a different encoding than utf-8 in
  278. SafeMIMEMultipart as well
  279. """
  280. headers = {"Date": "Fri, 09 Nov 2001 01:08:47 -0000", "Message-ID": "foo"}
  281. from_email, to = 'from@example.com', '"Sürname, Firstname" <to@example.com>'
  282. text_content = 'This is an important message.'
  283. html_content = '<p>This is an <strong>important</strong> message.</p>'
  284. msg = EmailMultiAlternatives('Message from Firstname Sürname', text_content, from_email, [to], headers=headers)
  285. msg.attach_alternative(html_content, "text/html")
  286. msg.encoding = 'iso-8859-1'
  287. self.assertEqual(msg.message()['To'], '=?iso-8859-1?q?S=FCrname=2C_Firstname?= <to@example.com>')
  288. self.assertEqual(msg.message()['Subject'], '=?iso-8859-1?q?Message_from_Firstname_S=FCrname?=')
  289. def test_encoding(self):
  290. """
  291. Regression for #12791 - Encode body correctly with other encodings
  292. than utf-8
  293. """
  294. email = EmailMessage('Subject', 'Firstname Sürname is a great guy.', 'from@example.com', ['other@example.com'])
  295. email.encoding = 'iso-8859-1'
  296. message = email.message()
  297. self.assertMessageHasHeaders(message, {
  298. ('MIME-Version', '1.0'),
  299. ('Content-Type', 'text/plain; charset="iso-8859-1"'),
  300. ('Content-Transfer-Encoding', 'quoted-printable'),
  301. ('Subject', 'Subject'),
  302. ('From', 'from@example.com'),
  303. ('To', 'other@example.com')})
  304. self.assertEqual(message.get_payload(), 'Firstname S=FCrname is a great guy.')
  305. # Make sure MIME attachments also works correctly with other encodings than utf-8
  306. text_content = 'Firstname Sürname is a great guy.'
  307. html_content = '<p>Firstname Sürname is a <strong>great</strong> guy.</p>'
  308. msg = EmailMultiAlternatives('Subject', text_content, 'from@example.com', ['to@example.com'])
  309. msg.encoding = 'iso-8859-1'
  310. msg.attach_alternative(html_content, "text/html")
  311. payload0 = msg.message().get_payload(0)
  312. self.assertMessageHasHeaders(payload0, {
  313. ('MIME-Version', '1.0'),
  314. ('Content-Type', 'text/plain; charset="iso-8859-1"'),
  315. ('Content-Transfer-Encoding', 'quoted-printable')})
  316. self.assertTrue(payload0.as_bytes().endswith(b'\n\nFirstname S=FCrname is a great guy.'))
  317. payload1 = msg.message().get_payload(1)
  318. self.assertMessageHasHeaders(payload1, {
  319. ('MIME-Version', '1.0'),
  320. ('Content-Type', 'text/html; charset="iso-8859-1"'),
  321. ('Content-Transfer-Encoding', 'quoted-printable')})
  322. self.assertTrue(
  323. payload1.as_bytes().endswith(b'\n\n<p>Firstname S=FCrname is a <strong>great</strong> guy.</p>')
  324. )
  325. def test_attachments(self):
  326. """Regression test for #9367"""
  327. headers = {"Date": "Fri, 09 Nov 2001 01:08:47 -0000", "Message-ID": "foo"}
  328. subject, from_email, to = 'hello', 'from@example.com', 'to@example.com'
  329. text_content = 'This is an important message.'
  330. html_content = '<p>This is an <strong>important</strong> message.</p>'
  331. msg = EmailMultiAlternatives(subject, text_content, from_email, [to], headers=headers)
  332. msg.attach_alternative(html_content, "text/html")
  333. msg.attach("an attachment.pdf", b"%PDF-1.4.%...", mimetype="application/pdf")
  334. msg_bytes = msg.message().as_bytes()
  335. message = message_from_bytes(msg_bytes)
  336. self.assertTrue(message.is_multipart())
  337. self.assertEqual(message.get_content_type(), 'multipart/mixed')
  338. self.assertEqual(message.get_default_type(), 'text/plain')
  339. payload = message.get_payload()
  340. self.assertEqual(payload[0].get_content_type(), 'multipart/alternative')
  341. self.assertEqual(payload[1].get_content_type(), 'application/pdf')
  342. def test_non_ascii_attachment_filename(self):
  343. """Regression test for #14964"""
  344. headers = {"Date": "Fri, 09 Nov 2001 01:08:47 -0000", "Message-ID": "foo"}
  345. subject, from_email, to = 'hello', 'from@example.com', 'to@example.com'
  346. content = 'This is the message.'
  347. msg = EmailMessage(subject, content, from_email, [to], headers=headers)
  348. # Unicode in file name
  349. msg.attach("une pièce jointe.pdf", b"%PDF-1.4.%...", mimetype="application/pdf")
  350. msg_bytes = msg.message().as_bytes()
  351. message = message_from_bytes(msg_bytes)
  352. payload = message.get_payload()
  353. self.assertEqual(payload[1].get_filename(), 'une pièce jointe.pdf')
  354. def test_attach_file(self):
  355. """
  356. Test attaching a file against different mimetypes and make sure that
  357. a file will be attached and sent properly even if an invalid mimetype
  358. is specified.
  359. """
  360. files = (
  361. # filename, actual mimetype
  362. ('file.txt', 'text/plain'),
  363. ('file.png', 'image/png'),
  364. ('file_txt', None),
  365. ('file_png', None),
  366. ('file_txt.png', 'image/png'),
  367. ('file_png.txt', 'text/plain'),
  368. )
  369. test_mimetypes = ['text/plain', 'image/png', None]
  370. for basename, real_mimetype in files:
  371. for mimetype in test_mimetypes:
  372. email = EmailMessage('subject', 'body', 'from@example.com', ['to@example.com'])
  373. self.assertEqual(mimetypes.guess_type(basename)[0], real_mimetype)
  374. self.assertEqual(email.attachments, [])
  375. file_path = os.path.join(os.path.dirname(__file__), 'attachments', basename)
  376. email.attach_file(file_path, mimetype=mimetype)
  377. self.assertEqual(len(email.attachments), 1)
  378. self.assertIn(basename, email.attachments[0])
  379. msgs_sent_num = email.send()
  380. self.assertEqual(msgs_sent_num, 1)
  381. def test_attach_text_as_bytes(self):
  382. msg = EmailMessage('subject', 'body', 'from@example.com', ['to@example.com'])
  383. msg.attach('file.txt', b'file content')
  384. sent_num = msg.send()
  385. self.assertEqual(sent_num, 1)
  386. filename, content, mimetype = self.get_decoded_attachments(msg)[0]
  387. self.assertEqual(filename, 'file.txt')
  388. self.assertEqual(content, b'file content')
  389. self.assertEqual(mimetype, 'text/plain')
  390. def test_attach_utf8_text_as_bytes(self):
  391. """
  392. Non-ASCII characters encoded as valid UTF-8 are correctly transported
  393. and decoded.
  394. """
  395. msg = EmailMessage('subject', 'body', 'from@example.com', ['to@example.com'])
  396. msg.attach('file.txt', b'\xc3\xa4') # UTF-8 encoded a umlaut.
  397. filename, content, mimetype = self.get_decoded_attachments(msg)[0]
  398. self.assertEqual(filename, 'file.txt')
  399. self.assertEqual(content, b'\xc3\xa4')
  400. self.assertEqual(mimetype, 'text/plain')
  401. def test_attach_non_utf8_text_as_bytes(self):
  402. """
  403. Binary data that can't be decoded as UTF-8 overrides the MIME type
  404. instead of decoding the data.
  405. """
  406. msg = EmailMessage('subject', 'body', 'from@example.com', ['to@example.com'])
  407. msg.attach('file.txt', b'\xff') # Invalid UTF-8.
  408. filename, content, mimetype = self.get_decoded_attachments(msg)[0]
  409. self.assertEqual(filename, 'file.txt')
  410. # Content should be passed through unmodified.
  411. self.assertEqual(content, b'\xff')
  412. self.assertEqual(mimetype, 'application/octet-stream')
  413. def test_dummy_backend(self):
  414. """
  415. Make sure that dummy backends returns correct number of sent messages
  416. """
  417. connection = dummy.EmailBackend()
  418. email = EmailMessage(
  419. 'Subject', 'Content', 'bounce@example.com', ['to@example.com'],
  420. headers={'From': 'from@example.com'},
  421. )
  422. self.assertEqual(connection.send_messages([email, email, email]), 3)
  423. def test_arbitrary_keyword(self):
  424. """
  425. Make sure that get_connection() accepts arbitrary keyword that might be
  426. used with custom backends.
  427. """
  428. c = mail.get_connection(fail_silently=True, foo='bar')
  429. self.assertTrue(c.fail_silently)
  430. def test_custom_backend(self):
  431. """Test custom backend defined in this suite."""
  432. conn = mail.get_connection('mail.custombackend.EmailBackend')
  433. self.assertTrue(hasattr(conn, 'test_outbox'))
  434. email = EmailMessage(
  435. 'Subject', 'Content', 'bounce@example.com', ['to@example.com'],
  436. headers={'From': 'from@example.com'},
  437. )
  438. conn.send_messages([email])
  439. self.assertEqual(len(conn.test_outbox), 1)
  440. def test_backend_arg(self):
  441. """Test backend argument of mail.get_connection()"""
  442. self.assertIsInstance(mail.get_connection('django.core.mail.backends.smtp.EmailBackend'), smtp.EmailBackend)
  443. self.assertIsInstance(
  444. mail.get_connection('django.core.mail.backends.locmem.EmailBackend'),
  445. locmem.EmailBackend
  446. )
  447. self.assertIsInstance(mail.get_connection('django.core.mail.backends.dummy.EmailBackend'), dummy.EmailBackend)
  448. self.assertIsInstance(
  449. mail.get_connection('django.core.mail.backends.console.EmailBackend'),
  450. console.EmailBackend
  451. )
  452. tmp_dir = tempfile.mkdtemp()
  453. try:
  454. self.assertIsInstance(
  455. mail.get_connection('django.core.mail.backends.filebased.EmailBackend', file_path=tmp_dir),
  456. filebased.EmailBackend
  457. )
  458. finally:
  459. shutil.rmtree(tmp_dir)
  460. self.assertIsInstance(mail.get_connection(), locmem.EmailBackend)
  461. @override_settings(
  462. EMAIL_BACKEND='django.core.mail.backends.locmem.EmailBackend',
  463. ADMINS=[('nobody', 'nobody@example.com')],
  464. MANAGERS=[('nobody', 'nobody@example.com')])
  465. def test_connection_arg(self):
  466. """Test connection argument to send_mail(), et. al."""
  467. mail.outbox = []
  468. # Send using non-default connection
  469. connection = mail.get_connection('mail.custombackend.EmailBackend')
  470. send_mail('Subject', 'Content', 'from@example.com', ['to@example.com'], connection=connection)
  471. self.assertEqual(mail.outbox, [])
  472. self.assertEqual(len(connection.test_outbox), 1)
  473. self.assertEqual(connection.test_outbox[0].subject, 'Subject')
  474. connection = mail.get_connection('mail.custombackend.EmailBackend')
  475. send_mass_mail([
  476. ('Subject1', 'Content1', 'from1@example.com', ['to1@example.com']),
  477. ('Subject2', 'Content2', 'from2@example.com', ['to2@example.com']),
  478. ], connection=connection)
  479. self.assertEqual(mail.outbox, [])
  480. self.assertEqual(len(connection.test_outbox), 2)
  481. self.assertEqual(connection.test_outbox[0].subject, 'Subject1')
  482. self.assertEqual(connection.test_outbox[1].subject, 'Subject2')
  483. connection = mail.get_connection('mail.custombackend.EmailBackend')
  484. mail_admins('Admin message', 'Content', connection=connection)
  485. self.assertEqual(mail.outbox, [])
  486. self.assertEqual(len(connection.test_outbox), 1)
  487. self.assertEqual(connection.test_outbox[0].subject, '[Django] Admin message')
  488. connection = mail.get_connection('mail.custombackend.EmailBackend')
  489. mail_managers('Manager message', 'Content', connection=connection)
  490. self.assertEqual(mail.outbox, [])
  491. self.assertEqual(len(connection.test_outbox), 1)
  492. self.assertEqual(connection.test_outbox[0].subject, '[Django] Manager message')
  493. def test_dont_mangle_from_in_body(self):
  494. # Regression for #13433 - Make sure that EmailMessage doesn't mangle
  495. # 'From ' in message body.
  496. email = EmailMessage(
  497. 'Subject', 'From the future', 'bounce@example.com', ['to@example.com'],
  498. headers={'From': 'from@example.com'},
  499. )
  500. self.assertNotIn(b'>From the future', email.message().as_bytes())
  501. def test_dont_base64_encode(self):
  502. # Ticket #3472
  503. # Shouldn't use Base64 encoding at all
  504. msg = EmailMessage(
  505. 'Subject', 'UTF-8 encoded body', 'bounce@example.com', ['to@example.com'],
  506. headers={'From': 'from@example.com'},
  507. )
  508. self.assertIn(b'Content-Transfer-Encoding: 7bit', msg.message().as_bytes())
  509. # Ticket #11212
  510. # Shouldn't use quoted printable, should detect it can represent content with 7 bit data
  511. msg = EmailMessage(
  512. 'Subject', 'Body with only ASCII characters.', 'bounce@example.com', ['to@example.com'],
  513. headers={'From': 'from@example.com'},
  514. )
  515. s = msg.message().as_bytes()
  516. self.assertIn(b'Content-Transfer-Encoding: 7bit', s)
  517. # Shouldn't use quoted printable, should detect it can represent content with 8 bit data
  518. msg = EmailMessage(
  519. 'Subject', 'Body with latin characters: àáä.', 'bounce@example.com', ['to@example.com'],
  520. headers={'From': 'from@example.com'},
  521. )
  522. s = msg.message().as_bytes()
  523. self.assertIn(b'Content-Transfer-Encoding: 8bit', s)
  524. s = msg.message().as_string()
  525. self.assertIn('Content-Transfer-Encoding: 8bit', s)
  526. msg = EmailMessage(
  527. 'Subject', 'Body with non latin characters: А Б В Г Д Е Ж Ѕ З И І К Л М Н О П.', 'bounce@example.com',
  528. ['to@example.com'], headers={'From': 'from@example.com'},
  529. )
  530. s = msg.message().as_bytes()
  531. self.assertIn(b'Content-Transfer-Encoding: 8bit', s)
  532. s = msg.message().as_string()
  533. self.assertIn('Content-Transfer-Encoding: 8bit', s)
  534. def test_dont_base64_encode_message_rfc822(self):
  535. # Ticket #18967
  536. # Shouldn't use base64 encoding for a child EmailMessage attachment.
  537. # Create a child message first
  538. child_msg = EmailMessage(
  539. 'Child Subject', 'Some body of child message', 'bounce@example.com', ['to@example.com'],
  540. headers={'From': 'from@example.com'},
  541. )
  542. child_s = child_msg.message().as_string()
  543. # Now create a parent
  544. parent_msg = EmailMessage(
  545. 'Parent Subject', 'Some parent body', 'bounce@example.com', ['to@example.com'],
  546. headers={'From': 'from@example.com'},
  547. )
  548. # Attach to parent as a string
  549. parent_msg.attach(content=child_s, mimetype='message/rfc822')
  550. parent_s = parent_msg.message().as_string()
  551. # The child message header is not base64 encoded
  552. self.assertIn('Child Subject', parent_s)
  553. # Feature test: try attaching email.Message object directly to the mail.
  554. parent_msg = EmailMessage(
  555. 'Parent Subject', 'Some parent body', 'bounce@example.com', ['to@example.com'],
  556. headers={'From': 'from@example.com'},
  557. )
  558. parent_msg.attach(content=child_msg.message(), mimetype='message/rfc822')
  559. parent_s = parent_msg.message().as_string()
  560. # The child message header is not base64 encoded
  561. self.assertIn('Child Subject', parent_s)
  562. # Feature test: try attaching Django's EmailMessage object directly to the mail.
  563. parent_msg = EmailMessage(
  564. 'Parent Subject', 'Some parent body', 'bounce@example.com', ['to@example.com'],
  565. headers={'From': 'from@example.com'},
  566. )
  567. parent_msg.attach(content=child_msg, mimetype='message/rfc822')
  568. parent_s = parent_msg.message().as_string()
  569. # The child message header is not base64 encoded
  570. self.assertIn('Child Subject', parent_s)
  571. def test_sanitize_address(self):
  572. """
  573. Email addresses are properly sanitized.
  574. """
  575. # Simple ASCII address - string form
  576. self.assertEqual(sanitize_address('to@example.com', 'ascii'), 'to@example.com')
  577. self.assertEqual(sanitize_address('to@example.com', 'utf-8'), 'to@example.com')
  578. # Bytestrings are transformed to normal strings.
  579. self.assertEqual(sanitize_address(b'to@example.com', 'utf-8'), 'to@example.com')
  580. # Simple ASCII address - tuple form
  581. self.assertEqual(
  582. sanitize_address(('A name', 'to@example.com'), 'ascii'),
  583. 'A name <to@example.com>'
  584. )
  585. self.assertEqual(
  586. sanitize_address(('A name', 'to@example.com'), 'utf-8'),
  587. '=?utf-8?q?A_name?= <to@example.com>'
  588. )
  589. # Unicode characters are are supported in RFC-6532.
  590. self.assertEqual(
  591. sanitize_address('tó@example.com', 'utf-8'),
  592. '=?utf-8?b?dMOz?=@example.com'
  593. )
  594. self.assertEqual(
  595. sanitize_address(('Tó Example', 'tó@example.com'), 'utf-8'),
  596. '=?utf-8?q?T=C3=B3_Example?= <=?utf-8?b?dMOz?=@example.com>'
  597. )
  598. @requires_tz_support
  599. class MailTimeZoneTests(SimpleTestCase):
  600. @override_settings(EMAIL_USE_LOCALTIME=False, USE_TZ=True, TIME_ZONE='Africa/Algiers')
  601. def test_date_header_utc(self):
  602. """
  603. EMAIL_USE_LOCALTIME=False creates a datetime in UTC.
  604. """
  605. email = EmailMessage('Subject', 'Body', 'bounce@example.com', ['to@example.com'])
  606. self.assertTrue(email.message()['Date'].endswith('-0000'))
  607. @override_settings(EMAIL_USE_LOCALTIME=True, USE_TZ=True, TIME_ZONE='Africa/Algiers')
  608. def test_date_header_localtime(self):
  609. """
  610. EMAIL_USE_LOCALTIME=True creates a datetime in the local time zone.
  611. """
  612. email = EmailMessage('Subject', 'Body', 'bounce@example.com', ['to@example.com'])
  613. self.assertTrue(email.message()['Date'].endswith('+0100')) # Africa/Algiers is UTC+1
  614. class PythonGlobalState(SimpleTestCase):
  615. """
  616. Tests for #12422 -- Django smarts (#2472/#11212) with charset of utf-8 text
  617. parts shouldn't pollute global email Python package charset registry when
  618. django.mail.message is imported.
  619. """
  620. def test_utf8(self):
  621. txt = MIMEText('UTF-8 encoded body', 'plain', 'utf-8')
  622. self.assertIn('Content-Transfer-Encoding: base64', txt.as_string())
  623. def test_7bit(self):
  624. txt = MIMEText('Body with only ASCII characters.', 'plain', 'utf-8')
  625. self.assertIn('Content-Transfer-Encoding: base64', txt.as_string())
  626. def test_8bit_latin(self):
  627. txt = MIMEText('Body with latin characters: àáä.', 'plain', 'utf-8')
  628. self.assertIn('Content-Transfer-Encoding: base64', txt.as_string())
  629. def test_8bit_non_latin(self):
  630. txt = MIMEText('Body with non latin characters: А Б В Г Д Е Ж Ѕ З И І К Л М Н О П.', 'plain', 'utf-8')
  631. self.assertIn('Content-Transfer-Encoding: base64', txt.as_string())
  632. class BaseEmailBackendTests(HeadersCheckMixin):
  633. email_backend = None
  634. def setUp(self):
  635. self.settings_override = override_settings(EMAIL_BACKEND=self.email_backend)
  636. self.settings_override.enable()
  637. def tearDown(self):
  638. self.settings_override.disable()
  639. def assertStartsWith(self, first, second):
  640. if not first.startswith(second):
  641. self.longMessage = True
  642. self.assertEqual(first[:len(second)], second, "First string doesn't start with the second.")
  643. def get_mailbox_content(self):
  644. raise NotImplementedError('subclasses of BaseEmailBackendTests must provide a get_mailbox_content() method')
  645. def flush_mailbox(self):
  646. raise NotImplementedError('subclasses of BaseEmailBackendTests may require a flush_mailbox() method')
  647. def get_the_message(self):
  648. mailbox = self.get_mailbox_content()
  649. self.assertEqual(
  650. len(mailbox), 1,
  651. "Expected exactly one message, got %d.\n%r" % (len(mailbox), [m.as_string() for m in mailbox])
  652. )
  653. return mailbox[0]
  654. def test_send(self):
  655. email = EmailMessage('Subject', 'Content', 'from@example.com', ['to@example.com'])
  656. num_sent = mail.get_connection().send_messages([email])
  657. self.assertEqual(num_sent, 1)
  658. message = self.get_the_message()
  659. self.assertEqual(message["subject"], "Subject")
  660. self.assertEqual(message.get_payload(), "Content")
  661. self.assertEqual(message["from"], "from@example.com")
  662. self.assertEqual(message.get_all("to"), ["to@example.com"])
  663. def test_send_unicode(self):
  664. email = EmailMessage('Chère maman', 'Je t\'aime très fort', 'from@example.com', ['to@example.com'])
  665. num_sent = mail.get_connection().send_messages([email])
  666. self.assertEqual(num_sent, 1)
  667. message = self.get_the_message()
  668. self.assertEqual(message["subject"], '=?utf-8?q?Ch=C3=A8re_maman?=')
  669. self.assertEqual(force_text(message.get_payload(decode=True)), 'Je t\'aime très fort')
  670. def test_send_long_lines(self):
  671. """
  672. Email line length is limited to 998 chars by the RFC:
  673. https://tools.ietf.org/html/rfc5322#section-2.1.1
  674. Message body containing longer lines are converted to Quoted-Printable
  675. to avoid having to insert newlines, which could be hairy to do properly.
  676. """
  677. # Unencoded body length is < 998 (840) but > 998 when utf-8 encoded.
  678. email = EmailMessage('Subject', 'В южных морях ' * 60, 'from@example.com', ['to@example.com'])
  679. email.send()
  680. message = self.get_the_message()
  681. self.assertMessageHasHeaders(message, {
  682. ('MIME-Version', '1.0'),
  683. ('Content-Type', 'text/plain; charset="utf-8"'),
  684. ('Content-Transfer-Encoding', 'quoted-printable'),
  685. })
  686. def test_send_many(self):
  687. email1 = EmailMessage('Subject', 'Content1', 'from@example.com', ['to@example.com'])
  688. email2 = EmailMessage('Subject', 'Content2', 'from@example.com', ['to@example.com'])
  689. # send_messages() may take a list or a generator.
  690. emails_lists = ([email1, email2], (email for email in [email1, email2]))
  691. for emails_list in emails_lists:
  692. num_sent = mail.get_connection().send_messages(emails_list)
  693. self.assertEqual(num_sent, 2)
  694. messages = self.get_mailbox_content()
  695. self.assertEqual(len(messages), 2)
  696. self.assertEqual(messages[0].get_payload(), 'Content1')
  697. self.assertEqual(messages[1].get_payload(), 'Content2')
  698. self.flush_mailbox()
  699. def test_send_verbose_name(self):
  700. email = EmailMessage("Subject", "Content", '"Firstname Sürname" <from@example.com>',
  701. ["to@example.com"])
  702. email.send()
  703. message = self.get_the_message()
  704. self.assertEqual(message["subject"], "Subject")
  705. self.assertEqual(message.get_payload(), "Content")
  706. self.assertEqual(message["from"], "=?utf-8?q?Firstname_S=C3=BCrname?= <from@example.com>")
  707. def test_plaintext_send_mail(self):
  708. """
  709. Test send_mail without the html_message
  710. regression test for adding html_message parameter to send_mail()
  711. """
  712. send_mail('Subject', 'Content', 'sender@example.com', ['nobody@example.com'])
  713. message = self.get_the_message()
  714. self.assertEqual(message.get('subject'), 'Subject')
  715. self.assertEqual(message.get_all('to'), ['nobody@example.com'])
  716. self.assertFalse(message.is_multipart())
  717. self.assertEqual(message.get_payload(), 'Content')
  718. self.assertEqual(message.get_content_type(), 'text/plain')
  719. def test_html_send_mail(self):
  720. """Test html_message argument to send_mail"""
  721. send_mail('Subject', 'Content', 'sender@example.com', ['nobody@example.com'], html_message='HTML Content')
  722. message = self.get_the_message()
  723. self.assertEqual(message.get('subject'), 'Subject')
  724. self.assertEqual(message.get_all('to'), ['nobody@example.com'])
  725. self.assertTrue(message.is_multipart())
  726. self.assertEqual(len(message.get_payload()), 2)
  727. self.assertEqual(message.get_payload(0).get_payload(), 'Content')
  728. self.assertEqual(message.get_payload(0).get_content_type(), 'text/plain')
  729. self.assertEqual(message.get_payload(1).get_payload(), 'HTML Content')
  730. self.assertEqual(message.get_payload(1).get_content_type(), 'text/html')
  731. @override_settings(MANAGERS=[('nobody', 'nobody@example.com')])
  732. def test_html_mail_managers(self):
  733. """Test html_message argument to mail_managers"""
  734. mail_managers('Subject', 'Content', html_message='HTML Content')
  735. message = self.get_the_message()
  736. self.assertEqual(message.get('subject'), '[Django] Subject')
  737. self.assertEqual(message.get_all('to'), ['nobody@example.com'])
  738. self.assertTrue(message.is_multipart())
  739. self.assertEqual(len(message.get_payload()), 2)
  740. self.assertEqual(message.get_payload(0).get_payload(), 'Content')
  741. self.assertEqual(message.get_payload(0).get_content_type(), 'text/plain')
  742. self.assertEqual(message.get_payload(1).get_payload(), 'HTML Content')
  743. self.assertEqual(message.get_payload(1).get_content_type(), 'text/html')
  744. @override_settings(ADMINS=[('nobody', 'nobody@example.com')])
  745. def test_html_mail_admins(self):
  746. """Test html_message argument to mail_admins """
  747. mail_admins('Subject', 'Content', html_message='HTML Content')
  748. message = self.get_the_message()
  749. self.assertEqual(message.get('subject'), '[Django] Subject')
  750. self.assertEqual(message.get_all('to'), ['nobody@example.com'])
  751. self.assertTrue(message.is_multipart())
  752. self.assertEqual(len(message.get_payload()), 2)
  753. self.assertEqual(message.get_payload(0).get_payload(), 'Content')
  754. self.assertEqual(message.get_payload(0).get_content_type(), 'text/plain')
  755. self.assertEqual(message.get_payload(1).get_payload(), 'HTML Content')
  756. self.assertEqual(message.get_payload(1).get_content_type(), 'text/html')
  757. @override_settings(
  758. ADMINS=[('nobody', 'nobody+admin@example.com')],
  759. MANAGERS=[('nobody', 'nobody+manager@example.com')])
  760. def test_manager_and_admin_mail_prefix(self):
  761. """
  762. String prefix + lazy translated subject = bad output
  763. Regression for #13494
  764. """
  765. mail_managers(ugettext_lazy('Subject'), 'Content')
  766. message = self.get_the_message()
  767. self.assertEqual(message.get('subject'), '[Django] Subject')
  768. self.flush_mailbox()
  769. mail_admins(ugettext_lazy('Subject'), 'Content')
  770. message = self.get_the_message()
  771. self.assertEqual(message.get('subject'), '[Django] Subject')
  772. @override_settings(ADMINS=[], MANAGERS=[])
  773. def test_empty_admins(self):
  774. """
  775. mail_admins/mail_managers doesn't connect to the mail server
  776. if there are no recipients (#9383)
  777. """
  778. mail_admins('hi', 'there')
  779. self.assertEqual(self.get_mailbox_content(), [])
  780. mail_managers('hi', 'there')
  781. self.assertEqual(self.get_mailbox_content(), [])
  782. def test_message_cc_header(self):
  783. """
  784. Regression test for #7722
  785. """
  786. email = EmailMessage('Subject', 'Content', 'from@example.com', ['to@example.com'], cc=['cc@example.com'])
  787. mail.get_connection().send_messages([email])
  788. message = self.get_the_message()
  789. self.assertMessageHasHeaders(message, {
  790. ('MIME-Version', '1.0'),
  791. ('Content-Type', 'text/plain; charset="utf-8"'),
  792. ('Content-Transfer-Encoding', '7bit'),
  793. ('Subject', 'Subject'),
  794. ('From', 'from@example.com'),
  795. ('To', 'to@example.com'),
  796. ('Cc', 'cc@example.com')})
  797. self.assertIn('\nDate: ', message.as_string())
  798. def test_idn_send(self):
  799. """
  800. Regression test for #14301
  801. """
  802. self.assertTrue(send_mail('Subject', 'Content', 'from@öäü.com', ['to@öäü.com']))
  803. message = self.get_the_message()
  804. self.assertEqual(message.get('subject'), 'Subject')
  805. self.assertEqual(message.get('from'), 'from@xn--4ca9at.com')
  806. self.assertEqual(message.get('to'), 'to@xn--4ca9at.com')
  807. self.flush_mailbox()
  808. m = EmailMessage('Subject', 'Content', 'from@öäü.com', ['to@öäü.com'], cc=['cc@öäü.com'])
  809. m.send()
  810. message = self.get_the_message()
  811. self.assertEqual(message.get('subject'), 'Subject')
  812. self.assertEqual(message.get('from'), 'from@xn--4ca9at.com')
  813. self.assertEqual(message.get('to'), 'to@xn--4ca9at.com')
  814. self.assertEqual(message.get('cc'), 'cc@xn--4ca9at.com')
  815. def test_recipient_without_domain(self):
  816. """
  817. Regression test for #15042
  818. """
  819. self.assertTrue(send_mail("Subject", "Content", "tester", ["django"]))
  820. message = self.get_the_message()
  821. self.assertEqual(message.get('subject'), 'Subject')
  822. self.assertEqual(message.get('from'), "tester")
  823. self.assertEqual(message.get('to'), "django")
  824. def test_lazy_addresses(self):
  825. """
  826. Email sending should support lazy email addresses (#24416).
  827. """
  828. _ = ugettext_lazy
  829. self.assertTrue(send_mail('Subject', 'Content', _('tester'), [_('django')]))
  830. message = self.get_the_message()
  831. self.assertEqual(message.get('from'), 'tester')
  832. self.assertEqual(message.get('to'), 'django')
  833. self.flush_mailbox()
  834. m = EmailMessage(
  835. 'Subject', 'Content', _('tester'), [_('to1'), _('to2')],
  836. cc=[_('cc1'), _('cc2')],
  837. bcc=[_('bcc')],
  838. reply_to=[_('reply')],
  839. )
  840. self.assertEqual(m.recipients(), ['to1', 'to2', 'cc1', 'cc2', 'bcc'])
  841. m.send()
  842. message = self.get_the_message()
  843. self.assertEqual(message.get('from'), 'tester')
  844. self.assertEqual(message.get('to'), 'to1, to2')
  845. self.assertEqual(message.get('cc'), 'cc1, cc2')
  846. self.assertEqual(message.get('Reply-To'), 'reply')
  847. def test_close_connection(self):
  848. """
  849. Connection can be closed (even when not explicitly opened)
  850. """
  851. conn = mail.get_connection(username='', password='')
  852. conn.close()
  853. def test_use_as_contextmanager(self):
  854. """
  855. The connection can be used as a contextmanager.
  856. """
  857. opened = [False]
  858. closed = [False]
  859. conn = mail.get_connection(username='', password='')
  860. def open():
  861. opened[0] = True
  862. conn.open = open
  863. def close():
  864. closed[0] = True
  865. conn.close = close
  866. with conn as same_conn:
  867. self.assertTrue(opened[0])
  868. self.assertIs(same_conn, conn)
  869. self.assertFalse(closed[0])
  870. self.assertTrue(closed[0])
  871. class LocmemBackendTests(BaseEmailBackendTests, SimpleTestCase):
  872. email_backend = 'django.core.mail.backends.locmem.EmailBackend'
  873. def get_mailbox_content(self):
  874. return [m.message() for m in mail.outbox]
  875. def flush_mailbox(self):
  876. mail.outbox = []
  877. def tearDown(self):
  878. super().tearDown()
  879. mail.outbox = []
  880. def test_locmem_shared_messages(self):
  881. """
  882. Make sure that the locmen backend populates the outbox.
  883. """
  884. connection = locmem.EmailBackend()
  885. connection2 = locmem.EmailBackend()
  886. email = EmailMessage(
  887. 'Subject', 'Content', 'bounce@example.com', ['to@example.com'],
  888. headers={'From': 'from@example.com'},
  889. )
  890. connection.send_messages([email])
  891. connection2.send_messages([email])
  892. self.assertEqual(len(mail.outbox), 2)
  893. def test_validate_multiline_headers(self):
  894. # Ticket #18861 - Validate emails when using the locmem backend
  895. with self.assertRaises(BadHeaderError):
  896. send_mail('Subject\nMultiline', 'Content', 'from@example.com', ['to@example.com'])
  897. class FileBackendTests(BaseEmailBackendTests, SimpleTestCase):
  898. email_backend = 'django.core.mail.backends.filebased.EmailBackend'
  899. def setUp(self):
  900. super().setUp()
  901. self.tmp_dir = tempfile.mkdtemp()
  902. self.addCleanup(shutil.rmtree, self.tmp_dir)
  903. self._settings_override = override_settings(EMAIL_FILE_PATH=self.tmp_dir)
  904. self._settings_override.enable()
  905. def tearDown(self):
  906. self._settings_override.disable()
  907. super().tearDown()
  908. def flush_mailbox(self):
  909. for filename in os.listdir(self.tmp_dir):
  910. os.unlink(os.path.join(self.tmp_dir, filename))
  911. def get_mailbox_content(self):
  912. messages = []
  913. for filename in os.listdir(self.tmp_dir):
  914. with open(os.path.join(self.tmp_dir, filename), 'rb') as fp:
  915. session = fp.read().split(force_bytes('\n' + ('-' * 79) + '\n', encoding='ascii'))
  916. messages.extend(message_from_bytes(m) for m in session if m)
  917. return messages
  918. def test_file_sessions(self):
  919. """Make sure opening a connection creates a new file"""
  920. msg = EmailMessage(
  921. 'Subject', 'Content', 'bounce@example.com', ['to@example.com'],
  922. headers={'From': 'from@example.com'},
  923. )
  924. connection = mail.get_connection()
  925. connection.send_messages([msg])
  926. self.assertEqual(len(os.listdir(self.tmp_dir)), 1)
  927. with open(os.path.join(self.tmp_dir, os.listdir(self.tmp_dir)[0]), 'rb') as fp:
  928. message = message_from_binary_file(fp)
  929. self.assertEqual(message.get_content_type(), 'text/plain')
  930. self.assertEqual(message.get('subject'), 'Subject')
  931. self.assertEqual(message.get('from'), 'from@example.com')
  932. self.assertEqual(message.get('to'), 'to@example.com')
  933. connection2 = mail.get_connection()
  934. connection2.send_messages([msg])
  935. self.assertEqual(len(os.listdir(self.tmp_dir)), 2)
  936. connection.send_messages([msg])
  937. self.assertEqual(len(os.listdir(self.tmp_dir)), 2)
  938. msg.connection = mail.get_connection()
  939. self.assertTrue(connection.open())
  940. msg.send()
  941. self.assertEqual(len(os.listdir(self.tmp_dir)), 3)
  942. msg.send()
  943. self.assertEqual(len(os.listdir(self.tmp_dir)), 3)
  944. connection.close()
  945. class ConsoleBackendTests(BaseEmailBackendTests, SimpleTestCase):
  946. email_backend = 'django.core.mail.backends.console.EmailBackend'
  947. def setUp(self):
  948. super().setUp()
  949. self.__stdout = sys.stdout
  950. self.stream = sys.stdout = StringIO()
  951. def tearDown(self):
  952. del self.stream
  953. sys.stdout = self.__stdout
  954. del self.__stdout
  955. super().tearDown()
  956. def flush_mailbox(self):
  957. self.stream = sys.stdout = StringIO()
  958. def get_mailbox_content(self):
  959. messages = self.stream.getvalue().split('\n' + ('-' * 79) + '\n')
  960. return [message_from_bytes(force_bytes(m)) for m in messages if m]
  961. def test_console_stream_kwarg(self):
  962. """
  963. The console backend can be pointed at an arbitrary stream.
  964. """
  965. s = StringIO()
  966. connection = mail.get_connection('django.core.mail.backends.console.EmailBackend', stream=s)
  967. send_mail('Subject', 'Content', 'from@example.com', ['to@example.com'], connection=connection)
  968. message = force_bytes(s.getvalue().split('\n' + ('-' * 79) + '\n')[0])
  969. self.assertMessageHasHeaders(message, {
  970. ('MIME-Version', '1.0'),
  971. ('Content-Type', 'text/plain; charset="utf-8"'),
  972. ('Content-Transfer-Encoding', '7bit'),
  973. ('Subject', 'Subject'),
  974. ('From', 'from@example.com'),
  975. ('To', 'to@example.com')})
  976. self.assertIn(b'\nDate: ', message)
  977. class FakeSMTPChannel(smtpd.SMTPChannel):
  978. def collect_incoming_data(self, data):
  979. try:
  980. smtpd.SMTPChannel.collect_incoming_data(self, data)
  981. except UnicodeDecodeError:
  982. # ignore decode error in SSL/TLS connection tests as we only care
  983. # whether the connection attempt was made
  984. pass
  985. def smtp_AUTH(self, arg):
  986. if arg == 'CRAM-MD5':
  987. # This is only the first part of the login process. But it's enough
  988. # for our tests.
  989. challenge = base64.b64encode(b'somerandomstring13579')
  990. self.push('334 %s' % challenge.decode())
  991. else:
  992. self.push('502 Error: login "%s" not implemented' % arg)
  993. class FakeSMTPServer(smtpd.SMTPServer, threading.Thread):
  994. """
  995. Asyncore SMTP server wrapped into a thread. Based on DummyFTPServer from:
  996. http://svn.python.org/view/python/branches/py3k/Lib/test/test_ftplib.py?revision=86061&view=markup
  997. """
  998. channel_class = FakeSMTPChannel
  999. def __init__(self, *args, **kwargs):
  1000. threading.Thread.__init__(self)
  1001. # New kwarg added in Python 3.5; default switching to False in 3.6.
  1002. if sys.version_info >= (3, 5):
  1003. kwargs['decode_data'] = True
  1004. smtpd.SMTPServer.__init__(self, *args, **kwargs)
  1005. self._sink = []
  1006. self.active = False
  1007. self.active_lock = threading.Lock()
  1008. self.sink_lock = threading.Lock()
  1009. def process_message(self, peer, mailfrom, rcpttos, data):
  1010. data = data.encode('utf-8')
  1011. m = message_from_bytes(data)
  1012. maddr = parseaddr(m.get('from'))[1]
  1013. if mailfrom != maddr:
  1014. # According to the spec, mailfrom does not necessarily match the
  1015. # From header - this is the case where the local part isn't
  1016. # encoded, so try to correct that.
  1017. lp, domain = mailfrom.split('@', 1)
  1018. lp = Header(lp, 'utf-8').encode()
  1019. mailfrom = '@'.join([lp, domain])
  1020. if mailfrom != maddr:
  1021. return "553 '%s' != '%s'" % (mailfrom, maddr)
  1022. with self.sink_lock:
  1023. self._sink.append(m)
  1024. def get_sink(self):
  1025. with self.sink_lock:
  1026. return self._sink[:]
  1027. def flush_sink(self):
  1028. with self.sink_lock:
  1029. self._sink[:] = []
  1030. def start(self):
  1031. assert not self.active
  1032. self.__flag = threading.Event()
  1033. threading.Thread.start(self)
  1034. self.__flag.wait()
  1035. def run(self):
  1036. self.active = True
  1037. self.__flag.set()
  1038. while self.active and asyncore.socket_map:
  1039. with self.active_lock:
  1040. asyncore.loop(timeout=0.1, count=1)
  1041. asyncore.close_all()
  1042. def stop(self):
  1043. if self.active:
  1044. self.active = False
  1045. self.join()
  1046. class FakeAUTHSMTPConnection(SMTP):
  1047. """
  1048. A SMTP connection pretending support for the AUTH command. It does not, but
  1049. at least this can allow testing the first part of the AUTH process.
  1050. """
  1051. def ehlo(self, name=''):
  1052. response = SMTP.ehlo(self, name=name)
  1053. self.esmtp_features.update({
  1054. 'auth': 'CRAM-MD5 PLAIN LOGIN',
  1055. })
  1056. return response
  1057. class SMTPBackendTestsBase(SimpleTestCase):
  1058. @classmethod
  1059. def setUpClass(cls):
  1060. super().setUpClass()
  1061. cls.server = FakeSMTPServer(('127.0.0.1', 0), None)
  1062. cls._settings_override = override_settings(
  1063. EMAIL_HOST="127.0.0.1",
  1064. EMAIL_PORT=cls.server.socket.getsockname()[1])
  1065. cls._settings_override.enable()
  1066. cls.server.start()
  1067. @classmethod
  1068. def tearDownClass(cls):
  1069. cls._settings_override.disable()
  1070. cls.server.stop()
  1071. super().tearDownClass()
  1072. class SMTPBackendTests(BaseEmailBackendTests, SMTPBackendTestsBase):
  1073. email_backend = 'django.core.mail.backends.smtp.EmailBackend'
  1074. def setUp(self):
  1075. super().setUp()
  1076. self.server.flush_sink()
  1077. def tearDown(self):
  1078. self.server.flush_sink()
  1079. super().tearDown()
  1080. def flush_mailbox(self):
  1081. self.server.flush_sink()
  1082. def get_mailbox_content(self):
  1083. return self.server.get_sink()
  1084. @override_settings(
  1085. EMAIL_HOST_USER="not empty username",
  1086. EMAIL_HOST_PASSWORD="not empty password")
  1087. def test_email_authentication_use_settings(self):
  1088. backend = smtp.EmailBackend()
  1089. self.assertEqual(backend.username, 'not empty username')
  1090. self.assertEqual(backend.password, 'not empty password')
  1091. @override_settings(
  1092. EMAIL_HOST_USER="not empty username",
  1093. EMAIL_HOST_PASSWORD="not empty password")
  1094. def test_email_authentication_override_settings(self):
  1095. backend = smtp.EmailBackend(username='username', password='password')
  1096. self.assertEqual(backend.username, 'username')
  1097. self.assertEqual(backend.password, 'password')
  1098. @override_settings(
  1099. EMAIL_HOST_USER="not empty username",
  1100. EMAIL_HOST_PASSWORD="not empty password")
  1101. def test_email_disabled_authentication(self):
  1102. backend = smtp.EmailBackend(username='', password='')
  1103. self.assertEqual(backend.username, '')
  1104. self.assertEqual(backend.password, '')
  1105. def test_auth_attempted(self):
  1106. """
  1107. Opening the backend with non empty username/password tries
  1108. to authenticate against the SMTP server.
  1109. """
  1110. backend = smtp.EmailBackend(
  1111. username='not empty username', password='not empty password')
  1112. with self.assertRaisesMessage(SMTPException, 'SMTP AUTH extension not supported by server.'):
  1113. with backend:
  1114. pass
  1115. def test_server_open(self):
  1116. """
  1117. open() returns whether it opened a connection.
  1118. """
  1119. backend = smtp.EmailBackend(username='', password='')
  1120. self.assertFalse(backend.connection)
  1121. opened = backend.open()
  1122. backend.close()
  1123. self.assertTrue(opened)
  1124. def test_server_login(self):
  1125. """
  1126. Even if the Python SMTP server doesn't support authentication, the
  1127. login process starts and the appropriate exception is raised.
  1128. """
  1129. class CustomEmailBackend(smtp.EmailBackend):
  1130. connection_class = FakeAUTHSMTPConnection
  1131. backend = CustomEmailBackend(username='username', password='password')
  1132. with self.assertRaises(SMTPAuthenticationError):
  1133. with backend:
  1134. pass
  1135. @override_settings(EMAIL_USE_TLS=True)
  1136. def test_email_tls_use_settings(self):
  1137. backend = smtp.EmailBackend()
  1138. self.assertTrue(backend.use_tls)
  1139. @override_settings(EMAIL_USE_TLS=True)
  1140. def test_email_tls_override_settings(self):
  1141. backend = smtp.EmailBackend(use_tls=False)
  1142. self.assertFalse(backend.use_tls)
  1143. def test_email_tls_default_disabled(self):
  1144. backend = smtp.EmailBackend()
  1145. self.assertFalse(backend.use_tls)
  1146. @override_settings(EMAIL_USE_SSL=True)
  1147. def test_email_ssl_use_settings(self):
  1148. backend = smtp.EmailBackend()
  1149. self.assertTrue(backend.use_ssl)
  1150. @override_settings(EMAIL_USE_SSL=True)
  1151. def test_email_ssl_override_settings(self):
  1152. backend = smtp.EmailBackend(use_ssl=False)
  1153. self.assertFalse(backend.use_ssl)
  1154. def test_email_ssl_default_disabled(self):
  1155. backend = smtp.EmailBackend()
  1156. self.assertFalse(backend.use_ssl)
  1157. @override_settings(EMAIL_SSL_CERTFILE='foo')
  1158. def test_email_ssl_certfile_use_settings(self):
  1159. backend = smtp.EmailBackend()
  1160. self.assertEqual(backend.ssl_certfile, 'foo')
  1161. @override_settings(EMAIL_SSL_CERTFILE='foo')
  1162. def test_email_ssl_certfile_override_settings(self):
  1163. backend = smtp.EmailBackend(ssl_certfile='bar')
  1164. self.assertEqual(backend.ssl_certfile, 'bar')
  1165. def test_email_ssl_certfile_default_disabled(self):
  1166. backend = smtp.EmailBackend()
  1167. self.assertIsNone(backend.ssl_certfile)
  1168. @override_settings(EMAIL_SSL_KEYFILE='foo')
  1169. def test_email_ssl_keyfile_use_settings(self):
  1170. backend = smtp.EmailBackend()
  1171. self.assertEqual(backend.ssl_keyfile, 'foo')
  1172. @override_settings(EMAIL_SSL_KEYFILE='foo')
  1173. def test_email_ssl_keyfile_override_settings(self):
  1174. backend = smtp.EmailBackend(ssl_keyfile='bar')
  1175. self.assertEqual(backend.ssl_keyfile, 'bar')
  1176. def test_email_ssl_keyfile_default_disabled(self):
  1177. backend = smtp.EmailBackend()
  1178. self.assertIsNone(backend.ssl_keyfile)
  1179. @override_settings(EMAIL_USE_TLS=True)
  1180. def test_email_tls_attempts_starttls(self):
  1181. backend = smtp.EmailBackend()
  1182. self.assertTrue(backend.use_tls)
  1183. with self.assertRaisesMessage(SMTPException, 'STARTTLS extension not supported by server.'):
  1184. with backend:
  1185. pass
  1186. @override_settings(EMAIL_USE_SSL=True)
  1187. def test_email_ssl_attempts_ssl_connection(self):
  1188. backend = smtp.EmailBackend()
  1189. self.assertTrue(backend.use_ssl)
  1190. with self.assertRaises(SSLError):
  1191. with backend:
  1192. pass
  1193. def test_connection_timeout_default(self):
  1194. """The connection's timeout value is None by default."""
  1195. connection = mail.get_connection('django.core.mail.backends.smtp.EmailBackend')
  1196. self.assertIsNone(connection.timeout)
  1197. def test_connection_timeout_custom(self):
  1198. """The timeout parameter can be customized."""
  1199. class MyEmailBackend(smtp.EmailBackend):
  1200. def __init__(self, *args, **kwargs):
  1201. kwargs.setdefault('timeout', 42)
  1202. super().__init__(*args, **kwargs)
  1203. myemailbackend = MyEmailBackend()
  1204. myemailbackend.open()
  1205. self.assertEqual(myemailbackend.timeout, 42)
  1206. self.assertEqual(myemailbackend.connection.timeout, 42)
  1207. myemailbackend.close()
  1208. @override_settings(EMAIL_TIMEOUT=10)
  1209. def test_email_timeout_override_settings(self):
  1210. backend = smtp.EmailBackend()
  1211. self.assertEqual(backend.timeout, 10)
  1212. def test_email_msg_uses_crlf(self):
  1213. """#23063 -- RFC-compliant messages are sent over SMTP."""
  1214. send = SMTP.send
  1215. try:
  1216. smtp_messages = []
  1217. def mock_send(self, s):
  1218. smtp_messages.append(s)
  1219. return send(self, s)
  1220. SMTP.send = mock_send
  1221. email = EmailMessage('Subject', 'Content', 'from@example.com', ['to@example.com'])
  1222. mail.get_connection().send_messages([email])
  1223. # Find the actual message
  1224. msg = None
  1225. for i, m in enumerate(smtp_messages):
  1226. if m[:4] == 'data':
  1227. msg = smtp_messages[i + 1]
  1228. break
  1229. self.assertTrue(msg)
  1230. msg = msg.decode('utf-8')
  1231. # The message only contains CRLF and not combinations of CRLF, LF, and CR.
  1232. msg = msg.replace('\r\n', '')
  1233. self.assertNotIn('\r', msg)
  1234. self.assertNotIn('\n', msg)
  1235. finally:
  1236. SMTP.send = send
  1237. def test_send_messages_after_open_failed(self):
  1238. """
  1239. send_messages() shouldn't try to send messages if open() raises an
  1240. exception after initializing the connection.
  1241. """
  1242. backend = smtp.EmailBackend()
  1243. # Simulate connection initialization success and a subsequent
  1244. # connection exception.
  1245. backend.connection = True
  1246. backend.open = lambda: None
  1247. email = EmailMessage('Subject', 'Content', 'from@example.com', ['to@example.com'])
  1248. self.assertEqual(backend.send_messages([email]), None)
  1249. class SMTPBackendStoppedServerTests(SMTPBackendTestsBase):
  1250. """
  1251. These tests require a separate class, because the FakeSMTPServer is shut
  1252. down in setUpClass(), and it cannot be restarted ("RuntimeError: threads
  1253. can only be started once").
  1254. """
  1255. @classmethod
  1256. def setUpClass(cls):
  1257. super().setUpClass()
  1258. cls.backend = smtp.EmailBackend(username='', password='')
  1259. cls.server.stop()
  1260. def test_server_stopped(self):
  1261. """
  1262. Closing the backend while the SMTP server is stopped doesn't raise an
  1263. exception.
  1264. """
  1265. self.backend.close()
  1266. def test_fail_silently_on_connection_error(self):
  1267. """
  1268. A socket connection error is silenced with fail_silently=True.
  1269. """
  1270. with self.assertRaises(socket.error):
  1271. self.backend.open()
  1272. self.backend.fail_silently = True
  1273. self.backend.open()