tests.py 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008
  1. import mimetypes
  2. import os
  3. import shutil
  4. import socket
  5. import sys
  6. import tempfile
  7. from email import charset, message_from_binary_file, message_from_bytes
  8. from email.header import Header
  9. from email.mime.text import MIMEText
  10. from email.utils import parseaddr
  11. from io import StringIO
  12. from pathlib import Path
  13. from smtplib import SMTP, SMTPException
  14. from ssl import SSLError
  15. from unittest import mock, skipUnless
  16. from django.core import mail
  17. from django.core.mail import (
  18. DNS_NAME,
  19. EmailMessage,
  20. EmailMultiAlternatives,
  21. mail_admins,
  22. mail_managers,
  23. send_mail,
  24. send_mass_mail,
  25. )
  26. from django.core.mail.backends import console, dummy, filebased, locmem, smtp
  27. from django.core.mail.message import BadHeaderError, sanitize_address
  28. from django.test import SimpleTestCase, override_settings
  29. from django.test.utils import requires_tz_support
  30. from django.utils.translation import gettext_lazy
  31. from django.utils.version import PY311
  32. try:
  33. from aiosmtpd.controller import Controller
  34. HAS_AIOSMTPD = True
  35. except ImportError:
  36. HAS_AIOSMTPD = False
  37. class HeadersCheckMixin:
  38. def assertMessageHasHeaders(self, message, headers):
  39. """
  40. Asserts that the `message` has all `headers`.
  41. message: can be an instance of an email.Message subclass or a string
  42. with the contents of an email message.
  43. headers: should be a set of (header-name, header-value) tuples.
  44. """
  45. if isinstance(message, bytes):
  46. message = message_from_bytes(message)
  47. msg_headers = set(message.items())
  48. self.assertTrue(
  49. headers.issubset(msg_headers),
  50. msg="Message is missing "
  51. "the following headers: %s" % (headers - msg_headers),
  52. )
  53. class MailTests(HeadersCheckMixin, SimpleTestCase):
  54. """
  55. Non-backend specific tests.
  56. """
  57. def get_decoded_attachments(self, django_message):
  58. """
  59. Encode the specified django.core.mail.message.EmailMessage, then decode
  60. it using Python's email.parser module and, for each attachment of the
  61. message, return a list of tuples with (filename, content, mimetype).
  62. """
  63. msg_bytes = django_message.message().as_bytes()
  64. email_message = message_from_bytes(msg_bytes)
  65. def iter_attachments():
  66. for i in email_message.walk():
  67. if i.get_content_disposition() == "attachment":
  68. filename = i.get_filename()
  69. content = i.get_payload(decode=True)
  70. mimetype = i.get_content_type()
  71. yield filename, content, mimetype
  72. return list(iter_attachments())
  73. def test_ascii(self):
  74. email = EmailMessage(
  75. "Subject", "Content", "from@example.com", ["to@example.com"]
  76. )
  77. message = email.message()
  78. self.assertEqual(message["Subject"], "Subject")
  79. self.assertEqual(message.get_payload(), "Content")
  80. self.assertEqual(message["From"], "from@example.com")
  81. self.assertEqual(message["To"], "to@example.com")
  82. def test_multiple_recipients(self):
  83. email = EmailMessage(
  84. "Subject",
  85. "Content",
  86. "from@example.com",
  87. ["to@example.com", "other@example.com"],
  88. )
  89. message = email.message()
  90. self.assertEqual(message["Subject"], "Subject")
  91. self.assertEqual(message.get_payload(), "Content")
  92. self.assertEqual(message["From"], "from@example.com")
  93. self.assertEqual(message["To"], "to@example.com, other@example.com")
  94. def test_header_omitted_for_no_to_recipients(self):
  95. message = EmailMessage(
  96. "Subject", "Content", "from@example.com", cc=["cc@example.com"]
  97. ).message()
  98. self.assertNotIn("To", message)
  99. def test_recipients_with_empty_strings(self):
  100. """
  101. Empty strings in various recipient arguments are always stripped
  102. off the final recipient list.
  103. """
  104. email = EmailMessage(
  105. "Subject",
  106. "Content",
  107. "from@example.com",
  108. ["to@example.com", ""],
  109. cc=["cc@example.com", ""],
  110. bcc=["", "bcc@example.com"],
  111. reply_to=["", None],
  112. )
  113. self.assertEqual(
  114. email.recipients(), ["to@example.com", "cc@example.com", "bcc@example.com"]
  115. )
  116. def test_cc(self):
  117. """Regression test for #7722"""
  118. email = EmailMessage(
  119. "Subject",
  120. "Content",
  121. "from@example.com",
  122. ["to@example.com"],
  123. cc=["cc@example.com"],
  124. )
  125. message = email.message()
  126. self.assertEqual(message["Cc"], "cc@example.com")
  127. self.assertEqual(email.recipients(), ["to@example.com", "cc@example.com"])
  128. # Test multiple CC with multiple To
  129. email = EmailMessage(
  130. "Subject",
  131. "Content",
  132. "from@example.com",
  133. ["to@example.com", "other@example.com"],
  134. cc=["cc@example.com", "cc.other@example.com"],
  135. )
  136. message = email.message()
  137. self.assertEqual(message["Cc"], "cc@example.com, cc.other@example.com")
  138. self.assertEqual(
  139. email.recipients(),
  140. [
  141. "to@example.com",
  142. "other@example.com",
  143. "cc@example.com",
  144. "cc.other@example.com",
  145. ],
  146. )
  147. # Testing with Bcc
  148. email = EmailMessage(
  149. "Subject",
  150. "Content",
  151. "from@example.com",
  152. ["to@example.com", "other@example.com"],
  153. cc=["cc@example.com", "cc.other@example.com"],
  154. bcc=["bcc@example.com"],
  155. )
  156. message = email.message()
  157. self.assertEqual(message["Cc"], "cc@example.com, cc.other@example.com")
  158. self.assertEqual(
  159. email.recipients(),
  160. [
  161. "to@example.com",
  162. "other@example.com",
  163. "cc@example.com",
  164. "cc.other@example.com",
  165. "bcc@example.com",
  166. ],
  167. )
  168. def test_cc_headers(self):
  169. message = EmailMessage(
  170. "Subject",
  171. "Content",
  172. "bounce@example.com",
  173. ["to@example.com"],
  174. cc=["foo@example.com"],
  175. headers={"Cc": "override@example.com"},
  176. ).message()
  177. self.assertEqual(message["Cc"], "override@example.com")
  178. def test_cc_in_headers_only(self):
  179. message = EmailMessage(
  180. "Subject",
  181. "Content",
  182. "bounce@example.com",
  183. ["to@example.com"],
  184. headers={"Cc": "foo@example.com"},
  185. ).message()
  186. self.assertEqual(message["Cc"], "foo@example.com")
  187. def test_reply_to(self):
  188. email = EmailMessage(
  189. "Subject",
  190. "Content",
  191. "from@example.com",
  192. ["to@example.com"],
  193. reply_to=["reply_to@example.com"],
  194. )
  195. message = email.message()
  196. self.assertEqual(message["Reply-To"], "reply_to@example.com")
  197. email = EmailMessage(
  198. "Subject",
  199. "Content",
  200. "from@example.com",
  201. ["to@example.com"],
  202. reply_to=["reply_to1@example.com", "reply_to2@example.com"],
  203. )
  204. message = email.message()
  205. self.assertEqual(
  206. message["Reply-To"], "reply_to1@example.com, reply_to2@example.com"
  207. )
  208. def test_recipients_as_tuple(self):
  209. email = EmailMessage(
  210. "Subject",
  211. "Content",
  212. "from@example.com",
  213. ("to@example.com", "other@example.com"),
  214. cc=("cc@example.com", "cc.other@example.com"),
  215. bcc=("bcc@example.com",),
  216. )
  217. message = email.message()
  218. self.assertEqual(message["Cc"], "cc@example.com, cc.other@example.com")
  219. self.assertEqual(
  220. email.recipients(),
  221. [
  222. "to@example.com",
  223. "other@example.com",
  224. "cc@example.com",
  225. "cc.other@example.com",
  226. "bcc@example.com",
  227. ],
  228. )
  229. def test_recipients_as_string(self):
  230. with self.assertRaisesMessage(
  231. TypeError, '"to" argument must be a list or tuple'
  232. ):
  233. EmailMessage(to="foo@example.com")
  234. with self.assertRaisesMessage(
  235. TypeError, '"cc" argument must be a list or tuple'
  236. ):
  237. EmailMessage(cc="foo@example.com")
  238. with self.assertRaisesMessage(
  239. TypeError, '"bcc" argument must be a list or tuple'
  240. ):
  241. EmailMessage(bcc="foo@example.com")
  242. with self.assertRaisesMessage(
  243. TypeError, '"reply_to" argument must be a list or tuple'
  244. ):
  245. EmailMessage(reply_to="reply_to@example.com")
  246. def test_header_injection(self):
  247. msg = "Header values can't contain newlines "
  248. email = EmailMessage(
  249. "Subject\nInjection Test", "Content", "from@example.com", ["to@example.com"]
  250. )
  251. with self.assertRaisesMessage(BadHeaderError, msg):
  252. email.message()
  253. email = EmailMessage(
  254. gettext_lazy("Subject\nInjection Test"),
  255. "Content",
  256. "from@example.com",
  257. ["to@example.com"],
  258. )
  259. with self.assertRaisesMessage(BadHeaderError, msg):
  260. email.message()
  261. with self.assertRaisesMessage(BadHeaderError, msg):
  262. EmailMessage(
  263. "Subject",
  264. "Content",
  265. "from@example.com",
  266. ["Name\nInjection test <to@example.com>"],
  267. ).message()
  268. def test_space_continuation(self):
  269. """
  270. Test for space continuation character in long (ASCII) subject headers (#7747)
  271. """
  272. email = EmailMessage(
  273. "Long subject lines that get wrapped should contain a space continuation "
  274. "character to get expected behavior in Outlook and Thunderbird",
  275. "Content",
  276. "from@example.com",
  277. ["to@example.com"],
  278. )
  279. message = email.message()
  280. self.assertEqual(
  281. message["Subject"].encode(),
  282. b"Long subject lines that get wrapped should contain a space continuation\n"
  283. b" character to get expected behavior in Outlook and Thunderbird",
  284. )
  285. def test_message_header_overrides(self):
  286. """
  287. Specifying dates or message-ids in the extra headers overrides the
  288. default values (#9233)
  289. """
  290. headers = {"date": "Fri, 09 Nov 2001 01:08:47 -0000", "Message-ID": "foo"}
  291. email = EmailMessage(
  292. "subject",
  293. "content",
  294. "from@example.com",
  295. ["to@example.com"],
  296. headers=headers,
  297. )
  298. self.assertMessageHasHeaders(
  299. email.message(),
  300. {
  301. ("Content-Transfer-Encoding", "7bit"),
  302. ("Content-Type", 'text/plain; charset="utf-8"'),
  303. ("From", "from@example.com"),
  304. ("MIME-Version", "1.0"),
  305. ("Message-ID", "foo"),
  306. ("Subject", "subject"),
  307. ("To", "to@example.com"),
  308. ("date", "Fri, 09 Nov 2001 01:08:47 -0000"),
  309. },
  310. )
  311. def test_from_header(self):
  312. """
  313. Make sure we can manually set the From header (#9214)
  314. """
  315. email = EmailMessage(
  316. "Subject",
  317. "Content",
  318. "bounce@example.com",
  319. ["to@example.com"],
  320. headers={"From": "from@example.com"},
  321. )
  322. message = email.message()
  323. self.assertEqual(message["From"], "from@example.com")
  324. def test_to_header(self):
  325. """
  326. Make sure we can manually set the To header (#17444)
  327. """
  328. email = EmailMessage(
  329. "Subject",
  330. "Content",
  331. "bounce@example.com",
  332. ["list-subscriber@example.com", "list-subscriber2@example.com"],
  333. headers={"To": "mailing-list@example.com"},
  334. )
  335. message = email.message()
  336. self.assertEqual(message["To"], "mailing-list@example.com")
  337. self.assertEqual(
  338. email.to, ["list-subscriber@example.com", "list-subscriber2@example.com"]
  339. )
  340. # If we don't set the To header manually, it should default to the `to`
  341. # argument to the constructor.
  342. email = EmailMessage(
  343. "Subject",
  344. "Content",
  345. "bounce@example.com",
  346. ["list-subscriber@example.com", "list-subscriber2@example.com"],
  347. )
  348. message = email.message()
  349. self.assertEqual(
  350. message["To"], "list-subscriber@example.com, list-subscriber2@example.com"
  351. )
  352. self.assertEqual(
  353. email.to, ["list-subscriber@example.com", "list-subscriber2@example.com"]
  354. )
  355. def test_to_in_headers_only(self):
  356. message = EmailMessage(
  357. "Subject",
  358. "Content",
  359. "bounce@example.com",
  360. headers={"To": "to@example.com"},
  361. ).message()
  362. self.assertEqual(message["To"], "to@example.com")
  363. def test_reply_to_header(self):
  364. """
  365. Specifying 'Reply-To' in headers should override reply_to.
  366. """
  367. email = EmailMessage(
  368. "Subject",
  369. "Content",
  370. "bounce@example.com",
  371. ["to@example.com"],
  372. reply_to=["foo@example.com"],
  373. headers={"Reply-To": "override@example.com"},
  374. )
  375. message = email.message()
  376. self.assertEqual(message["Reply-To"], "override@example.com")
  377. def test_reply_to_in_headers_only(self):
  378. message = EmailMessage(
  379. "Subject",
  380. "Content",
  381. "from@example.com",
  382. ["to@example.com"],
  383. headers={"Reply-To": "reply_to@example.com"},
  384. ).message()
  385. self.assertEqual(message["Reply-To"], "reply_to@example.com")
  386. def test_multiple_message_call(self):
  387. """
  388. Regression for #13259 - Make sure that headers are not changed when
  389. calling EmailMessage.message()
  390. """
  391. email = EmailMessage(
  392. "Subject",
  393. "Content",
  394. "bounce@example.com",
  395. ["to@example.com"],
  396. headers={"From": "from@example.com"},
  397. )
  398. message = email.message()
  399. self.assertEqual(message["From"], "from@example.com")
  400. message = email.message()
  401. self.assertEqual(message["From"], "from@example.com")
  402. def test_unicode_address_header(self):
  403. """
  404. Regression for #11144 - When a to/from/cc header contains Unicode,
  405. make sure the email addresses are parsed correctly (especially with
  406. regards to commas)
  407. """
  408. email = EmailMessage(
  409. "Subject",
  410. "Content",
  411. "from@example.com",
  412. ['"Firstname Sürname" <to@example.com>', "other@example.com"],
  413. )
  414. self.assertEqual(
  415. email.message()["To"],
  416. "=?utf-8?q?Firstname_S=C3=BCrname?= <to@example.com>, other@example.com",
  417. )
  418. email = EmailMessage(
  419. "Subject",
  420. "Content",
  421. "from@example.com",
  422. ['"Sürname, Firstname" <to@example.com>', "other@example.com"],
  423. )
  424. self.assertEqual(
  425. email.message()["To"],
  426. "=?utf-8?q?S=C3=BCrname=2C_Firstname?= <to@example.com>, other@example.com",
  427. )
  428. def test_unicode_headers(self):
  429. email = EmailMessage(
  430. "Gżegżółka",
  431. "Content",
  432. "from@example.com",
  433. ["to@example.com"],
  434. headers={
  435. "Sender": '"Firstname Sürname" <sender@example.com>',
  436. "Comments": "My Sürname is non-ASCII",
  437. },
  438. )
  439. message = email.message()
  440. self.assertEqual(message["Subject"], "=?utf-8?b?R8W8ZWfFvMOzxYJrYQ==?=")
  441. self.assertEqual(
  442. message["Sender"], "=?utf-8?q?Firstname_S=C3=BCrname?= <sender@example.com>"
  443. )
  444. self.assertEqual(
  445. message["Comments"], "=?utf-8?q?My_S=C3=BCrname_is_non-ASCII?="
  446. )
  447. def test_safe_mime_multipart(self):
  448. """
  449. Make sure headers can be set with a different encoding than utf-8 in
  450. SafeMIMEMultipart as well
  451. """
  452. headers = {"Date": "Fri, 09 Nov 2001 01:08:47 -0000", "Message-ID": "foo"}
  453. from_email, to = "from@example.com", '"Sürname, Firstname" <to@example.com>'
  454. text_content = "This is an important message."
  455. html_content = "<p>This is an <strong>important</strong> message.</p>"
  456. msg = EmailMultiAlternatives(
  457. "Message from Firstname Sürname",
  458. text_content,
  459. from_email,
  460. [to],
  461. headers=headers,
  462. )
  463. msg.attach_alternative(html_content, "text/html")
  464. msg.encoding = "iso-8859-1"
  465. self.assertEqual(
  466. msg.message()["To"],
  467. "=?iso-8859-1?q?S=FCrname=2C_Firstname?= <to@example.com>",
  468. )
  469. self.assertEqual(
  470. msg.message()["Subject"],
  471. "=?iso-8859-1?q?Message_from_Firstname_S=FCrname?=",
  472. )
  473. def test_safe_mime_multipart_with_attachments(self):
  474. """
  475. EmailMultiAlternatives includes alternatives if the body is empty and
  476. it has attachments.
  477. """
  478. msg = EmailMultiAlternatives(body="")
  479. html_content = "<p>This is <strong>html</strong></p>"
  480. msg.attach_alternative(html_content, "text/html")
  481. msg.attach("example.txt", "Text file content", "text/plain")
  482. self.assertIn(html_content, msg.message().as_string())
  483. def test_none_body(self):
  484. msg = EmailMessage("subject", None, "from@example.com", ["to@example.com"])
  485. self.assertEqual(msg.body, "")
  486. self.assertEqual(msg.message().get_payload(), "")
  487. @mock.patch("socket.getfqdn", return_value="漢字")
  488. def test_non_ascii_dns_non_unicode_email(self, mocked_getfqdn):
  489. delattr(DNS_NAME, "_fqdn")
  490. email = EmailMessage(
  491. "subject", "content", "from@example.com", ["to@example.com"]
  492. )
  493. email.encoding = "iso-8859-1"
  494. self.assertIn("@xn--p8s937b>", email.message()["Message-ID"])
  495. def test_encoding(self):
  496. """
  497. Regression for #12791 - Encode body correctly with other encodings
  498. than utf-8
  499. """
  500. email = EmailMessage(
  501. "Subject",
  502. "Firstname Sürname is a great guy.",
  503. "from@example.com",
  504. ["other@example.com"],
  505. )
  506. email.encoding = "iso-8859-1"
  507. message = email.message()
  508. self.assertMessageHasHeaders(
  509. message,
  510. {
  511. ("MIME-Version", "1.0"),
  512. ("Content-Type", 'text/plain; charset="iso-8859-1"'),
  513. ("Content-Transfer-Encoding", "quoted-printable"),
  514. ("Subject", "Subject"),
  515. ("From", "from@example.com"),
  516. ("To", "other@example.com"),
  517. },
  518. )
  519. self.assertEqual(message.get_payload(), "Firstname S=FCrname is a great guy.")
  520. # MIME attachments works correctly with other encodings than utf-8.
  521. text_content = "Firstname Sürname is a great guy."
  522. html_content = "<p>Firstname Sürname is a <strong>great</strong> guy.</p>"
  523. msg = EmailMultiAlternatives(
  524. "Subject", text_content, "from@example.com", ["to@example.com"]
  525. )
  526. msg.encoding = "iso-8859-1"
  527. msg.attach_alternative(html_content, "text/html")
  528. payload0 = msg.message().get_payload(0)
  529. self.assertMessageHasHeaders(
  530. payload0,
  531. {
  532. ("MIME-Version", "1.0"),
  533. ("Content-Type", 'text/plain; charset="iso-8859-1"'),
  534. ("Content-Transfer-Encoding", "quoted-printable"),
  535. },
  536. )
  537. self.assertTrue(
  538. payload0.as_bytes().endswith(b"\n\nFirstname S=FCrname is a great guy.")
  539. )
  540. payload1 = msg.message().get_payload(1)
  541. self.assertMessageHasHeaders(
  542. payload1,
  543. {
  544. ("MIME-Version", "1.0"),
  545. ("Content-Type", 'text/html; charset="iso-8859-1"'),
  546. ("Content-Transfer-Encoding", "quoted-printable"),
  547. },
  548. )
  549. self.assertTrue(
  550. payload1.as_bytes().endswith(
  551. b"\n\n<p>Firstname S=FCrname is a <strong>great</strong> guy.</p>"
  552. )
  553. )
  554. def test_attachments(self):
  555. """Regression test for #9367"""
  556. headers = {"Date": "Fri, 09 Nov 2001 01:08:47 -0000", "Message-ID": "foo"}
  557. subject, from_email, to = "hello", "from@example.com", "to@example.com"
  558. text_content = "This is an important message."
  559. html_content = "<p>This is an <strong>important</strong> message.</p>"
  560. msg = EmailMultiAlternatives(
  561. subject, text_content, from_email, [to], headers=headers
  562. )
  563. msg.attach_alternative(html_content, "text/html")
  564. msg.attach("an attachment.pdf", b"%PDF-1.4.%...", mimetype="application/pdf")
  565. msg_bytes = msg.message().as_bytes()
  566. message = message_from_bytes(msg_bytes)
  567. self.assertTrue(message.is_multipart())
  568. self.assertEqual(message.get_content_type(), "multipart/mixed")
  569. self.assertEqual(message.get_default_type(), "text/plain")
  570. payload = message.get_payload()
  571. self.assertEqual(payload[0].get_content_type(), "multipart/alternative")
  572. self.assertEqual(payload[1].get_content_type(), "application/pdf")
  573. def test_attachments_two_tuple(self):
  574. msg = EmailMessage(attachments=[("filename1", "content1")])
  575. filename, content, mimetype = self.get_decoded_attachments(msg)[0]
  576. self.assertEqual(filename, "filename1")
  577. self.assertEqual(content, b"content1")
  578. self.assertEqual(mimetype, "application/octet-stream")
  579. def test_attachments_MIMEText(self):
  580. txt = MIMEText("content1")
  581. msg = EmailMessage(attachments=[txt])
  582. payload = msg.message().get_payload()
  583. self.assertEqual(payload[0], txt)
  584. def test_non_ascii_attachment_filename(self):
  585. """Regression test for #14964"""
  586. headers = {"Date": "Fri, 09 Nov 2001 01:08:47 -0000", "Message-ID": "foo"}
  587. subject, from_email, to = "hello", "from@example.com", "to@example.com"
  588. content = "This is the message."
  589. msg = EmailMessage(subject, content, from_email, [to], headers=headers)
  590. # Unicode in file name
  591. msg.attach("une pièce jointe.pdf", b"%PDF-1.4.%...", mimetype="application/pdf")
  592. msg_bytes = msg.message().as_bytes()
  593. message = message_from_bytes(msg_bytes)
  594. payload = message.get_payload()
  595. self.assertEqual(payload[1].get_filename(), "une pièce jointe.pdf")
  596. def test_attach_file(self):
  597. """
  598. Test attaching a file against different mimetypes and make sure that
  599. a file will be attached and sent properly even if an invalid mimetype
  600. is specified.
  601. """
  602. files = (
  603. # filename, actual mimetype
  604. ("file.txt", "text/plain"),
  605. ("file.png", "image/png"),
  606. ("file_txt", None),
  607. ("file_png", None),
  608. ("file_txt.png", "image/png"),
  609. ("file_png.txt", "text/plain"),
  610. ("file.eml", "message/rfc822"),
  611. )
  612. test_mimetypes = ["text/plain", "image/png", None]
  613. for basename, real_mimetype in files:
  614. for mimetype in test_mimetypes:
  615. email = EmailMessage(
  616. "subject", "body", "from@example.com", ["to@example.com"]
  617. )
  618. self.assertEqual(mimetypes.guess_type(basename)[0], real_mimetype)
  619. self.assertEqual(email.attachments, [])
  620. file_path = os.path.join(
  621. os.path.dirname(__file__), "attachments", basename
  622. )
  623. email.attach_file(file_path, mimetype=mimetype)
  624. self.assertEqual(len(email.attachments), 1)
  625. self.assertIn(basename, email.attachments[0])
  626. msgs_sent_num = email.send()
  627. self.assertEqual(msgs_sent_num, 1)
  628. def test_attach_text_as_bytes(self):
  629. msg = EmailMessage("subject", "body", "from@example.com", ["to@example.com"])
  630. msg.attach("file.txt", b"file content")
  631. sent_num = msg.send()
  632. self.assertEqual(sent_num, 1)
  633. filename, content, mimetype = self.get_decoded_attachments(msg)[0]
  634. self.assertEqual(filename, "file.txt")
  635. self.assertEqual(content, b"file content")
  636. self.assertEqual(mimetype, "text/plain")
  637. def test_attach_utf8_text_as_bytes(self):
  638. """
  639. Non-ASCII characters encoded as valid UTF-8 are correctly transported
  640. and decoded.
  641. """
  642. msg = EmailMessage("subject", "body", "from@example.com", ["to@example.com"])
  643. msg.attach("file.txt", b"\xc3\xa4") # UTF-8 encoded a umlaut.
  644. filename, content, mimetype = self.get_decoded_attachments(msg)[0]
  645. self.assertEqual(filename, "file.txt")
  646. self.assertEqual(content, b"\xc3\xa4")
  647. self.assertEqual(mimetype, "text/plain")
  648. def test_attach_non_utf8_text_as_bytes(self):
  649. """
  650. Binary data that can't be decoded as UTF-8 overrides the MIME type
  651. instead of decoding the data.
  652. """
  653. msg = EmailMessage("subject", "body", "from@example.com", ["to@example.com"])
  654. msg.attach("file.txt", b"\xff") # Invalid UTF-8.
  655. filename, content, mimetype = self.get_decoded_attachments(msg)[0]
  656. self.assertEqual(filename, "file.txt")
  657. # Content should be passed through unmodified.
  658. self.assertEqual(content, b"\xff")
  659. self.assertEqual(mimetype, "application/octet-stream")
  660. def test_attach_mimetext_content_mimetype(self):
  661. email_msg = EmailMessage()
  662. txt = MIMEText("content")
  663. msg = (
  664. "content and mimetype must not be given when a MIMEBase instance "
  665. "is provided."
  666. )
  667. with self.assertRaisesMessage(ValueError, msg):
  668. email_msg.attach(txt, content="content")
  669. with self.assertRaisesMessage(ValueError, msg):
  670. email_msg.attach(txt, mimetype="text/plain")
  671. def test_attach_content_none(self):
  672. email_msg = EmailMessage()
  673. msg = "content must be provided."
  674. with self.assertRaisesMessage(ValueError, msg):
  675. email_msg.attach("file.txt", mimetype="application/pdf")
  676. def test_dummy_backend(self):
  677. """
  678. Make sure that dummy backends returns correct number of sent messages
  679. """
  680. connection = dummy.EmailBackend()
  681. email = EmailMessage(
  682. "Subject",
  683. "Content",
  684. "bounce@example.com",
  685. ["to@example.com"],
  686. headers={"From": "from@example.com"},
  687. )
  688. self.assertEqual(connection.send_messages([email, email, email]), 3)
  689. def test_arbitrary_keyword(self):
  690. """
  691. Make sure that get_connection() accepts arbitrary keyword that might be
  692. used with custom backends.
  693. """
  694. c = mail.get_connection(fail_silently=True, foo="bar")
  695. self.assertTrue(c.fail_silently)
  696. def test_custom_backend(self):
  697. """Test custom backend defined in this suite."""
  698. conn = mail.get_connection("mail.custombackend.EmailBackend")
  699. self.assertTrue(hasattr(conn, "test_outbox"))
  700. email = EmailMessage(
  701. "Subject",
  702. "Content",
  703. "bounce@example.com",
  704. ["to@example.com"],
  705. headers={"From": "from@example.com"},
  706. )
  707. conn.send_messages([email])
  708. self.assertEqual(len(conn.test_outbox), 1)
  709. def test_backend_arg(self):
  710. """Test backend argument of mail.get_connection()"""
  711. self.assertIsInstance(
  712. mail.get_connection("django.core.mail.backends.smtp.EmailBackend"),
  713. smtp.EmailBackend,
  714. )
  715. self.assertIsInstance(
  716. mail.get_connection("django.core.mail.backends.locmem.EmailBackend"),
  717. locmem.EmailBackend,
  718. )
  719. self.assertIsInstance(
  720. mail.get_connection("django.core.mail.backends.dummy.EmailBackend"),
  721. dummy.EmailBackend,
  722. )
  723. self.assertIsInstance(
  724. mail.get_connection("django.core.mail.backends.console.EmailBackend"),
  725. console.EmailBackend,
  726. )
  727. with tempfile.TemporaryDirectory() as tmp_dir:
  728. self.assertIsInstance(
  729. mail.get_connection(
  730. "django.core.mail.backends.filebased.EmailBackend",
  731. file_path=tmp_dir,
  732. ),
  733. filebased.EmailBackend,
  734. )
  735. if sys.platform == "win32" and not PY311:
  736. msg = (
  737. "_getfullpathname: path should be string, bytes or os.PathLike, not "
  738. "object"
  739. )
  740. else:
  741. msg = "expected str, bytes or os.PathLike object, not object"
  742. with self.assertRaisesMessage(TypeError, msg):
  743. mail.get_connection(
  744. "django.core.mail.backends.filebased.EmailBackend", file_path=object()
  745. )
  746. self.assertIsInstance(mail.get_connection(), locmem.EmailBackend)
  747. @override_settings(
  748. EMAIL_BACKEND="django.core.mail.backends.locmem.EmailBackend",
  749. ADMINS=[("nobody", "nobody@example.com")],
  750. MANAGERS=[("nobody", "nobody@example.com")],
  751. )
  752. def test_connection_arg(self):
  753. """Test connection argument to send_mail(), et. al."""
  754. mail.outbox = []
  755. # Send using non-default connection
  756. connection = mail.get_connection("mail.custombackend.EmailBackend")
  757. send_mail(
  758. "Subject",
  759. "Content",
  760. "from@example.com",
  761. ["to@example.com"],
  762. connection=connection,
  763. )
  764. self.assertEqual(mail.outbox, [])
  765. self.assertEqual(len(connection.test_outbox), 1)
  766. self.assertEqual(connection.test_outbox[0].subject, "Subject")
  767. connection = mail.get_connection("mail.custombackend.EmailBackend")
  768. send_mass_mail(
  769. [
  770. ("Subject1", "Content1", "from1@example.com", ["to1@example.com"]),
  771. ("Subject2", "Content2", "from2@example.com", ["to2@example.com"]),
  772. ],
  773. connection=connection,
  774. )
  775. self.assertEqual(mail.outbox, [])
  776. self.assertEqual(len(connection.test_outbox), 2)
  777. self.assertEqual(connection.test_outbox[0].subject, "Subject1")
  778. self.assertEqual(connection.test_outbox[1].subject, "Subject2")
  779. connection = mail.get_connection("mail.custombackend.EmailBackend")
  780. mail_admins("Admin message", "Content", connection=connection)
  781. self.assertEqual(mail.outbox, [])
  782. self.assertEqual(len(connection.test_outbox), 1)
  783. self.assertEqual(connection.test_outbox[0].subject, "[Django] Admin message")
  784. connection = mail.get_connection("mail.custombackend.EmailBackend")
  785. mail_managers("Manager message", "Content", connection=connection)
  786. self.assertEqual(mail.outbox, [])
  787. self.assertEqual(len(connection.test_outbox), 1)
  788. self.assertEqual(connection.test_outbox[0].subject, "[Django] Manager message")
  789. def test_dont_mangle_from_in_body(self):
  790. # Regression for #13433 - Make sure that EmailMessage doesn't mangle
  791. # 'From ' in message body.
  792. email = EmailMessage(
  793. "Subject",
  794. "From the future",
  795. "bounce@example.com",
  796. ["to@example.com"],
  797. headers={"From": "from@example.com"},
  798. )
  799. self.assertNotIn(b">From the future", email.message().as_bytes())
  800. def test_dont_base64_encode(self):
  801. # Ticket #3472
  802. # Shouldn't use Base64 encoding at all
  803. msg = EmailMessage(
  804. "Subject",
  805. "UTF-8 encoded body",
  806. "bounce@example.com",
  807. ["to@example.com"],
  808. headers={"From": "from@example.com"},
  809. )
  810. self.assertIn(b"Content-Transfer-Encoding: 7bit", msg.message().as_bytes())
  811. # Ticket #11212
  812. # Shouldn't use quoted printable, should detect it can represent
  813. # content with 7 bit data.
  814. msg = EmailMessage(
  815. "Subject",
  816. "Body with only ASCII characters.",
  817. "bounce@example.com",
  818. ["to@example.com"],
  819. headers={"From": "from@example.com"},
  820. )
  821. s = msg.message().as_bytes()
  822. self.assertIn(b"Content-Transfer-Encoding: 7bit", s)
  823. # Shouldn't use quoted printable, should detect it can represent
  824. # content with 8 bit data.
  825. msg = EmailMessage(
  826. "Subject",
  827. "Body with latin characters: àáä.",
  828. "bounce@example.com",
  829. ["to@example.com"],
  830. headers={"From": "from@example.com"},
  831. )
  832. s = msg.message().as_bytes()
  833. self.assertIn(b"Content-Transfer-Encoding: 8bit", s)
  834. s = msg.message().as_string()
  835. self.assertIn("Content-Transfer-Encoding: 8bit", s)
  836. msg = EmailMessage(
  837. "Subject",
  838. "Body with non latin characters: А Б В Г Д Е Ж Ѕ З И І К Л М Н О П.",
  839. "bounce@example.com",
  840. ["to@example.com"],
  841. headers={"From": "from@example.com"},
  842. )
  843. s = msg.message().as_bytes()
  844. self.assertIn(b"Content-Transfer-Encoding: 8bit", s)
  845. s = msg.message().as_string()
  846. self.assertIn("Content-Transfer-Encoding: 8bit", s)
  847. def test_dont_base64_encode_message_rfc822(self):
  848. # Ticket #18967
  849. # Shouldn't use base64 encoding for a child EmailMessage attachment.
  850. # Create a child message first
  851. child_msg = EmailMessage(
  852. "Child Subject",
  853. "Some body of child message",
  854. "bounce@example.com",
  855. ["to@example.com"],
  856. headers={"From": "from@example.com"},
  857. )
  858. child_s = child_msg.message().as_string()
  859. # Now create a parent
  860. parent_msg = EmailMessage(
  861. "Parent Subject",
  862. "Some parent body",
  863. "bounce@example.com",
  864. ["to@example.com"],
  865. headers={"From": "from@example.com"},
  866. )
  867. # Attach to parent as a string
  868. parent_msg.attach(content=child_s, mimetype="message/rfc822")
  869. parent_s = parent_msg.message().as_string()
  870. # The child message header is not base64 encoded
  871. self.assertIn("Child Subject", parent_s)
  872. # Feature test: try attaching email.Message object directly to the mail.
  873. parent_msg = EmailMessage(
  874. "Parent Subject",
  875. "Some parent body",
  876. "bounce@example.com",
  877. ["to@example.com"],
  878. headers={"From": "from@example.com"},
  879. )
  880. parent_msg.attach(content=child_msg.message(), mimetype="message/rfc822")
  881. parent_s = parent_msg.message().as_string()
  882. # The child message header is not base64 encoded
  883. self.assertIn("Child Subject", parent_s)
  884. # Feature test: try attaching Django's EmailMessage object directly to the mail.
  885. parent_msg = EmailMessage(
  886. "Parent Subject",
  887. "Some parent body",
  888. "bounce@example.com",
  889. ["to@example.com"],
  890. headers={"From": "from@example.com"},
  891. )
  892. parent_msg.attach(content=child_msg, mimetype="message/rfc822")
  893. parent_s = parent_msg.message().as_string()
  894. # The child message header is not base64 encoded
  895. self.assertIn("Child Subject", parent_s)
  896. def test_custom_utf8_encoding(self):
  897. """A UTF-8 charset with a custom body encoding is respected."""
  898. body = "Body with latin characters: àáä."
  899. msg = EmailMessage("Subject", body, "bounce@example.com", ["to@example.com"])
  900. encoding = charset.Charset("utf-8")
  901. encoding.body_encoding = charset.QP
  902. msg.encoding = encoding
  903. message = msg.message()
  904. self.assertMessageHasHeaders(
  905. message,
  906. {
  907. ("MIME-Version", "1.0"),
  908. ("Content-Type", 'text/plain; charset="utf-8"'),
  909. ("Content-Transfer-Encoding", "quoted-printable"),
  910. },
  911. )
  912. self.assertEqual(message.get_payload(), encoding.body_encode(body))
  913. def test_sanitize_address(self):
  914. """Email addresses are properly sanitized."""
  915. for email_address, encoding, expected_result in (
  916. # ASCII addresses.
  917. ("to@example.com", "ascii", "to@example.com"),
  918. ("to@example.com", "utf-8", "to@example.com"),
  919. (("A name", "to@example.com"), "ascii", "A name <to@example.com>"),
  920. (
  921. ("A name", "to@example.com"),
  922. "utf-8",
  923. "A name <to@example.com>",
  924. ),
  925. ("localpartonly", "ascii", "localpartonly"),
  926. # ASCII addresses with display names.
  927. ("A name <to@example.com>", "ascii", "A name <to@example.com>"),
  928. ("A name <to@example.com>", "utf-8", "A name <to@example.com>"),
  929. ('"A name" <to@example.com>', "ascii", "A name <to@example.com>"),
  930. ('"A name" <to@example.com>', "utf-8", "A name <to@example.com>"),
  931. # Unicode addresses (supported per RFC-6532).
  932. ("tó@example.com", "utf-8", "=?utf-8?b?dMOz?=@example.com"),
  933. ("to@éxample.com", "utf-8", "to@xn--xample-9ua.com"),
  934. (
  935. ("Tó Example", "tó@example.com"),
  936. "utf-8",
  937. "=?utf-8?q?T=C3=B3_Example?= <=?utf-8?b?dMOz?=@example.com>",
  938. ),
  939. # Unicode addresses with display names.
  940. (
  941. "Tó Example <tó@example.com>",
  942. "utf-8",
  943. "=?utf-8?q?T=C3=B3_Example?= <=?utf-8?b?dMOz?=@example.com>",
  944. ),
  945. (
  946. "To Example <to@éxample.com>",
  947. "ascii",
  948. "To Example <to@xn--xample-9ua.com>",
  949. ),
  950. (
  951. "To Example <to@éxample.com>",
  952. "utf-8",
  953. "To Example <to@xn--xample-9ua.com>",
  954. ),
  955. # Addresses with two @ signs.
  956. ('"to@other.com"@example.com', "utf-8", r'"to@other.com"@example.com'),
  957. (
  958. '"to@other.com" <to@example.com>',
  959. "utf-8",
  960. '"to@other.com" <to@example.com>',
  961. ),
  962. (
  963. ("To Example", "to@other.com@example.com"),
  964. "utf-8",
  965. 'To Example <"to@other.com"@example.com>',
  966. ),
  967. # Addresses with long unicode display names.
  968. (
  969. "Tó Example very long" * 4 + " <to@example.com>",
  970. "utf-8",
  971. "=?utf-8?q?T=C3=B3_Example_very_longT=C3=B3_Example_very_longT"
  972. "=C3=B3_Example_?=\n"
  973. " =?utf-8?q?very_longT=C3=B3_Example_very_long?= "
  974. "<to@example.com>",
  975. ),
  976. (
  977. ("Tó Example very long" * 4, "to@example.com"),
  978. "utf-8",
  979. "=?utf-8?q?T=C3=B3_Example_very_longT=C3=B3_Example_very_longT"
  980. "=C3=B3_Example_?=\n"
  981. " =?utf-8?q?very_longT=C3=B3_Example_very_long?= "
  982. "<to@example.com>",
  983. ),
  984. # Address with long display name and unicode domain.
  985. (
  986. ("To Example very long" * 4, "to@exampl€.com"),
  987. "utf-8",
  988. "To Example very longTo Example very longTo Example very longT"
  989. "o Example very\n"
  990. " long <to@xn--exampl-nc1c.com>",
  991. ),
  992. ):
  993. with self.subTest(email_address=email_address, encoding=encoding):
  994. self.assertEqual(
  995. sanitize_address(email_address, encoding), expected_result
  996. )
  997. def test_sanitize_address_invalid(self):
  998. for email_address in (
  999. # Invalid address with two @ signs.
  1000. "to@other.com@example.com",
  1001. # Invalid address without the quotes.
  1002. "to@other.com <to@example.com>",
  1003. # Other invalid addresses.
  1004. "@",
  1005. "to@",
  1006. "@example.com",
  1007. ):
  1008. with self.subTest(email_address=email_address):
  1009. with self.assertRaises(ValueError):
  1010. sanitize_address(email_address, encoding="utf-8")
  1011. def test_sanitize_address_header_injection(self):
  1012. msg = "Invalid address; address parts cannot contain newlines."
  1013. tests = [
  1014. "Name\nInjection <to@example.com>",
  1015. ("Name\nInjection", "to@xample.com"),
  1016. "Name <to\ninjection@example.com>",
  1017. ("Name", "to\ninjection@example.com"),
  1018. ]
  1019. for email_address in tests:
  1020. with self.subTest(email_address=email_address):
  1021. with self.assertRaisesMessage(ValueError, msg):
  1022. sanitize_address(email_address, encoding="utf-8")
  1023. def test_email_multi_alternatives_content_mimetype_none(self):
  1024. email_msg = EmailMultiAlternatives()
  1025. msg = "Both content and mimetype must be provided."
  1026. with self.assertRaisesMessage(ValueError, msg):
  1027. email_msg.attach_alternative(None, "text/html")
  1028. with self.assertRaisesMessage(ValueError, msg):
  1029. email_msg.attach_alternative("<p>content</p>", None)
  1030. @requires_tz_support
  1031. class MailTimeZoneTests(SimpleTestCase):
  1032. @override_settings(
  1033. EMAIL_USE_LOCALTIME=False, USE_TZ=True, TIME_ZONE="Africa/Algiers"
  1034. )
  1035. def test_date_header_utc(self):
  1036. """
  1037. EMAIL_USE_LOCALTIME=False creates a datetime in UTC.
  1038. """
  1039. email = EmailMessage(
  1040. "Subject", "Body", "bounce@example.com", ["to@example.com"]
  1041. )
  1042. self.assertTrue(email.message()["Date"].endswith("-0000"))
  1043. @override_settings(
  1044. EMAIL_USE_LOCALTIME=True, USE_TZ=True, TIME_ZONE="Africa/Algiers"
  1045. )
  1046. def test_date_header_localtime(self):
  1047. """
  1048. EMAIL_USE_LOCALTIME=True creates a datetime in the local time zone.
  1049. """
  1050. email = EmailMessage(
  1051. "Subject", "Body", "bounce@example.com", ["to@example.com"]
  1052. )
  1053. self.assertTrue(
  1054. email.message()["Date"].endswith("+0100")
  1055. ) # Africa/Algiers is UTC+1
  1056. class PythonGlobalState(SimpleTestCase):
  1057. """
  1058. Tests for #12422 -- Django smarts (#2472/#11212) with charset of utf-8 text
  1059. parts shouldn't pollute global email Python package charset registry when
  1060. django.mail.message is imported.
  1061. """
  1062. def test_utf8(self):
  1063. txt = MIMEText("UTF-8 encoded body", "plain", "utf-8")
  1064. self.assertIn("Content-Transfer-Encoding: base64", txt.as_string())
  1065. def test_7bit(self):
  1066. txt = MIMEText("Body with only ASCII characters.", "plain", "utf-8")
  1067. self.assertIn("Content-Transfer-Encoding: base64", txt.as_string())
  1068. def test_8bit_latin(self):
  1069. txt = MIMEText("Body with latin characters: àáä.", "plain", "utf-8")
  1070. self.assertIn("Content-Transfer-Encoding: base64", txt.as_string())
  1071. def test_8bit_non_latin(self):
  1072. txt = MIMEText(
  1073. "Body with non latin characters: А Б В Г Д Е Ж Ѕ З И І К Л М Н О П.",
  1074. "plain",
  1075. "utf-8",
  1076. )
  1077. self.assertIn("Content-Transfer-Encoding: base64", txt.as_string())
  1078. class BaseEmailBackendTests(HeadersCheckMixin):
  1079. email_backend = None
  1080. def setUp(self):
  1081. self.settings_override = override_settings(EMAIL_BACKEND=self.email_backend)
  1082. self.settings_override.enable()
  1083. def tearDown(self):
  1084. self.settings_override.disable()
  1085. def assertStartsWith(self, first, second):
  1086. if not first.startswith(second):
  1087. self.longMessage = True
  1088. self.assertEqual(
  1089. first[: len(second)],
  1090. second,
  1091. "First string doesn't start with the second.",
  1092. )
  1093. def get_mailbox_content(self):
  1094. raise NotImplementedError(
  1095. "subclasses of BaseEmailBackendTests must provide a get_mailbox_content() "
  1096. "method"
  1097. )
  1098. def flush_mailbox(self):
  1099. raise NotImplementedError(
  1100. "subclasses of BaseEmailBackendTests may require a flush_mailbox() method"
  1101. )
  1102. def get_the_message(self):
  1103. mailbox = self.get_mailbox_content()
  1104. self.assertEqual(
  1105. len(mailbox),
  1106. 1,
  1107. "Expected exactly one message, got %d.\n%r"
  1108. % (len(mailbox), [m.as_string() for m in mailbox]),
  1109. )
  1110. return mailbox[0]
  1111. def test_send(self):
  1112. email = EmailMessage(
  1113. "Subject", "Content", "from@example.com", ["to@example.com"]
  1114. )
  1115. num_sent = mail.get_connection().send_messages([email])
  1116. self.assertEqual(num_sent, 1)
  1117. message = self.get_the_message()
  1118. self.assertEqual(message["subject"], "Subject")
  1119. self.assertEqual(message.get_payload(), "Content")
  1120. self.assertEqual(message["from"], "from@example.com")
  1121. self.assertEqual(message.get_all("to"), ["to@example.com"])
  1122. def test_send_unicode(self):
  1123. email = EmailMessage(
  1124. "Chère maman", "Je t'aime très fort", "from@example.com", ["to@example.com"]
  1125. )
  1126. num_sent = mail.get_connection().send_messages([email])
  1127. self.assertEqual(num_sent, 1)
  1128. message = self.get_the_message()
  1129. self.assertEqual(message["subject"], "=?utf-8?q?Ch=C3=A8re_maman?=")
  1130. self.assertEqual(
  1131. message.get_payload(decode=True).decode(), "Je t'aime très fort"
  1132. )
  1133. def test_send_long_lines(self):
  1134. """
  1135. Email line length is limited to 998 chars by the RFC 5322 Section
  1136. 2.1.1.
  1137. Message body containing longer lines are converted to Quoted-Printable
  1138. to avoid having to insert newlines, which could be hairy to do properly.
  1139. """
  1140. # Unencoded body length is < 998 (840) but > 998 when utf-8 encoded.
  1141. email = EmailMessage(
  1142. "Subject", "В южных морях " * 60, "from@example.com", ["to@example.com"]
  1143. )
  1144. email.send()
  1145. message = self.get_the_message()
  1146. self.assertMessageHasHeaders(
  1147. message,
  1148. {
  1149. ("MIME-Version", "1.0"),
  1150. ("Content-Type", 'text/plain; charset="utf-8"'),
  1151. ("Content-Transfer-Encoding", "quoted-printable"),
  1152. },
  1153. )
  1154. def test_send_many(self):
  1155. email1 = EmailMessage(
  1156. "Subject", "Content1", "from@example.com", ["to@example.com"]
  1157. )
  1158. email2 = EmailMessage(
  1159. "Subject", "Content2", "from@example.com", ["to@example.com"]
  1160. )
  1161. # send_messages() may take a list or an iterator.
  1162. emails_lists = ([email1, email2], iter((email1, email2)))
  1163. for emails_list in emails_lists:
  1164. num_sent = mail.get_connection().send_messages(emails_list)
  1165. self.assertEqual(num_sent, 2)
  1166. messages = self.get_mailbox_content()
  1167. self.assertEqual(len(messages), 2)
  1168. self.assertEqual(messages[0].get_payload(), "Content1")
  1169. self.assertEqual(messages[1].get_payload(), "Content2")
  1170. self.flush_mailbox()
  1171. def test_send_verbose_name(self):
  1172. email = EmailMessage(
  1173. "Subject",
  1174. "Content",
  1175. '"Firstname Sürname" <from@example.com>',
  1176. ["to@example.com"],
  1177. )
  1178. email.send()
  1179. message = self.get_the_message()
  1180. self.assertEqual(message["subject"], "Subject")
  1181. self.assertEqual(message.get_payload(), "Content")
  1182. self.assertEqual(
  1183. message["from"], "=?utf-8?q?Firstname_S=C3=BCrname?= <from@example.com>"
  1184. )
  1185. def test_plaintext_send_mail(self):
  1186. """
  1187. Test send_mail without the html_message
  1188. regression test for adding html_message parameter to send_mail()
  1189. """
  1190. send_mail("Subject", "Content", "sender@example.com", ["nobody@example.com"])
  1191. message = self.get_the_message()
  1192. self.assertEqual(message.get("subject"), "Subject")
  1193. self.assertEqual(message.get_all("to"), ["nobody@example.com"])
  1194. self.assertFalse(message.is_multipart())
  1195. self.assertEqual(message.get_payload(), "Content")
  1196. self.assertEqual(message.get_content_type(), "text/plain")
  1197. def test_html_send_mail(self):
  1198. """Test html_message argument to send_mail"""
  1199. send_mail(
  1200. "Subject",
  1201. "Content",
  1202. "sender@example.com",
  1203. ["nobody@example.com"],
  1204. html_message="HTML Content",
  1205. )
  1206. message = self.get_the_message()
  1207. self.assertEqual(message.get("subject"), "Subject")
  1208. self.assertEqual(message.get_all("to"), ["nobody@example.com"])
  1209. self.assertTrue(message.is_multipart())
  1210. self.assertEqual(len(message.get_payload()), 2)
  1211. self.assertEqual(message.get_payload(0).get_payload(), "Content")
  1212. self.assertEqual(message.get_payload(0).get_content_type(), "text/plain")
  1213. self.assertEqual(message.get_payload(1).get_payload(), "HTML Content")
  1214. self.assertEqual(message.get_payload(1).get_content_type(), "text/html")
  1215. @override_settings(MANAGERS=[("nobody", "nobody@example.com")])
  1216. def test_html_mail_managers(self):
  1217. """Test html_message argument to mail_managers"""
  1218. mail_managers("Subject", "Content", html_message="HTML Content")
  1219. message = self.get_the_message()
  1220. self.assertEqual(message.get("subject"), "[Django] Subject")
  1221. self.assertEqual(message.get_all("to"), ["nobody@example.com"])
  1222. self.assertTrue(message.is_multipart())
  1223. self.assertEqual(len(message.get_payload()), 2)
  1224. self.assertEqual(message.get_payload(0).get_payload(), "Content")
  1225. self.assertEqual(message.get_payload(0).get_content_type(), "text/plain")
  1226. self.assertEqual(message.get_payload(1).get_payload(), "HTML Content")
  1227. self.assertEqual(message.get_payload(1).get_content_type(), "text/html")
  1228. @override_settings(ADMINS=[("nobody", "nobody@example.com")])
  1229. def test_html_mail_admins(self):
  1230. """Test html_message argument to mail_admins"""
  1231. mail_admins("Subject", "Content", html_message="HTML Content")
  1232. message = self.get_the_message()
  1233. self.assertEqual(message.get("subject"), "[Django] Subject")
  1234. self.assertEqual(message.get_all("to"), ["nobody@example.com"])
  1235. self.assertTrue(message.is_multipart())
  1236. self.assertEqual(len(message.get_payload()), 2)
  1237. self.assertEqual(message.get_payload(0).get_payload(), "Content")
  1238. self.assertEqual(message.get_payload(0).get_content_type(), "text/plain")
  1239. self.assertEqual(message.get_payload(1).get_payload(), "HTML Content")
  1240. self.assertEqual(message.get_payload(1).get_content_type(), "text/html")
  1241. @override_settings(
  1242. ADMINS=[("nobody", "nobody+admin@example.com")],
  1243. MANAGERS=[("nobody", "nobody+manager@example.com")],
  1244. )
  1245. def test_manager_and_admin_mail_prefix(self):
  1246. """
  1247. String prefix + lazy translated subject = bad output
  1248. Regression for #13494
  1249. """
  1250. mail_managers(gettext_lazy("Subject"), "Content")
  1251. message = self.get_the_message()
  1252. self.assertEqual(message.get("subject"), "[Django] Subject")
  1253. self.flush_mailbox()
  1254. mail_admins(gettext_lazy("Subject"), "Content")
  1255. message = self.get_the_message()
  1256. self.assertEqual(message.get("subject"), "[Django] Subject")
  1257. @override_settings(ADMINS=[], MANAGERS=[])
  1258. def test_empty_admins(self):
  1259. """
  1260. mail_admins/mail_managers doesn't connect to the mail server
  1261. if there are no recipients (#9383)
  1262. """
  1263. mail_admins("hi", "there")
  1264. self.assertEqual(self.get_mailbox_content(), [])
  1265. mail_managers("hi", "there")
  1266. self.assertEqual(self.get_mailbox_content(), [])
  1267. def test_wrong_admins_managers(self):
  1268. tests = (
  1269. "test@example.com",
  1270. ("test@example.com",),
  1271. ["test@example.com", "other@example.com"],
  1272. ("test@example.com", "other@example.com"),
  1273. )
  1274. for setting, mail_func in (
  1275. ("ADMINS", mail_admins),
  1276. ("MANAGERS", mail_managers),
  1277. ):
  1278. msg = "The %s setting must be a list of 2-tuples." % setting
  1279. for value in tests:
  1280. with self.subTest(setting=setting, value=value), self.settings(
  1281. **{setting: value}
  1282. ):
  1283. with self.assertRaisesMessage(ValueError, msg):
  1284. mail_func("subject", "content")
  1285. def test_message_cc_header(self):
  1286. """
  1287. Regression test for #7722
  1288. """
  1289. email = EmailMessage(
  1290. "Subject",
  1291. "Content",
  1292. "from@example.com",
  1293. ["to@example.com"],
  1294. cc=["cc@example.com"],
  1295. )
  1296. mail.get_connection().send_messages([email])
  1297. message = self.get_the_message()
  1298. self.assertMessageHasHeaders(
  1299. message,
  1300. {
  1301. ("MIME-Version", "1.0"),
  1302. ("Content-Type", 'text/plain; charset="utf-8"'),
  1303. ("Content-Transfer-Encoding", "7bit"),
  1304. ("Subject", "Subject"),
  1305. ("From", "from@example.com"),
  1306. ("To", "to@example.com"),
  1307. ("Cc", "cc@example.com"),
  1308. },
  1309. )
  1310. self.assertIn("\nDate: ", message.as_string())
  1311. def test_idn_send(self):
  1312. """
  1313. Regression test for #14301
  1314. """
  1315. self.assertTrue(send_mail("Subject", "Content", "from@öäü.com", ["to@öäü.com"]))
  1316. message = self.get_the_message()
  1317. self.assertEqual(message.get("subject"), "Subject")
  1318. self.assertEqual(message.get("from"), "from@xn--4ca9at.com")
  1319. self.assertEqual(message.get("to"), "to@xn--4ca9at.com")
  1320. self.flush_mailbox()
  1321. m = EmailMessage(
  1322. "Subject", "Content", "from@öäü.com", ["to@öäü.com"], cc=["cc@öäü.com"]
  1323. )
  1324. m.send()
  1325. message = self.get_the_message()
  1326. self.assertEqual(message.get("subject"), "Subject")
  1327. self.assertEqual(message.get("from"), "from@xn--4ca9at.com")
  1328. self.assertEqual(message.get("to"), "to@xn--4ca9at.com")
  1329. self.assertEqual(message.get("cc"), "cc@xn--4ca9at.com")
  1330. def test_recipient_without_domain(self):
  1331. """
  1332. Regression test for #15042
  1333. """
  1334. self.assertTrue(send_mail("Subject", "Content", "tester", ["django"]))
  1335. message = self.get_the_message()
  1336. self.assertEqual(message.get("subject"), "Subject")
  1337. self.assertEqual(message.get("from"), "tester")
  1338. self.assertEqual(message.get("to"), "django")
  1339. def test_lazy_addresses(self):
  1340. """
  1341. Email sending should support lazy email addresses (#24416).
  1342. """
  1343. _ = gettext_lazy
  1344. self.assertTrue(send_mail("Subject", "Content", _("tester"), [_("django")]))
  1345. message = self.get_the_message()
  1346. self.assertEqual(message.get("from"), "tester")
  1347. self.assertEqual(message.get("to"), "django")
  1348. self.flush_mailbox()
  1349. m = EmailMessage(
  1350. "Subject",
  1351. "Content",
  1352. _("tester"),
  1353. [_("to1"), _("to2")],
  1354. cc=[_("cc1"), _("cc2")],
  1355. bcc=[_("bcc")],
  1356. reply_to=[_("reply")],
  1357. )
  1358. self.assertEqual(m.recipients(), ["to1", "to2", "cc1", "cc2", "bcc"])
  1359. m.send()
  1360. message = self.get_the_message()
  1361. self.assertEqual(message.get("from"), "tester")
  1362. self.assertEqual(message.get("to"), "to1, to2")
  1363. self.assertEqual(message.get("cc"), "cc1, cc2")
  1364. self.assertEqual(message.get("Reply-To"), "reply")
  1365. def test_close_connection(self):
  1366. """
  1367. Connection can be closed (even when not explicitly opened)
  1368. """
  1369. conn = mail.get_connection(username="", password="")
  1370. conn.close()
  1371. def test_use_as_contextmanager(self):
  1372. """
  1373. The connection can be used as a contextmanager.
  1374. """
  1375. opened = [False]
  1376. closed = [False]
  1377. conn = mail.get_connection(username="", password="")
  1378. def open():
  1379. opened[0] = True
  1380. conn.open = open
  1381. def close():
  1382. closed[0] = True
  1383. conn.close = close
  1384. with conn as same_conn:
  1385. self.assertTrue(opened[0])
  1386. self.assertIs(same_conn, conn)
  1387. self.assertFalse(closed[0])
  1388. self.assertTrue(closed[0])
  1389. class LocmemBackendTests(BaseEmailBackendTests, SimpleTestCase):
  1390. email_backend = "django.core.mail.backends.locmem.EmailBackend"
  1391. def get_mailbox_content(self):
  1392. return [m.message() for m in mail.outbox]
  1393. def flush_mailbox(self):
  1394. mail.outbox = []
  1395. def tearDown(self):
  1396. super().tearDown()
  1397. mail.outbox = []
  1398. def test_locmem_shared_messages(self):
  1399. """
  1400. Make sure that the locmen backend populates the outbox.
  1401. """
  1402. connection = locmem.EmailBackend()
  1403. connection2 = locmem.EmailBackend()
  1404. email = EmailMessage(
  1405. "Subject",
  1406. "Content",
  1407. "bounce@example.com",
  1408. ["to@example.com"],
  1409. headers={"From": "from@example.com"},
  1410. )
  1411. connection.send_messages([email])
  1412. connection2.send_messages([email])
  1413. self.assertEqual(len(mail.outbox), 2)
  1414. def test_validate_multiline_headers(self):
  1415. # Ticket #18861 - Validate emails when using the locmem backend
  1416. with self.assertRaises(BadHeaderError):
  1417. send_mail(
  1418. "Subject\nMultiline", "Content", "from@example.com", ["to@example.com"]
  1419. )
  1420. class FileBackendTests(BaseEmailBackendTests, SimpleTestCase):
  1421. email_backend = "django.core.mail.backends.filebased.EmailBackend"
  1422. def setUp(self):
  1423. super().setUp()
  1424. self.tmp_dir = self.mkdtemp()
  1425. self.addCleanup(shutil.rmtree, self.tmp_dir)
  1426. self._settings_override = override_settings(EMAIL_FILE_PATH=self.tmp_dir)
  1427. self._settings_override.enable()
  1428. def tearDown(self):
  1429. self._settings_override.disable()
  1430. super().tearDown()
  1431. def mkdtemp(self):
  1432. return tempfile.mkdtemp()
  1433. def flush_mailbox(self):
  1434. for filename in os.listdir(self.tmp_dir):
  1435. os.unlink(os.path.join(self.tmp_dir, filename))
  1436. def get_mailbox_content(self):
  1437. messages = []
  1438. for filename in os.listdir(self.tmp_dir):
  1439. with open(os.path.join(self.tmp_dir, filename), "rb") as fp:
  1440. session = fp.read().split(b"\n" + (b"-" * 79) + b"\n")
  1441. messages.extend(message_from_bytes(m) for m in session if m)
  1442. return messages
  1443. def test_file_sessions(self):
  1444. """Make sure opening a connection creates a new file"""
  1445. msg = EmailMessage(
  1446. "Subject",
  1447. "Content",
  1448. "bounce@example.com",
  1449. ["to@example.com"],
  1450. headers={"From": "from@example.com"},
  1451. )
  1452. connection = mail.get_connection()
  1453. connection.send_messages([msg])
  1454. self.assertEqual(len(os.listdir(self.tmp_dir)), 1)
  1455. with open(os.path.join(self.tmp_dir, os.listdir(self.tmp_dir)[0]), "rb") as fp:
  1456. message = message_from_binary_file(fp)
  1457. self.assertEqual(message.get_content_type(), "text/plain")
  1458. self.assertEqual(message.get("subject"), "Subject")
  1459. self.assertEqual(message.get("from"), "from@example.com")
  1460. self.assertEqual(message.get("to"), "to@example.com")
  1461. connection2 = mail.get_connection()
  1462. connection2.send_messages([msg])
  1463. self.assertEqual(len(os.listdir(self.tmp_dir)), 2)
  1464. connection.send_messages([msg])
  1465. self.assertEqual(len(os.listdir(self.tmp_dir)), 2)
  1466. msg.connection = mail.get_connection()
  1467. self.assertTrue(connection.open())
  1468. msg.send()
  1469. self.assertEqual(len(os.listdir(self.tmp_dir)), 3)
  1470. msg.send()
  1471. self.assertEqual(len(os.listdir(self.tmp_dir)), 3)
  1472. connection.close()
  1473. class FileBackendPathLibTests(FileBackendTests):
  1474. def mkdtemp(self):
  1475. tmp_dir = super().mkdtemp()
  1476. return Path(tmp_dir)
  1477. class ConsoleBackendTests(BaseEmailBackendTests, SimpleTestCase):
  1478. email_backend = "django.core.mail.backends.console.EmailBackend"
  1479. def setUp(self):
  1480. super().setUp()
  1481. self.__stdout = sys.stdout
  1482. self.stream = sys.stdout = StringIO()
  1483. def tearDown(self):
  1484. del self.stream
  1485. sys.stdout = self.__stdout
  1486. del self.__stdout
  1487. super().tearDown()
  1488. def flush_mailbox(self):
  1489. self.stream = sys.stdout = StringIO()
  1490. def get_mailbox_content(self):
  1491. messages = self.stream.getvalue().split("\n" + ("-" * 79) + "\n")
  1492. return [message_from_bytes(m.encode()) for m in messages if m]
  1493. def test_console_stream_kwarg(self):
  1494. """
  1495. The console backend can be pointed at an arbitrary stream.
  1496. """
  1497. s = StringIO()
  1498. connection = mail.get_connection(
  1499. "django.core.mail.backends.console.EmailBackend", stream=s
  1500. )
  1501. send_mail(
  1502. "Subject",
  1503. "Content",
  1504. "from@example.com",
  1505. ["to@example.com"],
  1506. connection=connection,
  1507. )
  1508. message = s.getvalue().split("\n" + ("-" * 79) + "\n")[0].encode()
  1509. self.assertMessageHasHeaders(
  1510. message,
  1511. {
  1512. ("MIME-Version", "1.0"),
  1513. ("Content-Type", 'text/plain; charset="utf-8"'),
  1514. ("Content-Transfer-Encoding", "7bit"),
  1515. ("Subject", "Subject"),
  1516. ("From", "from@example.com"),
  1517. ("To", "to@example.com"),
  1518. },
  1519. )
  1520. self.assertIn(b"\nDate: ", message)
  1521. class SMTPHandler:
  1522. def __init__(self, *args, **kwargs):
  1523. self.mailbox = []
  1524. async def handle_DATA(self, server, session, envelope):
  1525. data = envelope.content
  1526. mail_from = envelope.mail_from
  1527. message = message_from_bytes(data.rstrip())
  1528. message_addr = parseaddr(message.get("from"))[1]
  1529. if mail_from != message_addr:
  1530. # According to the spec, mail_from does not necessarily match the
  1531. # From header - this is the case where the local part isn't
  1532. # encoded, so try to correct that.
  1533. lp, domain = mail_from.split("@", 1)
  1534. lp = Header(lp, "utf-8").encode()
  1535. mail_from = "@".join([lp, domain])
  1536. if mail_from != message_addr:
  1537. return f"553 '{mail_from}' != '{message_addr}'"
  1538. self.mailbox.append(message)
  1539. return "250 OK"
  1540. def flush_mailbox(self):
  1541. self.mailbox[:] = []
  1542. @skipUnless(HAS_AIOSMTPD, "No aiosmtpd library detected.")
  1543. class SMTPBackendTestsBase(SimpleTestCase):
  1544. @classmethod
  1545. def setUpClass(cls):
  1546. super().setUpClass()
  1547. # Find a free port.
  1548. with socket.socket() as s:
  1549. s.bind(("127.0.0.1", 0))
  1550. port = s.getsockname()[1]
  1551. cls.smtp_handler = SMTPHandler()
  1552. cls.smtp_controller = Controller(
  1553. cls.smtp_handler,
  1554. hostname="127.0.0.1",
  1555. port=port,
  1556. )
  1557. cls._settings_override = override_settings(
  1558. EMAIL_HOST=cls.smtp_controller.hostname,
  1559. EMAIL_PORT=cls.smtp_controller.port,
  1560. )
  1561. cls._settings_override.enable()
  1562. cls.addClassCleanup(cls._settings_override.disable)
  1563. cls.smtp_controller.start()
  1564. cls.addClassCleanup(cls.stop_smtp)
  1565. @classmethod
  1566. def stop_smtp(cls):
  1567. cls.smtp_controller.stop()
  1568. @skipUnless(HAS_AIOSMTPD, "No aiosmtpd library detected.")
  1569. class SMTPBackendTests(BaseEmailBackendTests, SMTPBackendTestsBase):
  1570. email_backend = "django.core.mail.backends.smtp.EmailBackend"
  1571. def setUp(self):
  1572. super().setUp()
  1573. self.smtp_handler.flush_mailbox()
  1574. def tearDown(self):
  1575. self.smtp_handler.flush_mailbox()
  1576. super().tearDown()
  1577. def flush_mailbox(self):
  1578. self.smtp_handler.flush_mailbox()
  1579. def get_mailbox_content(self):
  1580. return self.smtp_handler.mailbox
  1581. @override_settings(
  1582. EMAIL_HOST_USER="not empty username",
  1583. EMAIL_HOST_PASSWORD="not empty password",
  1584. )
  1585. def test_email_authentication_use_settings(self):
  1586. backend = smtp.EmailBackend()
  1587. self.assertEqual(backend.username, "not empty username")
  1588. self.assertEqual(backend.password, "not empty password")
  1589. @override_settings(
  1590. EMAIL_HOST_USER="not empty username",
  1591. EMAIL_HOST_PASSWORD="not empty password",
  1592. )
  1593. def test_email_authentication_override_settings(self):
  1594. backend = smtp.EmailBackend(username="username", password="password")
  1595. self.assertEqual(backend.username, "username")
  1596. self.assertEqual(backend.password, "password")
  1597. @override_settings(
  1598. EMAIL_HOST_USER="not empty username",
  1599. EMAIL_HOST_PASSWORD="not empty password",
  1600. )
  1601. def test_email_disabled_authentication(self):
  1602. backend = smtp.EmailBackend(username="", password="")
  1603. self.assertEqual(backend.username, "")
  1604. self.assertEqual(backend.password, "")
  1605. def test_auth_attempted(self):
  1606. """
  1607. Opening the backend with non empty username/password tries
  1608. to authenticate against the SMTP server.
  1609. """
  1610. backend = smtp.EmailBackend(
  1611. username="not empty username", password="not empty password"
  1612. )
  1613. with self.assertRaisesMessage(
  1614. SMTPException, "SMTP AUTH extension not supported by server."
  1615. ):
  1616. with backend:
  1617. pass
  1618. def test_server_open(self):
  1619. """
  1620. open() returns whether it opened a connection.
  1621. """
  1622. backend = smtp.EmailBackend(username="", password="")
  1623. self.assertIsNone(backend.connection)
  1624. opened = backend.open()
  1625. backend.close()
  1626. self.assertIs(opened, True)
  1627. def test_reopen_connection(self):
  1628. backend = smtp.EmailBackend()
  1629. # Simulate an already open connection.
  1630. backend.connection = mock.Mock(spec=object())
  1631. self.assertIs(backend.open(), False)
  1632. @override_settings(EMAIL_USE_TLS=True)
  1633. def test_email_tls_use_settings(self):
  1634. backend = smtp.EmailBackend()
  1635. self.assertTrue(backend.use_tls)
  1636. @override_settings(EMAIL_USE_TLS=True)
  1637. def test_email_tls_override_settings(self):
  1638. backend = smtp.EmailBackend(use_tls=False)
  1639. self.assertFalse(backend.use_tls)
  1640. def test_email_tls_default_disabled(self):
  1641. backend = smtp.EmailBackend()
  1642. self.assertFalse(backend.use_tls)
  1643. def test_ssl_tls_mutually_exclusive(self):
  1644. msg = (
  1645. "EMAIL_USE_TLS/EMAIL_USE_SSL are mutually exclusive, so only set "
  1646. "one of those settings to True."
  1647. )
  1648. with self.assertRaisesMessage(ValueError, msg):
  1649. smtp.EmailBackend(use_ssl=True, use_tls=True)
  1650. @override_settings(EMAIL_USE_SSL=True)
  1651. def test_email_ssl_use_settings(self):
  1652. backend = smtp.EmailBackend()
  1653. self.assertTrue(backend.use_ssl)
  1654. @override_settings(EMAIL_USE_SSL=True)
  1655. def test_email_ssl_override_settings(self):
  1656. backend = smtp.EmailBackend(use_ssl=False)
  1657. self.assertFalse(backend.use_ssl)
  1658. def test_email_ssl_default_disabled(self):
  1659. backend = smtp.EmailBackend()
  1660. self.assertFalse(backend.use_ssl)
  1661. @override_settings(EMAIL_SSL_CERTFILE="foo")
  1662. def test_email_ssl_certfile_use_settings(self):
  1663. backend = smtp.EmailBackend()
  1664. self.assertEqual(backend.ssl_certfile, "foo")
  1665. @override_settings(EMAIL_SSL_CERTFILE="foo")
  1666. def test_email_ssl_certfile_override_settings(self):
  1667. backend = smtp.EmailBackend(ssl_certfile="bar")
  1668. self.assertEqual(backend.ssl_certfile, "bar")
  1669. def test_email_ssl_certfile_default_disabled(self):
  1670. backend = smtp.EmailBackend()
  1671. self.assertIsNone(backend.ssl_certfile)
  1672. @override_settings(EMAIL_SSL_KEYFILE="foo")
  1673. def test_email_ssl_keyfile_use_settings(self):
  1674. backend = smtp.EmailBackend()
  1675. self.assertEqual(backend.ssl_keyfile, "foo")
  1676. @override_settings(EMAIL_SSL_KEYFILE="foo")
  1677. def test_email_ssl_keyfile_override_settings(self):
  1678. backend = smtp.EmailBackend(ssl_keyfile="bar")
  1679. self.assertEqual(backend.ssl_keyfile, "bar")
  1680. def test_email_ssl_keyfile_default_disabled(self):
  1681. backend = smtp.EmailBackend()
  1682. self.assertIsNone(backend.ssl_keyfile)
  1683. @override_settings(EMAIL_USE_TLS=True)
  1684. def test_email_tls_attempts_starttls(self):
  1685. backend = smtp.EmailBackend()
  1686. self.assertTrue(backend.use_tls)
  1687. with self.assertRaisesMessage(
  1688. SMTPException, "STARTTLS extension not supported by server."
  1689. ):
  1690. with backend:
  1691. pass
  1692. @override_settings(EMAIL_USE_SSL=True)
  1693. def test_email_ssl_attempts_ssl_connection(self):
  1694. backend = smtp.EmailBackend()
  1695. self.assertTrue(backend.use_ssl)
  1696. with self.assertRaises(SSLError):
  1697. with backend:
  1698. pass
  1699. def test_connection_timeout_default(self):
  1700. """The connection's timeout value is None by default."""
  1701. connection = mail.get_connection("django.core.mail.backends.smtp.EmailBackend")
  1702. self.assertIsNone(connection.timeout)
  1703. def test_connection_timeout_custom(self):
  1704. """The timeout parameter can be customized."""
  1705. class MyEmailBackend(smtp.EmailBackend):
  1706. def __init__(self, *args, **kwargs):
  1707. kwargs.setdefault("timeout", 42)
  1708. super().__init__(*args, **kwargs)
  1709. myemailbackend = MyEmailBackend()
  1710. myemailbackend.open()
  1711. self.assertEqual(myemailbackend.timeout, 42)
  1712. self.assertEqual(myemailbackend.connection.timeout, 42)
  1713. myemailbackend.close()
  1714. @override_settings(EMAIL_TIMEOUT=10)
  1715. def test_email_timeout_override_settings(self):
  1716. backend = smtp.EmailBackend()
  1717. self.assertEqual(backend.timeout, 10)
  1718. def test_email_msg_uses_crlf(self):
  1719. """#23063 -- RFC-compliant messages are sent over SMTP."""
  1720. send = SMTP.send
  1721. try:
  1722. smtp_messages = []
  1723. def mock_send(self, s):
  1724. smtp_messages.append(s)
  1725. return send(self, s)
  1726. SMTP.send = mock_send
  1727. email = EmailMessage(
  1728. "Subject", "Content", "from@example.com", ["to@example.com"]
  1729. )
  1730. mail.get_connection().send_messages([email])
  1731. # Find the actual message
  1732. msg = None
  1733. for i, m in enumerate(smtp_messages):
  1734. if m[:4] == "data":
  1735. msg = smtp_messages[i + 1]
  1736. break
  1737. self.assertTrue(msg)
  1738. msg = msg.decode()
  1739. # The message only contains CRLF and not combinations of CRLF, LF, and CR.
  1740. msg = msg.replace("\r\n", "")
  1741. self.assertNotIn("\r", msg)
  1742. self.assertNotIn("\n", msg)
  1743. finally:
  1744. SMTP.send = send
  1745. def test_send_messages_after_open_failed(self):
  1746. """
  1747. send_messages() shouldn't try to send messages if open() raises an
  1748. exception after initializing the connection.
  1749. """
  1750. backend = smtp.EmailBackend()
  1751. # Simulate connection initialization success and a subsequent
  1752. # connection exception.
  1753. backend.connection = mock.Mock(spec=object())
  1754. backend.open = lambda: None
  1755. email = EmailMessage(
  1756. "Subject", "Content", "from@example.com", ["to@example.com"]
  1757. )
  1758. self.assertEqual(backend.send_messages([email]), 0)
  1759. def test_send_messages_empty_list(self):
  1760. backend = smtp.EmailBackend()
  1761. backend.connection = mock.Mock(spec=object())
  1762. self.assertEqual(backend.send_messages([]), 0)
  1763. def test_send_messages_zero_sent(self):
  1764. """A message isn't sent if it doesn't have any recipients."""
  1765. backend = smtp.EmailBackend()
  1766. backend.connection = mock.Mock(spec=object())
  1767. email = EmailMessage("Subject", "Content", "from@example.com", to=[])
  1768. sent = backend.send_messages([email])
  1769. self.assertEqual(sent, 0)
  1770. @skipUnless(HAS_AIOSMTPD, "No aiosmtpd library detected.")
  1771. class SMTPBackendStoppedServerTests(SMTPBackendTestsBase):
  1772. @classmethod
  1773. def setUpClass(cls):
  1774. super().setUpClass()
  1775. cls.backend = smtp.EmailBackend(username="", password="")
  1776. cls.smtp_controller.stop()
  1777. @classmethod
  1778. def stop_smtp(cls):
  1779. # SMTP controller is stopped in setUpClass().
  1780. pass
  1781. def test_server_stopped(self):
  1782. """
  1783. Closing the backend while the SMTP server is stopped doesn't raise an
  1784. exception.
  1785. """
  1786. self.backend.close()
  1787. def test_fail_silently_on_connection_error(self):
  1788. """
  1789. A socket connection error is silenced with fail_silently=True.
  1790. """
  1791. with self.assertRaises(ConnectionError):
  1792. self.backend.open()
  1793. self.backend.fail_silently = True
  1794. self.backend.open()