tests.py 95 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510
  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
  8. from email import message_from_bytes as _message_from_bytes
  9. from email import policy
  10. from email.message import EmailMessage as PyEmailMessage
  11. from email.message import Message as PyMessage
  12. from email.mime.image import MIMEImage
  13. from email.mime.text import MIMEText
  14. from io import StringIO
  15. from pathlib import Path
  16. from smtplib import SMTP, SMTPException
  17. from ssl import SSLError
  18. from textwrap import dedent
  19. from unittest import mock, skipUnless
  20. from django.core import mail
  21. from django.core.mail import (
  22. DNS_NAME,
  23. BadHeaderError,
  24. EmailAlternative,
  25. EmailAttachment,
  26. EmailMessage,
  27. EmailMultiAlternatives,
  28. mail_admins,
  29. mail_managers,
  30. send_mail,
  31. send_mass_mail,
  32. )
  33. from django.core.mail.backends import console, dummy, filebased, locmem, smtp
  34. from django.core.mail.message import sanitize_address
  35. from django.test import SimpleTestCase, override_settings
  36. from django.test.utils import requires_tz_support
  37. from django.utils.translation import gettext_lazy
  38. try:
  39. from aiosmtpd.controller import Controller
  40. HAS_AIOSMTPD = True
  41. except ImportError:
  42. HAS_AIOSMTPD = False
  43. def message_from_bytes(s):
  44. """
  45. email.message_from_bytes() using modern email.policy.default.
  46. Returns a modern email.message.EmailMessage.
  47. """
  48. return _message_from_bytes(s, policy=policy.default)
  49. class MailTestsMixin:
  50. def assertMessageHasHeaders(self, message, headers):
  51. """
  52. Asserts that the `message` has all `headers`.
  53. message: can be an instance of an email.Message subclass or bytes
  54. with the contents of an email message.
  55. headers: should be a set of (header-name, header-value) tuples.
  56. """
  57. if isinstance(message, bytes):
  58. message = message_from_bytes(message)
  59. msg_headers = set(message.items())
  60. if not headers.issubset(msg_headers):
  61. missing = "\n".join(f" {h}: {v}" for h, v in headers - msg_headers)
  62. actual = "\n".join(f" {h}: {v}" for h, v in msg_headers)
  63. raise self.failureException(
  64. f"Expected headers not found in message.\n"
  65. f"Missing headers:\n{missing}\n"
  66. f"Actual headers:\n{actual}"
  67. )
  68. # In assertStartsWith()/assertEndsWith() failure messages, when truncating
  69. # a long first ("haystack") string, include this many characters beyond the
  70. # length of the second ("needle") string.
  71. START_END_EXTRA_CONTEXT = 15
  72. def assertStartsWith(self, first, second):
  73. if not first.startswith(second):
  74. # Use assertEqual() for failure message with diffs. If first value
  75. # is much longer than second, truncate end and add an ellipsis.
  76. self.longMessage = True
  77. max_len = len(second) + self.START_END_EXTRA_CONTEXT
  78. start_of_first = (
  79. first
  80. if len(first) <= max_len
  81. else first[:max_len] + ("…" if isinstance(first, str) else b"...")
  82. )
  83. self.assertEqual(
  84. start_of_first,
  85. second,
  86. "First string doesn't start with the second.",
  87. )
  88. def assertEndsWith(self, first, second):
  89. if not first.endswith(second):
  90. # Use assertEqual() for failure message with diffs. If first value
  91. # is much longer than second, truncate start and prepend an ellipsis.
  92. self.longMessage = True
  93. max_len = len(second) + self.START_END_EXTRA_CONTEXT
  94. end_of_first = (
  95. first
  96. if len(first) <= max_len
  97. else ("…" if isinstance(first, str) else b"...") + first[-max_len:]
  98. )
  99. self.assertEqual(
  100. end_of_first,
  101. second,
  102. "First string doesn't end with the second.",
  103. )
  104. def get_raw_attachments(self, django_message):
  105. """
  106. Return a list of the raw attachment parts in the MIME message generated
  107. by serializing django_message and reparsing the result.
  108. This returns only "top-level" attachments. It will not descend into
  109. message/* attached emails to find nested attachments.
  110. """
  111. msg_bytes = django_message.message().as_bytes()
  112. message = message_from_bytes(msg_bytes)
  113. return list(message.iter_attachments())
  114. def get_decoded_attachments(self, django_message):
  115. """
  116. Return a list of decoded attachments resulting from serializing
  117. django_message and reparsing the result.
  118. Each attachment is returned as an EmailAttachment named tuple with
  119. fields filename, content, and mimetype. The content will be decoded
  120. to str for mimetype text/*; retained as bytes for other mimetypes.
  121. """
  122. return [
  123. EmailAttachment(
  124. attachment.get_filename(),
  125. attachment.get_content(),
  126. attachment.get_content_type(),
  127. )
  128. for attachment in self.get_raw_attachments(django_message)
  129. ]
  130. def get_message_structure(self, message, level=0):
  131. """
  132. Return a multiline indented string representation
  133. of the message's MIME content-type structure, e.g.:
  134. multipart/mixed
  135. multipart/alternative
  136. text/plain
  137. text/html
  138. image/jpg
  139. text/calendar
  140. """
  141. # Adapted from email.iterators._structure().
  142. indent = " " * (level * 4)
  143. structure = [f"{indent}{message.get_content_type()}\n"]
  144. if message.is_multipart():
  145. for subpart in message.get_payload():
  146. structure.append(self.get_message_structure(subpart, level + 1))
  147. return "".join(structure)
  148. class MailTests(MailTestsMixin, SimpleTestCase):
  149. """
  150. Non-backend specific tests.
  151. """
  152. def test_ascii(self):
  153. email = EmailMessage(
  154. "Subject", "Content", "from@example.com", ["to@example.com"]
  155. )
  156. message = email.message()
  157. self.assertEqual(message["Subject"], "Subject")
  158. self.assertEqual(message.get_payload(), "Content")
  159. self.assertEqual(message["From"], "from@example.com")
  160. self.assertEqual(message["To"], "to@example.com")
  161. @mock.patch("django.core.mail.message.MIMEText.set_payload")
  162. def test_nonascii_as_string_with_ascii_charset(self, mock_set_payload):
  163. """Line length check should encode the payload supporting `surrogateescape`.
  164. Following https://github.com/python/cpython/issues/76511, newer
  165. versions of Python (3.12.3 and 3.13) ensure that a message's
  166. payload is encoded with the provided charset and `surrogateescape` is
  167. used as the error handling strategy.
  168. This test is heavily based on the test from the fix for the bug above.
  169. Line length checks in SafeMIMEText's set_payload should also use the
  170. same error handling strategy to avoid errors such as:
  171. UnicodeEncodeError: 'utf-8' codec can't encode <...>: surrogates not allowed
  172. """
  173. def simplified_set_payload(instance, payload, charset):
  174. instance._payload = payload
  175. mock_set_payload.side_effect = simplified_set_payload
  176. text = (
  177. "Text heavily based in Python's text for non-ascii messages: Föö bär"
  178. ).encode("iso-8859-1")
  179. body = text.decode("ascii", errors="surrogateescape")
  180. email = EmailMessage("Subject", body, "from@example.com", ["to@example.com"])
  181. message = email.message()
  182. mock_set_payload.assert_called_once()
  183. self.assertEqual(message.get_payload(decode=True), text)
  184. def test_multiple_recipients(self):
  185. email = EmailMessage(
  186. "Subject",
  187. "Content",
  188. "from@example.com",
  189. ["to@example.com", "other@example.com"],
  190. )
  191. message = email.message()
  192. self.assertEqual(message["Subject"], "Subject")
  193. self.assertEqual(message.get_payload(), "Content")
  194. self.assertEqual(message["From"], "from@example.com")
  195. self.assertEqual(message["To"], "to@example.com, other@example.com")
  196. def test_header_omitted_for_no_to_recipients(self):
  197. message = EmailMessage(
  198. "Subject", "Content", "from@example.com", cc=["cc@example.com"]
  199. ).message()
  200. self.assertNotIn("To", message)
  201. def test_recipients_with_empty_strings(self):
  202. """
  203. Empty strings in various recipient arguments are always stripped
  204. off the final recipient list.
  205. """
  206. email = EmailMessage(
  207. "Subject",
  208. "Content",
  209. "from@example.com",
  210. ["to@example.com", ""],
  211. cc=["cc@example.com", ""],
  212. bcc=["", "bcc@example.com"],
  213. reply_to=["", None],
  214. )
  215. self.assertEqual(
  216. email.recipients(), ["to@example.com", "cc@example.com", "bcc@example.com"]
  217. )
  218. def test_cc(self):
  219. """Regression test for #7722"""
  220. email = EmailMessage(
  221. "Subject",
  222. "Content",
  223. "from@example.com",
  224. ["to@example.com"],
  225. cc=["cc@example.com"],
  226. )
  227. message = email.message()
  228. self.assertEqual(message["Cc"], "cc@example.com")
  229. self.assertEqual(email.recipients(), ["to@example.com", "cc@example.com"])
  230. # Test multiple CC with multiple To
  231. email = EmailMessage(
  232. "Subject",
  233. "Content",
  234. "from@example.com",
  235. ["to@example.com", "other@example.com"],
  236. cc=["cc@example.com", "cc.other@example.com"],
  237. )
  238. message = email.message()
  239. self.assertEqual(message["Cc"], "cc@example.com, cc.other@example.com")
  240. self.assertEqual(
  241. email.recipients(),
  242. [
  243. "to@example.com",
  244. "other@example.com",
  245. "cc@example.com",
  246. "cc.other@example.com",
  247. ],
  248. )
  249. # Testing with Bcc
  250. email = EmailMessage(
  251. "Subject",
  252. "Content",
  253. "from@example.com",
  254. ["to@example.com", "other@example.com"],
  255. cc=["cc@example.com", "cc.other@example.com"],
  256. bcc=["bcc@example.com"],
  257. )
  258. message = email.message()
  259. self.assertEqual(message["Cc"], "cc@example.com, cc.other@example.com")
  260. self.assertEqual(
  261. email.recipients(),
  262. [
  263. "to@example.com",
  264. "other@example.com",
  265. "cc@example.com",
  266. "cc.other@example.com",
  267. "bcc@example.com",
  268. ],
  269. )
  270. def test_cc_headers(self):
  271. message = EmailMessage(
  272. "Subject",
  273. "Content",
  274. "bounce@example.com",
  275. ["to@example.com"],
  276. cc=["foo@example.com"],
  277. headers={"Cc": "override@example.com"},
  278. ).message()
  279. self.assertEqual(message.get_all("Cc"), ["override@example.com"])
  280. def test_cc_in_headers_only(self):
  281. message = EmailMessage(
  282. "Subject",
  283. "Content",
  284. "bounce@example.com",
  285. ["to@example.com"],
  286. headers={"Cc": "foo@example.com"},
  287. ).message()
  288. self.assertEqual(message.get_all("Cc"), ["foo@example.com"])
  289. def test_bcc_not_in_headers(self):
  290. """
  291. A bcc address should be in the recipients,
  292. but not in the (visible) message headers.
  293. """
  294. email = EmailMessage(
  295. to=["to@example.com"],
  296. bcc=["bcc@example.com"],
  297. )
  298. message = email.message()
  299. self.assertNotIn("Bcc", message)
  300. self.assertNotIn("bcc@example.com", message.as_string())
  301. self.assertEqual(email.recipients(), ["to@example.com", "bcc@example.com"])
  302. def test_reply_to(self):
  303. email = EmailMessage(
  304. "Subject",
  305. "Content",
  306. "from@example.com",
  307. ["to@example.com"],
  308. reply_to=["reply_to@example.com"],
  309. )
  310. message = email.message()
  311. self.assertEqual(message["Reply-To"], "reply_to@example.com")
  312. email = EmailMessage(
  313. "Subject",
  314. "Content",
  315. "from@example.com",
  316. ["to@example.com"],
  317. reply_to=["reply_to1@example.com", "reply_to2@example.com"],
  318. )
  319. message = email.message()
  320. self.assertEqual(
  321. message["Reply-To"], "reply_to1@example.com, reply_to2@example.com"
  322. )
  323. def test_recipients_as_tuple(self):
  324. email = EmailMessage(
  325. "Subject",
  326. "Content",
  327. "from@example.com",
  328. ("to@example.com", "other@example.com"),
  329. cc=("cc@example.com", "cc.other@example.com"),
  330. bcc=("bcc@example.com",),
  331. )
  332. message = email.message()
  333. self.assertEqual(message["Cc"], "cc@example.com, cc.other@example.com")
  334. self.assertEqual(
  335. email.recipients(),
  336. [
  337. "to@example.com",
  338. "other@example.com",
  339. "cc@example.com",
  340. "cc.other@example.com",
  341. "bcc@example.com",
  342. ],
  343. )
  344. def test_recipients_as_string(self):
  345. with self.assertRaisesMessage(
  346. TypeError, '"to" argument must be a list or tuple'
  347. ):
  348. EmailMessage(to="foo@example.com")
  349. with self.assertRaisesMessage(
  350. TypeError, '"cc" argument must be a list or tuple'
  351. ):
  352. EmailMessage(cc="foo@example.com")
  353. with self.assertRaisesMessage(
  354. TypeError, '"bcc" argument must be a list or tuple'
  355. ):
  356. EmailMessage(bcc="foo@example.com")
  357. with self.assertRaisesMessage(
  358. TypeError, '"reply_to" argument must be a list or tuple'
  359. ):
  360. EmailMessage(reply_to="reply_to@example.com")
  361. def test_header_injection(self):
  362. msg = "Header values can't contain newlines "
  363. cases = [
  364. {"subject": "Subject\nInjection Test"},
  365. {"subject": gettext_lazy("Lazy Subject\nInjection Test")},
  366. {"to": ["Name\nInjection test <to@example.com>"]},
  367. ]
  368. for kwargs in cases:
  369. with self.subTest(case=kwargs):
  370. email = EmailMessage(**kwargs)
  371. with self.assertRaisesMessage(BadHeaderError, msg):
  372. email.message()
  373. def test_folding_white_space(self):
  374. """
  375. Test for correct use of "folding white space" in long headers (#7747)
  376. """
  377. email = EmailMessage(
  378. "Long subject lines that get wrapped should contain a space continuation "
  379. "character to get expected behavior in Outlook and Thunderbird",
  380. "Content",
  381. "from@example.com",
  382. ["to@example.com"],
  383. )
  384. message = email.message()
  385. self.assertEqual(
  386. message["Subject"].encode(),
  387. b"Long subject lines that get wrapped should contain a space continuation\n"
  388. b" character to get expected behavior in Outlook and Thunderbird",
  389. )
  390. def test_message_header_overrides(self):
  391. """
  392. Specifying dates or message-ids in the extra headers overrides the
  393. default values (#9233)
  394. """
  395. headers = {"date": "Fri, 09 Nov 2001 01:08:47 -0000", "Message-ID": "foo"}
  396. email = EmailMessage(headers=headers)
  397. self.assertMessageHasHeaders(
  398. email.message(),
  399. {
  400. ("Message-ID", "foo"),
  401. ("date", "Fri, 09 Nov 2001 01:08:47 -0000"),
  402. },
  403. )
  404. def test_from_header(self):
  405. """
  406. Make sure we can manually set the From header (#9214)
  407. """
  408. email = EmailMessage(
  409. from_email="bounce@example.com",
  410. headers={"From": "from@example.com"},
  411. )
  412. message = email.message()
  413. self.assertEqual(message.get_all("From"), ["from@example.com"])
  414. def test_to_header(self):
  415. """
  416. Make sure we can manually set the To header (#17444)
  417. """
  418. email = EmailMessage(
  419. to=["list-subscriber@example.com", "list-subscriber2@example.com"],
  420. headers={"To": "mailing-list@example.com"},
  421. )
  422. message = email.message()
  423. self.assertEqual(message.get_all("To"), ["mailing-list@example.com"])
  424. self.assertEqual(
  425. email.to, ["list-subscriber@example.com", "list-subscriber2@example.com"]
  426. )
  427. # If we don't set the To header manually, it should default to the `to`
  428. # argument to the constructor.
  429. email = EmailMessage(
  430. to=["list-subscriber@example.com", "list-subscriber2@example.com"],
  431. )
  432. message = email.message()
  433. self.assertEqual(
  434. message.get_all("To"),
  435. ["list-subscriber@example.com, list-subscriber2@example.com"],
  436. )
  437. self.assertEqual(
  438. email.to, ["list-subscriber@example.com", "list-subscriber2@example.com"]
  439. )
  440. def test_to_in_headers_only(self):
  441. message = EmailMessage(
  442. headers={"To": "to@example.com"},
  443. ).message()
  444. self.assertEqual(message.get_all("To"), ["to@example.com"])
  445. def test_reply_to_header(self):
  446. """
  447. Specifying 'Reply-To' in headers should override reply_to.
  448. """
  449. email = EmailMessage(
  450. reply_to=["foo@example.com"],
  451. headers={"Reply-To": "override@example.com"},
  452. )
  453. message = email.message()
  454. self.assertEqual(message.get_all("Reply-To"), ["override@example.com"])
  455. def test_reply_to_in_headers_only(self):
  456. message = EmailMessage(
  457. headers={"Reply-To": "reply_to@example.com"},
  458. ).message()
  459. self.assertEqual(message.get_all("Reply-To"), ["reply_to@example.com"])
  460. def test_multiple_message_call(self):
  461. """
  462. Regression for #13259 - Make sure that headers are not changed when
  463. calling EmailMessage.message()
  464. """
  465. email = EmailMessage(
  466. from_email="bounce@example.com",
  467. headers={"From": "from@example.com"},
  468. )
  469. message = email.message()
  470. self.assertEqual(message.get_all("From"), ["from@example.com"])
  471. message = email.message()
  472. self.assertEqual(message.get_all("From"), ["from@example.com"])
  473. def test_unicode_address_header(self):
  474. """
  475. Regression for #11144 - When a to/from/cc header contains Unicode,
  476. make sure the email addresses are parsed correctly (especially with
  477. regards to commas)
  478. """
  479. email = EmailMessage(
  480. to=['"Firstname Sürname" <to@example.com>', "other@example.com"],
  481. )
  482. self.assertEqual(
  483. email.message()["To"],
  484. "=?utf-8?q?Firstname_S=C3=BCrname?= <to@example.com>, other@example.com",
  485. )
  486. email = EmailMessage(
  487. to=['"Sürname, Firstname" <to@example.com>', "other@example.com"],
  488. )
  489. self.assertEqual(
  490. email.message()["To"],
  491. "=?utf-8?q?S=C3=BCrname=2C_Firstname?= <to@example.com>, other@example.com",
  492. )
  493. def test_unicode_headers(self):
  494. email = EmailMessage(
  495. subject="Gżegżółka",
  496. to=["to@example.com"],
  497. headers={
  498. "Sender": '"Firstname Sürname" <sender@example.com>',
  499. "Comments": "My Sürname is non-ASCII",
  500. },
  501. )
  502. message = email.message()
  503. self.assertEqual(message["Subject"], "=?utf-8?b?R8W8ZWfFvMOzxYJrYQ==?=")
  504. self.assertEqual(
  505. message["Sender"], "=?utf-8?q?Firstname_S=C3=BCrname?= <sender@example.com>"
  506. )
  507. self.assertEqual(
  508. message["Comments"], "=?utf-8?q?My_S=C3=BCrname_is_non-ASCII?="
  509. )
  510. def test_non_utf8_headers_multipart(self):
  511. """
  512. Make sure headers can be set with a different encoding than utf-8 in
  513. EmailMultiAlternatives as well.
  514. """
  515. headers = {"Date": "Fri, 09 Nov 2001 01:08:47 -0000", "Message-ID": "foo"}
  516. from_email = "from@example.com"
  517. to = '"Sürname, Firstname" <to@example.com>'
  518. text_content = "This is an important message."
  519. html_content = "<p>This is an <strong>important</strong> message.</p>"
  520. msg = EmailMultiAlternatives(
  521. "Message from Firstname Sürname",
  522. text_content,
  523. from_email,
  524. [to],
  525. headers=headers,
  526. )
  527. msg.attach_alternative(html_content, "text/html")
  528. msg.encoding = "iso-8859-1"
  529. self.assertEqual(
  530. msg.message()["To"],
  531. "=?iso-8859-1?q?S=FCrname=2C_Firstname?= <to@example.com>",
  532. )
  533. self.assertEqual(
  534. msg.message()["Subject"],
  535. "=?iso-8859-1?q?Message_from_Firstname_S=FCrname?=",
  536. )
  537. def test_multipart_with_attachments(self):
  538. """
  539. EmailMultiAlternatives includes alternatives if the body is empty and
  540. it has attachments.
  541. """
  542. msg = EmailMultiAlternatives(body="")
  543. html_content = "<p>This is <strong>html</strong></p>"
  544. msg.attach_alternative(html_content, "text/html")
  545. msg.attach("example.txt", "Text file content", "text/plain")
  546. self.assertIn(html_content, msg.message().as_string())
  547. def test_alternatives(self):
  548. msg = EmailMultiAlternatives()
  549. html_content = "<p>This is <strong>html</strong></p>"
  550. mime_type = "text/html"
  551. msg.attach_alternative(html_content, mime_type)
  552. self.assertIsInstance(msg.alternatives[0], EmailAlternative)
  553. self.assertEqual(msg.alternatives[0][0], html_content)
  554. self.assertEqual(msg.alternatives[0].content, html_content)
  555. self.assertEqual(msg.alternatives[0][1], mime_type)
  556. self.assertEqual(msg.alternatives[0].mimetype, mime_type)
  557. self.assertIn(html_content, msg.message().as_string())
  558. def test_alternatives_constructor(self):
  559. html_content = "<p>This is <strong>html</strong></p>"
  560. mime_type = "text/html"
  561. msg = EmailMultiAlternatives(
  562. alternatives=[EmailAlternative(html_content, mime_type)]
  563. )
  564. self.assertIsInstance(msg.alternatives[0], EmailAlternative)
  565. self.assertEqual(msg.alternatives[0][0], html_content)
  566. self.assertEqual(msg.alternatives[0].content, html_content)
  567. self.assertEqual(msg.alternatives[0][1], mime_type)
  568. self.assertEqual(msg.alternatives[0].mimetype, mime_type)
  569. self.assertIn(html_content, msg.message().as_string())
  570. def test_alternatives_constructor_from_tuple(self):
  571. html_content = "<p>This is <strong>html</strong></p>"
  572. mime_type = "text/html"
  573. msg = EmailMultiAlternatives(alternatives=[(html_content, mime_type)])
  574. self.assertIsInstance(msg.alternatives[0], EmailAlternative)
  575. self.assertEqual(msg.alternatives[0][0], html_content)
  576. self.assertEqual(msg.alternatives[0].content, html_content)
  577. self.assertEqual(msg.alternatives[0][1], mime_type)
  578. self.assertEqual(msg.alternatives[0].mimetype, mime_type)
  579. self.assertIn(html_content, msg.message().as_string())
  580. def test_none_body(self):
  581. msg = EmailMessage("subject", None, "from@example.com", ["to@example.com"])
  582. self.assertEqual(msg.body, "")
  583. self.assertEqual(msg.message().get_payload(), "")
  584. @mock.patch("socket.getfqdn", return_value="漢字")
  585. def test_non_ascii_dns_non_unicode_email(self, mocked_getfqdn):
  586. delattr(DNS_NAME, "_fqdn")
  587. email = EmailMessage()
  588. email.encoding = "iso-8859-1"
  589. self.assertIn("@xn--p8s937b>", email.message()["Message-ID"])
  590. def test_encoding(self):
  591. """
  592. Regression for #12791 - Encode body correctly with other encodings
  593. than utf-8
  594. """
  595. email = EmailMessage(body="Firstname Sürname is a great guy.")
  596. email.encoding = "iso-8859-1"
  597. message = email.message()
  598. self.assertMessageHasHeaders(
  599. message,
  600. {
  601. ("MIME-Version", "1.0"),
  602. ("Content-Type", 'text/plain; charset="iso-8859-1"'),
  603. ("Content-Transfer-Encoding", "quoted-printable"),
  604. },
  605. )
  606. self.assertEqual(message.get_payload(), "Firstname S=FCrname is a great guy.")
  607. def test_encoding_alternatives(self):
  608. """
  609. Encode alternatives correctly with other encodings than utf-8.
  610. """
  611. text_content = "Firstname Sürname is a great guy."
  612. html_content = "<p>Firstname Sürname is a <strong>great</strong> guy.</p>"
  613. email = EmailMultiAlternatives(body=text_content)
  614. email.encoding = "iso-8859-1"
  615. email.attach_alternative(html_content, "text/html")
  616. message = email.message()
  617. # Check the text/plain part.
  618. payload0 = message.get_payload(0)
  619. self.assertMessageHasHeaders(
  620. payload0,
  621. {
  622. # (The MIME-Version header is neither required nor meaningful
  623. # in a subpart, and this check for it can be safely removed.)
  624. ("MIME-Version", "1.0"),
  625. ("Content-Type", 'text/plain; charset="iso-8859-1"'),
  626. ("Content-Transfer-Encoding", "quoted-printable"),
  627. },
  628. )
  629. self.assertEndsWith(
  630. payload0.as_bytes(), b"\n\nFirstname S=FCrname is a great guy."
  631. )
  632. # Check the text/html alternative.
  633. payload1 = message.get_payload(1)
  634. self.assertMessageHasHeaders(
  635. payload1,
  636. {
  637. # (The MIME-Version header is neither required nor meaningful
  638. # in a subpart, and this check for it can be safely removed.)
  639. ("MIME-Version", "1.0"),
  640. ("Content-Type", 'text/html; charset="iso-8859-1"'),
  641. ("Content-Transfer-Encoding", "quoted-printable"),
  642. },
  643. )
  644. self.assertEndsWith(
  645. payload1.as_bytes(),
  646. b"\n\n<p>Firstname S=FCrname is a <strong>great</strong> guy.</p>",
  647. )
  648. def test_attachments(self):
  649. msg = EmailMessage()
  650. file_name = "example.txt"
  651. file_content = "Text file content"
  652. mime_type = "text/plain"
  653. msg.attach(file_name, file_content, mime_type)
  654. self.assertEqual(msg.attachments[0][0], file_name)
  655. self.assertEqual(msg.attachments[0].filename, file_name)
  656. self.assertEqual(msg.attachments[0][1], file_content)
  657. self.assertEqual(msg.attachments[0].content, file_content)
  658. self.assertEqual(msg.attachments[0][2], mime_type)
  659. self.assertEqual(msg.attachments[0].mimetype, mime_type)
  660. attachments = self.get_decoded_attachments(msg)
  661. self.assertEqual(attachments[0], (file_name, file_content, mime_type))
  662. def test_attachments_constructor(self):
  663. file_name = "example.txt"
  664. file_content = "Text file content"
  665. mime_type = "text/plain"
  666. msg = EmailMessage(
  667. attachments=[EmailAttachment(file_name, file_content, mime_type)]
  668. )
  669. self.assertIsInstance(msg.attachments[0], EmailAttachment)
  670. self.assertEqual(msg.attachments[0][0], file_name)
  671. self.assertEqual(msg.attachments[0].filename, file_name)
  672. self.assertEqual(msg.attachments[0][1], file_content)
  673. self.assertEqual(msg.attachments[0].content, file_content)
  674. self.assertEqual(msg.attachments[0][2], mime_type)
  675. self.assertEqual(msg.attachments[0].mimetype, mime_type)
  676. attachments = self.get_decoded_attachments(msg)
  677. self.assertEqual(attachments[0], (file_name, file_content, mime_type))
  678. def test_attachments_constructor_from_tuple(self):
  679. file_name = "example.txt"
  680. file_content = "Text file content"
  681. mime_type = "text/plain"
  682. msg = EmailMessage(attachments=[(file_name, file_content, mime_type)])
  683. self.assertIsInstance(msg.attachments[0], EmailAttachment)
  684. self.assertEqual(msg.attachments[0][0], file_name)
  685. self.assertEqual(msg.attachments[0].filename, file_name)
  686. self.assertEqual(msg.attachments[0][1], file_content)
  687. self.assertEqual(msg.attachments[0].content, file_content)
  688. self.assertEqual(msg.attachments[0][2], mime_type)
  689. self.assertEqual(msg.attachments[0].mimetype, mime_type)
  690. attachments = self.get_decoded_attachments(msg)
  691. self.assertEqual(attachments[0], (file_name, file_content, mime_type))
  692. def test_attachments_constructor_omit_mimetype(self):
  693. """
  694. The mimetype can be omitted from an attachment tuple.
  695. """
  696. msg = EmailMessage(attachments=[("filename1", "content1")])
  697. filename, content, mimetype = self.get_decoded_attachments(msg)[0]
  698. self.assertEqual(filename, "filename1")
  699. self.assertEqual(content, b"content1")
  700. self.assertEqual(mimetype, "application/octet-stream")
  701. def test_attachments_with_alternative_parts(self):
  702. """
  703. Message with attachment and alternative has correct structure (#9367).
  704. """
  705. text_content = "This is an important message."
  706. html_content = "<p>This is an <strong>important</strong> message.</p>"
  707. msg = EmailMultiAlternatives(body=text_content)
  708. msg.attach_alternative(html_content, "text/html")
  709. msg.attach("an attachment.pdf", b"%PDF-1.4.%...", mimetype="application/pdf")
  710. msg_bytes = msg.message().as_bytes()
  711. message = message_from_bytes(msg_bytes)
  712. self.assertTrue(message.is_multipart())
  713. self.assertEqual(message.get_content_type(), "multipart/mixed")
  714. self.assertEqual(message.get_default_type(), "text/plain")
  715. payload = message.get_payload()
  716. self.assertEqual(payload[0].get_content_type(), "multipart/alternative")
  717. self.assertEqual(payload[1].get_content_type(), "application/pdf")
  718. def test_decoded_attachments_MIMEText(self):
  719. txt = MIMEText("content1")
  720. msg = EmailMessage(attachments=[txt])
  721. payload = msg.message().get_payload()
  722. self.assertEqual(payload[0], txt)
  723. def test_non_ascii_attachment_filename(self):
  724. """Regression test for #14964"""
  725. msg = EmailMessage(body="Content")
  726. # Unicode in file name
  727. msg.attach("une pièce jointe.pdf", b"%PDF-1.4.%...", mimetype="application/pdf")
  728. attachment = self.get_decoded_attachments(msg)[0]
  729. self.assertEqual(attachment.filename, "une pièce jointe.pdf")
  730. def test_attach_file(self):
  731. """
  732. Test attaching a file against different mimetypes and make sure that
  733. a file will be attached and sent in some form even if a mismatched
  734. mimetype is specified.
  735. """
  736. files = (
  737. # filename, actual mimetype
  738. ("file.txt", "text/plain"),
  739. ("file.png", "image/png"),
  740. ("file_txt", None),
  741. ("file_png", None),
  742. ("file_txt.png", "image/png"),
  743. ("file_png.txt", "text/plain"),
  744. ("file.eml", "message/rfc822"),
  745. )
  746. test_mimetypes = ["text/plain", "image/png", None]
  747. for basename, real_mimetype in files:
  748. for mimetype in test_mimetypes:
  749. with self.subTest(
  750. basename=basename, real_mimetype=real_mimetype, mimetype=mimetype
  751. ):
  752. self.assertEqual(mimetypes.guess_type(basename)[0], real_mimetype)
  753. expected_mimetype = (
  754. mimetype or real_mimetype or "application/octet-stream"
  755. )
  756. file_path = Path(__file__).parent / "attachments" / basename
  757. expected_content = file_path.read_bytes()
  758. if expected_mimetype.startswith("text/"):
  759. try:
  760. expected_content = expected_content.decode()
  761. except UnicodeDecodeError:
  762. expected_mimetype = "application/octet-stream"
  763. email = EmailMessage()
  764. email.attach_file(file_path, mimetype=mimetype)
  765. # Check EmailMessage.attachments.
  766. self.assertEqual(len(email.attachments), 1)
  767. self.assertEqual(email.attachments[0].filename, basename)
  768. self.assertEqual(email.attachments[0].mimetype, expected_mimetype)
  769. self.assertEqual(email.attachments[0].content, expected_content)
  770. # Check attachments in the generated message.
  771. # (The actual content is not checked as variations in platform
  772. # line endings and rfc822 refolding complicate the logic.)
  773. attachments = self.get_decoded_attachments(email)
  774. self.assertEqual(len(attachments), 1)
  775. actual = attachments[0]
  776. self.assertEqual(actual.filename, basename)
  777. self.assertEqual(actual.mimetype, expected_mimetype)
  778. def test_attach_text_as_bytes(self):
  779. msg = EmailMessage()
  780. msg.attach("file.txt", b"file content")
  781. filename, content, mimetype = self.get_decoded_attachments(msg)[0]
  782. self.assertEqual(filename, "file.txt")
  783. self.assertEqual(content, "file content") # (decoded)
  784. self.assertEqual(mimetype, "text/plain")
  785. def test_attach_utf8_text_as_bytes(self):
  786. """
  787. Non-ASCII characters encoded as valid UTF-8 are correctly transported
  788. in a form that can be decoded at the receiving end.
  789. """
  790. msg = EmailMessage()
  791. msg.attach("file.txt", b"\xc3\xa4") # UTF-8 encoded a umlaut.
  792. filename, content, mimetype = self.get_decoded_attachments(msg)[0]
  793. self.assertEqual(filename, "file.txt")
  794. self.assertEqual(content, "ä") # (decoded)
  795. self.assertEqual(mimetype, "text/plain")
  796. def test_attach_non_utf8_text_as_bytes(self):
  797. """
  798. Binary data that can't be decoded as UTF-8 overrides the MIME type
  799. instead of decoding the data.
  800. """
  801. msg = EmailMessage()
  802. msg.attach("file.txt", b"\xff") # Invalid UTF-8.
  803. filename, content, mimetype = self.get_decoded_attachments(msg)[0]
  804. self.assertEqual(filename, "file.txt")
  805. # Content should be passed through unmodified.
  806. self.assertEqual(content, b"\xff")
  807. self.assertEqual(mimetype, "application/octet-stream")
  808. def test_attach_mime_image(self):
  809. """
  810. EmailMessage.attach() docs: "You can pass it
  811. a single argument that is a MIMEBase instance."
  812. """
  813. # This also verifies complex attachments with extra header fields.
  814. email = EmailMessage()
  815. image = MIMEImage(b"GIF89a...", "gif")
  816. image["Content-Disposition"] = "inline"
  817. image["Content-ID"] = "<content-id@example.org>"
  818. email.attach(image)
  819. attachments = self.get_raw_attachments(email)
  820. self.assertEqual(len(attachments), 1)
  821. image_att = attachments[0]
  822. self.assertEqual(image_att.get_content_type(), "image/gif")
  823. self.assertEqual(image_att.get_content_disposition(), "inline")
  824. self.assertEqual(image_att["Content-ID"], "<content-id@example.org>")
  825. self.assertEqual(image_att.get_content(), b"GIF89a...")
  826. self.assertIsNone(image_att.get_filename())
  827. def test_attach_mime_image_in_constructor(self):
  828. image = MIMEImage(b"\x89PNG...", "png")
  829. image["Content-Disposition"] = "attachment; filename=test.png"
  830. email = EmailMessage(attachments=[image])
  831. attachments = self.get_raw_attachments(email)
  832. self.assertEqual(len(attachments), 1)
  833. image_att = attachments[0]
  834. self.assertEqual(image_att.get_content_type(), "image/png")
  835. self.assertEqual(image_att.get_content(), b"\x89PNG...")
  836. self.assertEqual(image_att.get_content_disposition(), "attachment")
  837. self.assertEqual(image_att.get_filename(), "test.png")
  838. def test_attach_rfc822_message(self):
  839. """
  840. EmailMessage.attach() docs: "If you specify a mimetype of message/rfc822,
  841. it will also accept django.core.mail.EmailMessage and email.message.Message."
  842. """
  843. # django.core.mail.EmailMessage
  844. django_email = EmailMessage("child subject", "child body")
  845. # email.message.Message
  846. py_message = PyMessage()
  847. py_message["Subject"] = "child subject"
  848. py_message.set_payload("child body")
  849. # email.message.EmailMessage
  850. py_email_message = PyEmailMessage()
  851. py_email_message["Subject"] = "child subject"
  852. py_email_message.set_content("child body")
  853. cases = [
  854. django_email,
  855. py_message,
  856. py_email_message,
  857. # Should also allow message serialized as str or bytes.
  858. py_message.as_string(),
  859. py_message.as_bytes(),
  860. ]
  861. for child_message in cases:
  862. with self.subTest(child_type=child_message.__class__):
  863. email = EmailMessage("parent message", "parent body")
  864. email.attach(content=child_message, mimetype="message/rfc822")
  865. self.assertEqual(len(email.attachments), 1)
  866. self.assertIsInstance(email.attachments[0], EmailAttachment)
  867. self.assertEqual(email.attachments[0].mimetype, "message/rfc822")
  868. # Make sure it is serialized correctly: a message/rfc822 attachment
  869. # whose "body" content (payload) is the "encapsulated" (child) message.
  870. attachments = self.get_raw_attachments(email)
  871. self.assertEqual(len(attachments), 1)
  872. rfc822_attachment = attachments[0]
  873. self.assertEqual(rfc822_attachment.get_content_type(), "message/rfc822")
  874. attached_message = rfc822_attachment.get_content()
  875. self.assertEqual(attached_message["Subject"], "child subject")
  876. self.assertEqual(attached_message.get_content().rstrip(), "child body")
  877. # Regression for #18967: Per RFC 2046 5.2.1, "No encoding other
  878. # than '7bit', '8bit', or 'binary' is permitted for the body of
  879. # a 'message/rfc822' entity." (Default CTE is "7bit".)
  880. cte = rfc822_attachment.get("Content-Transfer-Encoding", "7bit")
  881. self.assertIn(cte, ("7bit", "8bit", "binary"))
  882. # Any properly declared CTE is allowed for the attached message itself
  883. # (including quoted-printable or base64). For the plain ASCII content
  884. # in this test, we'd expect 7bit.
  885. child_cte = attached_message.get("Content-Transfer-Encoding", "7bit")
  886. self.assertEqual(child_cte, "7bit")
  887. self.assertEqual(attached_message.get_content_type(), "text/plain")
  888. def test_attach_mimebase_prohibits_other_params(self):
  889. email_msg = EmailMessage()
  890. txt = MIMEText("content")
  891. msg = (
  892. "content and mimetype must not be given when a MIMEBase instance "
  893. "is provided."
  894. )
  895. with self.assertRaisesMessage(ValueError, msg):
  896. email_msg.attach(txt, content="content")
  897. with self.assertRaisesMessage(ValueError, msg):
  898. email_msg.attach(txt, mimetype="text/plain")
  899. def test_attach_content_is_required(self):
  900. email_msg = EmailMessage()
  901. msg = "content must be provided."
  902. with self.assertRaisesMessage(ValueError, msg):
  903. email_msg.attach("file.txt", mimetype="application/pdf")
  904. def test_dummy_backend(self):
  905. """
  906. Make sure that dummy backends returns correct number of sent messages
  907. """
  908. connection = dummy.EmailBackend()
  909. email = EmailMessage(to=["to@example.com"])
  910. self.assertEqual(connection.send_messages([email, email, email]), 3)
  911. def test_arbitrary_keyword(self):
  912. """
  913. Make sure that get_connection() accepts arbitrary keyword that might be
  914. used with custom backends.
  915. """
  916. c = mail.get_connection(fail_silently=True, foo="bar")
  917. self.assertTrue(c.fail_silently)
  918. def test_custom_backend(self):
  919. """Test custom backend defined in this suite."""
  920. conn = mail.get_connection("mail.custombackend.EmailBackend")
  921. self.assertTrue(hasattr(conn, "test_outbox"))
  922. email = EmailMessage(to=["to@example.com"])
  923. conn.send_messages([email])
  924. self.assertEqual(len(conn.test_outbox), 1)
  925. def test_backend_arg(self):
  926. """Test backend argument of mail.get_connection()"""
  927. self.assertIsInstance(
  928. mail.get_connection("django.core.mail.backends.smtp.EmailBackend"),
  929. smtp.EmailBackend,
  930. )
  931. self.assertIsInstance(
  932. mail.get_connection("django.core.mail.backends.locmem.EmailBackend"),
  933. locmem.EmailBackend,
  934. )
  935. self.assertIsInstance(
  936. mail.get_connection("django.core.mail.backends.dummy.EmailBackend"),
  937. dummy.EmailBackend,
  938. )
  939. self.assertIsInstance(
  940. mail.get_connection("django.core.mail.backends.console.EmailBackend"),
  941. console.EmailBackend,
  942. )
  943. with tempfile.TemporaryDirectory() as tmp_dir:
  944. self.assertIsInstance(
  945. mail.get_connection(
  946. "django.core.mail.backends.filebased.EmailBackend",
  947. file_path=tmp_dir,
  948. ),
  949. filebased.EmailBackend,
  950. )
  951. msg = " not object"
  952. with self.assertRaisesMessage(TypeError, msg):
  953. mail.get_connection(
  954. "django.core.mail.backends.filebased.EmailBackend", file_path=object()
  955. )
  956. self.assertIsInstance(mail.get_connection(), locmem.EmailBackend)
  957. @override_settings(
  958. EMAIL_BACKEND="django.core.mail.backends.locmem.EmailBackend",
  959. ADMINS=[("nobody", "nobody@example.com")],
  960. MANAGERS=[("nobody", "nobody@example.com")],
  961. )
  962. def test_connection_arg(self):
  963. """Test connection argument to send_mail(), et. al."""
  964. mail.outbox = []
  965. # Send using non-default connection
  966. connection = mail.get_connection("mail.custombackend.EmailBackend")
  967. send_mail(
  968. "Subject",
  969. "Content",
  970. "from@example.com",
  971. ["to@example.com"],
  972. connection=connection,
  973. )
  974. self.assertEqual(mail.outbox, [])
  975. self.assertEqual(len(connection.test_outbox), 1)
  976. self.assertEqual(connection.test_outbox[0].subject, "Subject")
  977. connection = mail.get_connection("mail.custombackend.EmailBackend")
  978. send_mass_mail(
  979. [
  980. ("Subject1", "Content1", "from1@example.com", ["to1@example.com"]),
  981. ("Subject2", "Content2", "from2@example.com", ["to2@example.com"]),
  982. ],
  983. connection=connection,
  984. )
  985. self.assertEqual(mail.outbox, [])
  986. self.assertEqual(len(connection.test_outbox), 2)
  987. self.assertEqual(connection.test_outbox[0].subject, "Subject1")
  988. self.assertEqual(connection.test_outbox[1].subject, "Subject2")
  989. connection = mail.get_connection("mail.custombackend.EmailBackend")
  990. mail_admins("Admin message", "Content", connection=connection)
  991. self.assertEqual(mail.outbox, [])
  992. self.assertEqual(len(connection.test_outbox), 1)
  993. self.assertEqual(connection.test_outbox[0].subject, "[Django] Admin message")
  994. connection = mail.get_connection("mail.custombackend.EmailBackend")
  995. mail_managers("Manager message", "Content", connection=connection)
  996. self.assertEqual(mail.outbox, [])
  997. self.assertEqual(len(connection.test_outbox), 1)
  998. self.assertEqual(connection.test_outbox[0].subject, "[Django] Manager message")
  999. def test_dont_mangle_from_in_body(self):
  1000. # Regression for #13433 - Make sure that EmailMessage doesn't mangle
  1001. # 'From ' in message body.
  1002. email = EmailMessage(body="From the future")
  1003. self.assertNotIn(b">From the future", email.message().as_bytes())
  1004. def test_body_content_transfer_encoding(self):
  1005. # Shouldn't use base64 or quoted-printable, instead should detect it
  1006. # can represent content with 7-bit data (#3472, #11212).
  1007. msg = EmailMessage(body="Body with only ASCII characters.")
  1008. s = msg.message().as_bytes()
  1009. self.assertIn(b"Content-Transfer-Encoding: 7bit", s)
  1010. # Shouldn't use base64 or quoted-printable, instead should detect
  1011. # it can represent content with 8-bit data.
  1012. msg = EmailMessage(body="Body with latin characters: àáä.")
  1013. s = msg.message().as_bytes()
  1014. self.assertIn(b"Content-Transfer-Encoding: 8bit", s)
  1015. # The following test is left over from Python 2 and can be safely removed.
  1016. # 8bit CTE within a Unicode str is not meaningful, and Python's modern
  1017. # email api won't generate it. (The test still works with the legacy api.)
  1018. s = msg.message().as_string()
  1019. self.assertIn("Content-Transfer-Encoding: 8bit", s)
  1020. # Long body lines that require folding should use quoted-printable or base64,
  1021. # whichever is shorter. However, Python's legacy email API avoids re-folding
  1022. # non-ASCII text and just uses CTE 8bit. (The modern API would correctly choose
  1023. # base64 here. Any of these is deliverable.)
  1024. msg = EmailMessage(
  1025. "Subject",
  1026. "Body with non latin characters: А Б В Г Д Е Ж Ѕ З И І К Л М Н О П.",
  1027. "bounce@example.com",
  1028. ["to@example.com"],
  1029. headers={"From": "from@example.com"},
  1030. )
  1031. s = msg.message().as_bytes()
  1032. self.assertIn(b"Content-Transfer-Encoding: 8bit", s)
  1033. # The following test is left over from Python 2.
  1034. s = msg.message().as_string()
  1035. self.assertIn("Content-Transfer-Encoding: 8bit", s)
  1036. def test_custom_utf8_encoding(self):
  1037. """A UTF-8 charset with a custom body encoding is respected."""
  1038. body = "Body with latin characters: àáä."
  1039. msg = EmailMessage("Subject", body, "bounce@example.com", ["to@example.com"])
  1040. encoding = charset.Charset("utf-8")
  1041. encoding.body_encoding = charset.QP
  1042. msg.encoding = encoding
  1043. message = msg.message()
  1044. self.assertMessageHasHeaders(
  1045. message,
  1046. {
  1047. ("MIME-Version", "1.0"),
  1048. ("Content-Type", 'text/plain; charset="utf-8"'),
  1049. ("Content-Transfer-Encoding", "quoted-printable"),
  1050. },
  1051. )
  1052. self.assertEqual(message.get_payload(), encoding.body_encode(body))
  1053. def test_sanitize_address(self):
  1054. """Email addresses are properly sanitized."""
  1055. for email_address, encoding, expected_result in (
  1056. # ASCII addresses.
  1057. ("to@example.com", "ascii", "to@example.com"),
  1058. ("to@example.com", "utf-8", "to@example.com"),
  1059. (("A name", "to@example.com"), "ascii", "A name <to@example.com>"),
  1060. (
  1061. ("A name", "to@example.com"),
  1062. "utf-8",
  1063. "A name <to@example.com>",
  1064. ),
  1065. ("localpartonly", "ascii", "localpartonly"),
  1066. # ASCII addresses with display names.
  1067. ("A name <to@example.com>", "ascii", "A name <to@example.com>"),
  1068. ("A name <to@example.com>", "utf-8", "A name <to@example.com>"),
  1069. ('"A name" <to@example.com>', "ascii", "A name <to@example.com>"),
  1070. ('"A name" <to@example.com>', "utf-8", "A name <to@example.com>"),
  1071. # Unicode addresses: IDNA encoded domain supported per RFC-5890.
  1072. ("to@éxample.com", "utf-8", "to@xn--xample-9ua.com"),
  1073. # The next three cases should be removed when fixing #35713.
  1074. # (An 'encoded-word' localpart is prohibited by RFC-2047, and not
  1075. # supported by any known mail service.)
  1076. ("tó@example.com", "utf-8", "=?utf-8?b?dMOz?=@example.com"),
  1077. (
  1078. ("Tó Example", "tó@example.com"),
  1079. "utf-8",
  1080. "=?utf-8?q?T=C3=B3_Example?= <=?utf-8?b?dMOz?=@example.com>",
  1081. ),
  1082. (
  1083. "Tó Example <tó@example.com>",
  1084. "utf-8",
  1085. "=?utf-8?q?T=C3=B3_Example?= <=?utf-8?b?dMOz?=@example.com>",
  1086. ),
  1087. # IDNA addresses with display names.
  1088. (
  1089. "To Example <to@éxample.com>",
  1090. "ascii",
  1091. "To Example <to@xn--xample-9ua.com>",
  1092. ),
  1093. (
  1094. "To Example <to@éxample.com>",
  1095. "utf-8",
  1096. "To Example <to@xn--xample-9ua.com>",
  1097. ),
  1098. # Addresses with two @ signs.
  1099. ('"to@other.com"@example.com', "utf-8", r'"to@other.com"@example.com'),
  1100. (
  1101. '"to@other.com" <to@example.com>',
  1102. "utf-8",
  1103. '"to@other.com" <to@example.com>',
  1104. ),
  1105. (
  1106. ("To Example", "to@other.com@example.com"),
  1107. "utf-8",
  1108. 'To Example <"to@other.com"@example.com>',
  1109. ),
  1110. # Addresses with long unicode display names.
  1111. (
  1112. "Tó Example very long" * 4 + " <to@example.com>",
  1113. "utf-8",
  1114. "=?utf-8?q?T=C3=B3_Example_very_longT=C3=B3_Example_very_longT"
  1115. "=C3=B3_Example_?=\n"
  1116. " =?utf-8?q?very_longT=C3=B3_Example_very_long?= "
  1117. "<to@example.com>",
  1118. ),
  1119. (
  1120. ("Tó Example very long" * 4, "to@example.com"),
  1121. "utf-8",
  1122. "=?utf-8?q?T=C3=B3_Example_very_longT=C3=B3_Example_very_longT"
  1123. "=C3=B3_Example_?=\n"
  1124. " =?utf-8?q?very_longT=C3=B3_Example_very_long?= "
  1125. "<to@example.com>",
  1126. ),
  1127. # Address with long display name and unicode domain.
  1128. (
  1129. ("To Example very long" * 4, "to@exampl€.com"),
  1130. "utf-8",
  1131. "To Example very longTo Example very longTo Example very longT"
  1132. "o Example very\n"
  1133. " long <to@xn--exampl-nc1c.com>",
  1134. ),
  1135. ):
  1136. with self.subTest(email_address=email_address, encoding=encoding):
  1137. self.assertEqual(
  1138. sanitize_address(email_address, encoding), expected_result
  1139. )
  1140. def test_sanitize_address_invalid(self):
  1141. for email_address in (
  1142. # Invalid address with two @ signs.
  1143. "to@other.com@example.com",
  1144. # Invalid address without the quotes.
  1145. "to@other.com <to@example.com>",
  1146. # Other invalid addresses.
  1147. "@",
  1148. "to@",
  1149. "@example.com",
  1150. ("", ""),
  1151. ):
  1152. with self.subTest(email_address=email_address):
  1153. with self.assertRaisesMessage(ValueError, "Invalid address"):
  1154. sanitize_address(email_address, encoding="utf-8")
  1155. def test_sanitize_address_header_injection(self):
  1156. msg = "Invalid address; address parts cannot contain newlines."
  1157. tests = [
  1158. "Name\nInjection <to@example.com>",
  1159. ("Name\nInjection", "to@xample.com"),
  1160. "Name <to\ninjection@example.com>",
  1161. ("Name", "to\ninjection@example.com"),
  1162. ]
  1163. for email_address in tests:
  1164. with self.subTest(email_address=email_address):
  1165. with self.assertRaisesMessage(ValueError, msg):
  1166. sanitize_address(email_address, encoding="utf-8")
  1167. def test_email_multi_alternatives_content_mimetype_none(self):
  1168. email_msg = EmailMultiAlternatives()
  1169. msg = "Both content and mimetype must be provided."
  1170. with self.assertRaisesMessage(ValueError, msg):
  1171. email_msg.attach_alternative(None, "text/html")
  1172. with self.assertRaisesMessage(ValueError, msg):
  1173. email_msg.attach_alternative("<p>content</p>", None)
  1174. def test_mime_structure(self):
  1175. """
  1176. Check generated messages have the expected MIME parts and nesting.
  1177. """
  1178. html_body = EmailAlternative("<p>HTML</p>", "text/html")
  1179. image = EmailAttachment("image.gif", b"\x89PNG...", "image/png")
  1180. rfc822_attachment = EmailAttachment(
  1181. None, EmailMessage(body="text"), "message/rfc822"
  1182. )
  1183. cases = [
  1184. # name, email (EmailMessage or subclass), expected structure
  1185. (
  1186. "single body",
  1187. EmailMessage(body="text"),
  1188. """
  1189. text/plain
  1190. """,
  1191. ),
  1192. (
  1193. "single body with attachment",
  1194. EmailMessage(body="text", attachments=[image]),
  1195. """
  1196. multipart/mixed
  1197. text/plain
  1198. image/png
  1199. """,
  1200. ),
  1201. (
  1202. "alternative bodies",
  1203. EmailMultiAlternatives(body="text", alternatives=[html_body]),
  1204. """
  1205. multipart/alternative
  1206. text/plain
  1207. text/html
  1208. """,
  1209. ),
  1210. (
  1211. "alternative bodies with attachments",
  1212. EmailMultiAlternatives(
  1213. body="text", alternatives=[html_body], attachments=[image]
  1214. ),
  1215. """
  1216. multipart/mixed
  1217. multipart/alternative
  1218. text/plain
  1219. text/html
  1220. image/png
  1221. """,
  1222. ),
  1223. (
  1224. "alternative bodies with rfc822 attachment",
  1225. EmailMultiAlternatives(
  1226. body="text",
  1227. alternatives=[html_body],
  1228. attachments=[rfc822_attachment],
  1229. ),
  1230. """
  1231. multipart/mixed
  1232. multipart/alternative
  1233. text/plain
  1234. text/html
  1235. message/rfc822
  1236. text/plain
  1237. """,
  1238. ),
  1239. (
  1240. "attachment only",
  1241. EmailMessage(attachments=[image]),
  1242. # Avoid empty text/plain body.
  1243. """
  1244. multipart/mixed
  1245. image/png
  1246. """,
  1247. ),
  1248. (
  1249. "alternative only",
  1250. EmailMultiAlternatives(alternatives=[html_body]),
  1251. # Avoid empty text/plain body.
  1252. """
  1253. multipart/alternative
  1254. text/html
  1255. """,
  1256. ),
  1257. (
  1258. "alternative and attachment only",
  1259. EmailMultiAlternatives(alternatives=[html_body], attachments=[image]),
  1260. """
  1261. multipart/mixed
  1262. multipart/alternative
  1263. text/html
  1264. image/png
  1265. """,
  1266. ),
  1267. (
  1268. "empty EmailMessage",
  1269. EmailMessage(),
  1270. """
  1271. text/plain
  1272. """,
  1273. ),
  1274. (
  1275. "empty EmailMultiAlternatives",
  1276. EmailMultiAlternatives(),
  1277. """
  1278. text/plain
  1279. """,
  1280. ),
  1281. ]
  1282. for name, email, expected in cases:
  1283. expected = dedent(expected).lstrip()
  1284. with self.subTest(name=name):
  1285. message = email.message()
  1286. structure = self.get_message_structure(message)
  1287. self.assertEqual(structure, expected)
  1288. def test_body_contains(self):
  1289. email_msg = EmailMultiAlternatives()
  1290. email_msg.body = "I am content."
  1291. self.assertIs(email_msg.body_contains("I am"), True)
  1292. self.assertIs(email_msg.body_contains("I am content."), True)
  1293. email_msg.attach_alternative("<p>I am different content.</p>", "text/html")
  1294. self.assertIs(email_msg.body_contains("I am"), True)
  1295. self.assertIs(email_msg.body_contains("I am content."), False)
  1296. self.assertIs(email_msg.body_contains("<p>I am different content.</p>"), False)
  1297. def test_body_contains_alternative_non_text(self):
  1298. email_msg = EmailMultiAlternatives()
  1299. email_msg.body = "I am content."
  1300. email_msg.attach_alternative("I am content.", "text/html")
  1301. email_msg.attach_alternative(b"I am a song.", "audio/mpeg")
  1302. self.assertIs(email_msg.body_contains("I am content"), True)
  1303. def test_all_params_optional(self):
  1304. """
  1305. EmailMessage class docs: "All parameters are optional"
  1306. """
  1307. email = EmailMessage()
  1308. self.assertIsInstance(email.message(), PyMessage) # force serialization.
  1309. email = EmailMultiAlternatives()
  1310. self.assertIsInstance(email.message(), PyMessage) # force serialization.
  1311. def test_positional_arguments_order(self):
  1312. """
  1313. EmailMessage class docs: "… is initialized with the following parameters
  1314. (in the given order, if positional arguments are used)."
  1315. """
  1316. connection = mail.get_connection()
  1317. email = EmailMessage(
  1318. # (If you need to insert/remove/reorder any params here,
  1319. # that indicates a breaking change to documented behavior.)
  1320. "subject",
  1321. "body",
  1322. "from@example.com",
  1323. ["to@example.com"],
  1324. ["bcc@example.com"],
  1325. connection,
  1326. [EmailAttachment("file.txt", "attachment", "text/plain")],
  1327. {"X-Header": "custom header"},
  1328. ["cc@example.com"],
  1329. ["reply-to@example.com"],
  1330. # (New options can be added below here, ideally as keyword-only args.)
  1331. )
  1332. message = email.message()
  1333. self.assertEqual(message.get_all("Subject"), ["subject"])
  1334. self.assertEqual(message.get_all("From"), ["from@example.com"])
  1335. self.assertEqual(message.get_all("To"), ["to@example.com"])
  1336. self.assertEqual(message.get_all("X-Header"), ["custom header"])
  1337. self.assertEqual(message.get_all("Cc"), ["cc@example.com"])
  1338. self.assertEqual(message.get_all("Reply-To"), ["reply-to@example.com"])
  1339. self.assertEqual(message.get_payload(0).get_payload(), "body")
  1340. self.assertEqual(
  1341. self.get_decoded_attachments(email),
  1342. [("file.txt", "attachment", "text/plain")],
  1343. )
  1344. self.assertEqual(
  1345. email.recipients(), ["to@example.com", "cc@example.com", "bcc@example.com"]
  1346. )
  1347. self.assertIs(email.get_connection(), connection)
  1348. def test_all_params_can_be_set_before_send(self):
  1349. """
  1350. EmailMessage class docs: "All parameters … can be set at any time
  1351. prior to calling the send() method."
  1352. """
  1353. # This is meant to verify EmailMessage.__init__() doesn't apply any
  1354. # special processing that would be missing for properties set later.
  1355. original_connection = mail.get_connection(username="original")
  1356. new_connection = mail.get_connection(username="new")
  1357. email = EmailMessage(
  1358. "original subject",
  1359. "original body",
  1360. "original-from@example.com",
  1361. ["original-to@example.com"],
  1362. ["original-bcc@example.com"],
  1363. original_connection,
  1364. [EmailAttachment("original.txt", "original attachment", "text/plain")],
  1365. {"X-Header": "original header"},
  1366. ["original-cc@example.com"],
  1367. ["original-reply-to@example.com"],
  1368. )
  1369. email.subject = "new subject"
  1370. email.body = "new body"
  1371. email.from_email = "new-from@example.com"
  1372. email.to = ["new-to@example.com"]
  1373. email.bcc = ["new-bcc@example.com"]
  1374. email.connection = new_connection
  1375. email.attachments = [
  1376. ("new1.txt", "new attachment 1", "text/plain"), # plain tuple.
  1377. EmailAttachment("new2.txt", "new attachment 2", "text/csv"),
  1378. MIMEImage(b"GIF89a...", "gif"),
  1379. ]
  1380. email.extra_headers = {"X-Header": "new header"}
  1381. email.cc = ["new-cc@example.com"]
  1382. email.reply_to = ["new-reply-to@example.com"]
  1383. message = email.message()
  1384. self.assertEqual(message.get_all("Subject"), ["new subject"])
  1385. self.assertEqual(message.get_all("From"), ["new-from@example.com"])
  1386. self.assertEqual(message.get_all("To"), ["new-to@example.com"])
  1387. self.assertEqual(message.get_all("X-Header"), ["new header"])
  1388. self.assertEqual(message.get_all("Cc"), ["new-cc@example.com"])
  1389. self.assertEqual(message.get_all("Reply-To"), ["new-reply-to@example.com"])
  1390. self.assertEqual(message.get_payload(0).get_payload(), "new body")
  1391. self.assertEqual(
  1392. self.get_decoded_attachments(email),
  1393. [
  1394. ("new1.txt", "new attachment 1", "text/plain"),
  1395. ("new2.txt", "new attachment 2", "text/csv"),
  1396. (None, b"GIF89a...", "image/gif"),
  1397. ],
  1398. )
  1399. self.assertEqual(
  1400. email.recipients(),
  1401. ["new-to@example.com", "new-cc@example.com", "new-bcc@example.com"],
  1402. )
  1403. self.assertIs(email.get_connection(), new_connection)
  1404. self.assertNotIn("original", message.as_string())
  1405. @requires_tz_support
  1406. class MailTimeZoneTests(MailTestsMixin, SimpleTestCase):
  1407. @override_settings(
  1408. EMAIL_USE_LOCALTIME=False, USE_TZ=True, TIME_ZONE="Africa/Algiers"
  1409. )
  1410. def test_date_header_utc(self):
  1411. """
  1412. EMAIL_USE_LOCALTIME=False creates a datetime in UTC.
  1413. """
  1414. email = EmailMessage()
  1415. self.assertEndsWith(email.message()["Date"], "-0000")
  1416. @override_settings(
  1417. EMAIL_USE_LOCALTIME=True, USE_TZ=True, TIME_ZONE="Africa/Algiers"
  1418. )
  1419. def test_date_header_localtime(self):
  1420. """
  1421. EMAIL_USE_LOCALTIME=True creates a datetime in the local time zone.
  1422. """
  1423. email = EmailMessage()
  1424. # Africa/Algiers is UTC+1 year round.
  1425. self.assertEndsWith(email.message()["Date"], "+0100")
  1426. class PythonGlobalState(SimpleTestCase):
  1427. """
  1428. Tests for #12422 -- Django smarts (#2472/#11212) with charset of utf-8 text
  1429. parts shouldn't pollute global email Python package charset registry when
  1430. django.mail.message is imported.
  1431. """
  1432. def test_utf8(self):
  1433. txt = MIMEText("UTF-8 encoded body", "plain", "utf-8")
  1434. self.assertIn("Content-Transfer-Encoding: base64", txt.as_string())
  1435. def test_7bit(self):
  1436. txt = MIMEText("Body with only ASCII characters.", "plain", "utf-8")
  1437. self.assertIn("Content-Transfer-Encoding: base64", txt.as_string())
  1438. def test_8bit_latin(self):
  1439. txt = MIMEText("Body with latin characters: àáä.", "plain", "utf-8")
  1440. self.assertIn("Content-Transfer-Encoding: base64", txt.as_string())
  1441. def test_8bit_non_latin(self):
  1442. txt = MIMEText(
  1443. "Body with non latin characters: А Б В Г Д Е Ж Ѕ З И І К Л М Н О П.",
  1444. "plain",
  1445. "utf-8",
  1446. )
  1447. self.assertIn("Content-Transfer-Encoding: base64", txt.as_string())
  1448. class BaseEmailBackendTests(MailTestsMixin):
  1449. email_backend = None
  1450. @classmethod
  1451. def setUpClass(cls):
  1452. cls.enterClassContext(override_settings(EMAIL_BACKEND=cls.email_backend))
  1453. super().setUpClass()
  1454. def get_mailbox_content(self):
  1455. raise NotImplementedError(
  1456. "subclasses of BaseEmailBackendTests must provide a get_mailbox_content() "
  1457. "method"
  1458. )
  1459. def flush_mailbox(self):
  1460. raise NotImplementedError(
  1461. "subclasses of BaseEmailBackendTests may require a flush_mailbox() method"
  1462. )
  1463. def get_the_message(self):
  1464. mailbox = self.get_mailbox_content()
  1465. self.assertEqual(
  1466. len(mailbox),
  1467. 1,
  1468. "Expected exactly one message, got %d.\n%r"
  1469. % (len(mailbox), [m.as_string() for m in mailbox]),
  1470. )
  1471. return mailbox[0]
  1472. def test_send(self):
  1473. email = EmailMessage(
  1474. "Subject", "Content", "from@example.com", ["to@example.com"]
  1475. )
  1476. num_sent = mail.get_connection().send_messages([email])
  1477. self.assertEqual(num_sent, 1)
  1478. message = self.get_the_message()
  1479. self.assertEqual(message["subject"], "Subject")
  1480. self.assertEqual(message.get_payload(), "Content")
  1481. self.assertEqual(message["from"], "from@example.com")
  1482. self.assertEqual(message.get_all("to"), ["to@example.com"])
  1483. def test_send_unicode(self):
  1484. email = EmailMessage(
  1485. "Chère maman", "Je t'aime très fort", "from@example.com", ["to@example.com"]
  1486. )
  1487. num_sent = mail.get_connection().send_messages([email])
  1488. self.assertEqual(num_sent, 1)
  1489. message = self.get_the_message()
  1490. self.assertEqual(message["subject"], "Chère maman")
  1491. self.assertIn(b"Subject: =?utf-8?q?Ch=C3=A8re_maman?=", message.as_bytes())
  1492. self.assertEqual(message.get_content(), "Je t'aime très fort")
  1493. def test_send_long_lines(self):
  1494. """
  1495. Email line length is limited to 998 chars by the RFC 5322 Section
  1496. 2.1.1.
  1497. Message body containing longer lines are converted to Quoted-Printable
  1498. to avoid having to insert newlines, which could be hairy to do properly.
  1499. """
  1500. # Unencoded body length is < 998 (840) but > 998 when utf-8 encoded.
  1501. email = EmailMessage(
  1502. "Subject", "В южных морях " * 60, "from@example.com", ["to@example.com"]
  1503. )
  1504. email.send()
  1505. message = self.get_the_message()
  1506. self.assertMessageHasHeaders(
  1507. message,
  1508. {
  1509. ("MIME-Version", "1.0"),
  1510. ("Content-Type", 'text/plain; charset="utf-8"'),
  1511. ("Content-Transfer-Encoding", "quoted-printable"),
  1512. },
  1513. )
  1514. def test_send_many(self):
  1515. email1 = EmailMessage(to=["to-1@example.com"])
  1516. email2 = EmailMessage(to=["to-2@example.com"])
  1517. # send_messages() may take a list or an iterator.
  1518. emails_lists = ([email1, email2], iter((email1, email2)))
  1519. for emails_list in emails_lists:
  1520. with self.subTest(emails_list=repr(emails_list)):
  1521. num_sent = mail.get_connection().send_messages(emails_list)
  1522. self.assertEqual(num_sent, 2)
  1523. messages = self.get_mailbox_content()
  1524. self.assertEqual(len(messages), 2)
  1525. self.assertEqual(messages[0]["To"], "to-1@example.com")
  1526. self.assertEqual(messages[1]["To"], "to-2@example.com")
  1527. self.flush_mailbox()
  1528. def test_send_verbose_name(self):
  1529. email = EmailMessage(
  1530. from_email='"Firstname Sürname" <from@example.com>',
  1531. to=["to@example.com"],
  1532. )
  1533. email.send()
  1534. message = self.get_the_message()
  1535. self.assertEqual(message["from"], "Firstname Sürname <from@example.com>")
  1536. self.assertIn(
  1537. b"From: =?utf-8?q?Firstname_S=C3=BCrname?= <from@example.com>",
  1538. message.as_bytes(),
  1539. )
  1540. def test_plaintext_send_mail(self):
  1541. """
  1542. Test send_mail without the html_message
  1543. regression test for adding html_message parameter to send_mail()
  1544. """
  1545. send_mail("Subject", "Content", "sender@example.com", ["nobody@example.com"])
  1546. message = self.get_the_message()
  1547. self.assertEqual(message.get("subject"), "Subject")
  1548. self.assertEqual(message.get_all("to"), ["nobody@example.com"])
  1549. self.assertFalse(message.is_multipart())
  1550. self.assertEqual(message.get_payload(), "Content")
  1551. self.assertEqual(message.get_content_type(), "text/plain")
  1552. def test_html_send_mail(self):
  1553. """Test html_message argument to send_mail"""
  1554. send_mail(
  1555. "Subject",
  1556. "Content",
  1557. "sender@example.com",
  1558. ["nobody@example.com"],
  1559. html_message="HTML Content",
  1560. )
  1561. message = self.get_the_message()
  1562. self.assertEqual(message.get("subject"), "Subject")
  1563. self.assertEqual(message.get_all("to"), ["nobody@example.com"])
  1564. self.assertTrue(message.is_multipart())
  1565. self.assertEqual(len(message.get_payload()), 2)
  1566. self.assertEqual(message.get_payload(0).get_payload(), "Content")
  1567. self.assertEqual(message.get_payload(0).get_content_type(), "text/plain")
  1568. self.assertEqual(message.get_payload(1).get_payload(), "HTML Content")
  1569. self.assertEqual(message.get_payload(1).get_content_type(), "text/html")
  1570. @override_settings(MANAGERS=[("nobody", "nobody@example.com")])
  1571. def test_html_mail_managers(self):
  1572. """Test html_message argument to mail_managers"""
  1573. mail_managers("Subject", "Content", html_message="HTML Content")
  1574. message = self.get_the_message()
  1575. self.assertEqual(message.get("subject"), "[Django] Subject")
  1576. self.assertEqual(message.get_all("to"), ["nobody@example.com"])
  1577. self.assertTrue(message.is_multipart())
  1578. self.assertEqual(len(message.get_payload()), 2)
  1579. self.assertEqual(message.get_payload(0).get_payload(), "Content")
  1580. self.assertEqual(message.get_payload(0).get_content_type(), "text/plain")
  1581. self.assertEqual(message.get_payload(1).get_payload(), "HTML Content")
  1582. self.assertEqual(message.get_payload(1).get_content_type(), "text/html")
  1583. @override_settings(ADMINS=[("nobody", "nobody@example.com")])
  1584. def test_html_mail_admins(self):
  1585. """Test html_message argument to mail_admins"""
  1586. mail_admins("Subject", "Content", html_message="HTML Content")
  1587. message = self.get_the_message()
  1588. self.assertEqual(message.get("subject"), "[Django] Subject")
  1589. self.assertEqual(message.get_all("to"), ["nobody@example.com"])
  1590. self.assertTrue(message.is_multipart())
  1591. self.assertEqual(len(message.get_payload()), 2)
  1592. self.assertEqual(message.get_payload(0).get_payload(), "Content")
  1593. self.assertEqual(message.get_payload(0).get_content_type(), "text/plain")
  1594. self.assertEqual(message.get_payload(1).get_payload(), "HTML Content")
  1595. self.assertEqual(message.get_payload(1).get_content_type(), "text/html")
  1596. @override_settings(
  1597. ADMINS=[("nobody", "nobody+admin@example.com")],
  1598. MANAGERS=[("nobody", "nobody+manager@example.com")],
  1599. )
  1600. def test_manager_and_admin_mail_prefix(self):
  1601. """
  1602. String prefix + lazy translated subject = bad output
  1603. Regression for #13494
  1604. """
  1605. mail_managers(gettext_lazy("Subject"), "Content")
  1606. message = self.get_the_message()
  1607. self.assertEqual(message.get("subject"), "[Django] Subject")
  1608. self.flush_mailbox()
  1609. mail_admins(gettext_lazy("Subject"), "Content")
  1610. message = self.get_the_message()
  1611. self.assertEqual(message.get("subject"), "[Django] Subject")
  1612. @override_settings(ADMINS=[], MANAGERS=[])
  1613. def test_empty_admins(self):
  1614. """
  1615. mail_admins/mail_managers doesn't connect to the mail server
  1616. if there are no recipients (#9383)
  1617. """
  1618. mail_admins("hi", "there")
  1619. self.assertEqual(self.get_mailbox_content(), [])
  1620. mail_managers("hi", "there")
  1621. self.assertEqual(self.get_mailbox_content(), [])
  1622. def test_wrong_admins_managers(self):
  1623. tests = (
  1624. "test@example.com",
  1625. ("test@example.com",),
  1626. ["test@example.com", "other@example.com"],
  1627. ("test@example.com", "other@example.com"),
  1628. )
  1629. for setting, mail_func in (
  1630. ("ADMINS", mail_admins),
  1631. ("MANAGERS", mail_managers),
  1632. ):
  1633. msg = "The %s setting must be a list of 2-tuples." % setting
  1634. for value in tests:
  1635. with (
  1636. self.subTest(setting=setting, value=value),
  1637. self.settings(**{setting: value}),
  1638. ):
  1639. with self.assertRaisesMessage(ValueError, msg):
  1640. mail_func("subject", "content")
  1641. def test_message_cc_header(self):
  1642. """
  1643. Regression test for #7722
  1644. """
  1645. email = EmailMessage(
  1646. "Subject",
  1647. "Content",
  1648. "from@example.com",
  1649. ["to@example.com"],
  1650. cc=["cc@example.com"],
  1651. )
  1652. mail.get_connection().send_messages([email])
  1653. message = self.get_the_message()
  1654. self.assertMessageHasHeaders(
  1655. message,
  1656. {
  1657. ("MIME-Version", "1.0"),
  1658. ("Content-Type", 'text/plain; charset="utf-8"'),
  1659. ("Content-Transfer-Encoding", "7bit"),
  1660. ("Subject", "Subject"),
  1661. ("From", "from@example.com"),
  1662. ("To", "to@example.com"),
  1663. ("Cc", "cc@example.com"),
  1664. },
  1665. )
  1666. self.assertIn("\nDate: ", message.as_string())
  1667. def test_idn_send(self):
  1668. """
  1669. Regression test for #14301
  1670. """
  1671. self.assertTrue(send_mail("Subject", "Content", "from@öäü.com", ["to@öäü.com"]))
  1672. message = self.get_the_message()
  1673. self.assertEqual(message.get("from"), "from@xn--4ca9at.com")
  1674. self.assertEqual(message.get("to"), "to@xn--4ca9at.com")
  1675. self.flush_mailbox()
  1676. m = EmailMessage(
  1677. from_email="from@öäü.com", to=["to@öäü.com"], cc=["cc@öäü.com"]
  1678. )
  1679. m.send()
  1680. message = self.get_the_message()
  1681. self.assertEqual(message.get("from"), "from@xn--4ca9at.com")
  1682. self.assertEqual(message.get("to"), "to@xn--4ca9at.com")
  1683. self.assertEqual(message.get("cc"), "cc@xn--4ca9at.com")
  1684. def test_recipient_without_domain(self):
  1685. """
  1686. Regression test for #15042
  1687. """
  1688. self.assertTrue(send_mail("Subject", "Content", "tester", ["django"]))
  1689. message = self.get_the_message()
  1690. self.assertEqual(message.get("from"), "tester")
  1691. self.assertEqual(message.get("to"), "django")
  1692. def test_lazy_addresses(self):
  1693. """
  1694. Email sending should support lazy email addresses (#24416).
  1695. """
  1696. _ = gettext_lazy
  1697. self.assertTrue(send_mail("Subject", "Content", _("tester"), [_("django")]))
  1698. message = self.get_the_message()
  1699. self.assertEqual(message.get("from"), "tester")
  1700. self.assertEqual(message.get("to"), "django")
  1701. self.flush_mailbox()
  1702. m = EmailMessage(
  1703. from_email=_("tester"),
  1704. to=[_("to1"), _("to2")],
  1705. cc=[_("cc1"), _("cc2")],
  1706. bcc=[_("bcc")],
  1707. reply_to=[_("reply")],
  1708. )
  1709. self.assertEqual(m.recipients(), ["to1", "to2", "cc1", "cc2", "bcc"])
  1710. m.send()
  1711. message = self.get_the_message()
  1712. self.assertEqual(message.get("from"), "tester")
  1713. self.assertEqual(message.get("to"), "to1, to2")
  1714. self.assertEqual(message.get("cc"), "cc1, cc2")
  1715. self.assertEqual(message.get("Reply-To"), "reply")
  1716. def test_close_connection(self):
  1717. """
  1718. Connection can be closed (even when not explicitly opened)
  1719. """
  1720. conn = mail.get_connection(username="", password="")
  1721. conn.close()
  1722. def test_use_as_contextmanager(self):
  1723. """
  1724. The connection can be used as a contextmanager.
  1725. """
  1726. opened = [False]
  1727. closed = [False]
  1728. conn = mail.get_connection(username="", password="")
  1729. def open():
  1730. opened[0] = True
  1731. conn.open = open
  1732. def close():
  1733. closed[0] = True
  1734. conn.close = close
  1735. with conn as same_conn:
  1736. self.assertTrue(opened[0])
  1737. self.assertIs(same_conn, conn)
  1738. self.assertFalse(closed[0])
  1739. self.assertTrue(closed[0])
  1740. class LocmemBackendTests(BaseEmailBackendTests, SimpleTestCase):
  1741. email_backend = "django.core.mail.backends.locmem.EmailBackend"
  1742. def get_mailbox_content(self):
  1743. # Reparse as modern messages to work with shared BaseEmailBackendTests.
  1744. # (Once EmailMessage.message() uses Python's modern email API, this
  1745. # can be changed back to `[m.message() for m in mail.outbox]`.)
  1746. return [message_from_bytes(m.message().as_bytes()) for m in mail.outbox]
  1747. def flush_mailbox(self):
  1748. mail.outbox = []
  1749. def tearDown(self):
  1750. super().tearDown()
  1751. mail.outbox = []
  1752. def test_locmem_shared_messages(self):
  1753. """
  1754. Make sure that the locmen backend populates the outbox.
  1755. """
  1756. connection = locmem.EmailBackend()
  1757. connection2 = locmem.EmailBackend()
  1758. email = EmailMessage(to=["to@example.com"])
  1759. connection.send_messages([email])
  1760. connection2.send_messages([email])
  1761. self.assertEqual(len(mail.outbox), 2)
  1762. def test_validate_multiline_headers(self):
  1763. # Ticket #18861 - Validate emails when using the locmem backend
  1764. with self.assertRaises(BadHeaderError):
  1765. send_mail(
  1766. "Subject\nMultiline", "Content", "from@example.com", ["to@example.com"]
  1767. )
  1768. def test_outbox_not_mutated_after_send(self):
  1769. email = EmailMessage(
  1770. subject="correct subject",
  1771. to=["to@example.com"],
  1772. )
  1773. email.send()
  1774. email.subject = "other subject"
  1775. email.to.append("other@example.com")
  1776. self.assertEqual(mail.outbox[0].subject, "correct subject")
  1777. self.assertEqual(mail.outbox[0].to, ["to@example.com"])
  1778. class FileBackendTests(BaseEmailBackendTests, SimpleTestCase):
  1779. email_backend = "django.core.mail.backends.filebased.EmailBackend"
  1780. def setUp(self):
  1781. super().setUp()
  1782. self.tmp_dir = self.mkdtemp()
  1783. self.addCleanup(shutil.rmtree, self.tmp_dir)
  1784. _settings_override = override_settings(EMAIL_FILE_PATH=self.tmp_dir)
  1785. _settings_override.enable()
  1786. self.addCleanup(_settings_override.disable)
  1787. def mkdtemp(self):
  1788. return tempfile.mkdtemp()
  1789. def flush_mailbox(self):
  1790. for filename in os.listdir(self.tmp_dir):
  1791. os.unlink(os.path.join(self.tmp_dir, filename))
  1792. def get_mailbox_content(self):
  1793. messages = []
  1794. for filename in os.listdir(self.tmp_dir):
  1795. with open(os.path.join(self.tmp_dir, filename), "rb") as fp:
  1796. session = fp.read().split(b"\n" + (b"-" * 79) + b"\n")
  1797. messages.extend(message_from_bytes(m) for m in session if m)
  1798. return messages
  1799. def test_file_sessions(self):
  1800. """Make sure opening a connection creates a new file"""
  1801. msg = EmailMessage(
  1802. "Subject",
  1803. "Content",
  1804. "bounce@example.com",
  1805. ["to@example.com"],
  1806. headers={"From": "from@example.com"},
  1807. )
  1808. connection = mail.get_connection()
  1809. connection.send_messages([msg])
  1810. self.assertEqual(len(os.listdir(self.tmp_dir)), 1)
  1811. with open(os.path.join(self.tmp_dir, os.listdir(self.tmp_dir)[0]), "rb") as fp:
  1812. message = message_from_binary_file(fp, policy=policy.default)
  1813. self.assertEqual(message.get_content_type(), "text/plain")
  1814. self.assertEqual(message.get("subject"), "Subject")
  1815. self.assertEqual(message.get("from"), "from@example.com")
  1816. self.assertEqual(message.get("to"), "to@example.com")
  1817. connection2 = mail.get_connection()
  1818. connection2.send_messages([msg])
  1819. self.assertEqual(len(os.listdir(self.tmp_dir)), 2)
  1820. connection.send_messages([msg])
  1821. self.assertEqual(len(os.listdir(self.tmp_dir)), 2)
  1822. msg.connection = mail.get_connection()
  1823. self.assertTrue(connection.open())
  1824. msg.send()
  1825. self.assertEqual(len(os.listdir(self.tmp_dir)), 3)
  1826. msg.send()
  1827. self.assertEqual(len(os.listdir(self.tmp_dir)), 3)
  1828. connection.close()
  1829. class FileBackendPathLibTests(FileBackendTests):
  1830. def mkdtemp(self):
  1831. tmp_dir = super().mkdtemp()
  1832. return Path(tmp_dir)
  1833. class ConsoleBackendTests(BaseEmailBackendTests, SimpleTestCase):
  1834. email_backend = "django.core.mail.backends.console.EmailBackend"
  1835. def setUp(self):
  1836. super().setUp()
  1837. self.__stdout = sys.stdout
  1838. self.stream = sys.stdout = StringIO()
  1839. def tearDown(self):
  1840. del self.stream
  1841. sys.stdout = self.__stdout
  1842. del self.__stdout
  1843. super().tearDown()
  1844. def flush_mailbox(self):
  1845. self.stream = sys.stdout = StringIO()
  1846. def get_mailbox_content(self):
  1847. messages = self.stream.getvalue().split("\n" + ("-" * 79) + "\n")
  1848. return [message_from_bytes(m.encode()) for m in messages if m]
  1849. def test_console_stream_kwarg(self):
  1850. """
  1851. The console backend can be pointed at an arbitrary stream.
  1852. """
  1853. s = StringIO()
  1854. connection = mail.get_connection(
  1855. "django.core.mail.backends.console.EmailBackend", stream=s
  1856. )
  1857. send_mail(
  1858. "Subject",
  1859. "Content",
  1860. "from@example.com",
  1861. ["to@example.com"],
  1862. connection=connection,
  1863. )
  1864. message = s.getvalue().split("\n" + ("-" * 79) + "\n")[0].encode()
  1865. self.assertMessageHasHeaders(
  1866. message,
  1867. {
  1868. ("MIME-Version", "1.0"),
  1869. ("Content-Type", 'text/plain; charset="utf-8"'),
  1870. ("Content-Transfer-Encoding", "7bit"),
  1871. ("Subject", "Subject"),
  1872. ("From", "from@example.com"),
  1873. ("To", "to@example.com"),
  1874. },
  1875. )
  1876. self.assertIn(b"\nDate: ", message)
  1877. class SMTPHandler:
  1878. def __init__(self, *args, **kwargs):
  1879. self.mailbox = []
  1880. self.smtp_envelopes = []
  1881. async def handle_DATA(self, server, session, envelope):
  1882. data = envelope.content
  1883. mail_from = envelope.mail_from
  1884. message = message_from_bytes(data.rstrip())
  1885. try:
  1886. header_from = message["from"].addresses[0].addr_spec
  1887. except (KeyError, IndexError):
  1888. header_from = None
  1889. if mail_from != header_from:
  1890. return f"553 '{mail_from}' != '{header_from}'"
  1891. self.mailbox.append(message)
  1892. self.smtp_envelopes.append(
  1893. {
  1894. "mail_from": envelope.mail_from,
  1895. "rcpt_tos": envelope.rcpt_tos,
  1896. }
  1897. )
  1898. return "250 OK"
  1899. def flush_mailbox(self):
  1900. self.mailbox[:] = []
  1901. self.smtp_envelopes[:] = []
  1902. @skipUnless(HAS_AIOSMTPD, "No aiosmtpd library detected.")
  1903. class SMTPBackendTestsBase(SimpleTestCase):
  1904. @classmethod
  1905. def setUpClass(cls):
  1906. super().setUpClass()
  1907. # Find a free port.
  1908. with socket.socket() as s:
  1909. s.bind(("127.0.0.1", 0))
  1910. port = s.getsockname()[1]
  1911. cls.smtp_handler = SMTPHandler()
  1912. cls.smtp_controller = Controller(
  1913. cls.smtp_handler,
  1914. hostname="127.0.0.1",
  1915. port=port,
  1916. )
  1917. cls._settings_override = override_settings(
  1918. EMAIL_HOST=cls.smtp_controller.hostname,
  1919. EMAIL_PORT=cls.smtp_controller.port,
  1920. )
  1921. cls._settings_override.enable()
  1922. cls.addClassCleanup(cls._settings_override.disable)
  1923. cls.smtp_controller.start()
  1924. cls.addClassCleanup(cls.stop_smtp)
  1925. @classmethod
  1926. def stop_smtp(cls):
  1927. cls.smtp_controller.stop()
  1928. @skipUnless(HAS_AIOSMTPD, "No aiosmtpd library detected.")
  1929. class SMTPBackendTests(BaseEmailBackendTests, SMTPBackendTestsBase):
  1930. email_backend = "django.core.mail.backends.smtp.EmailBackend"
  1931. def setUp(self):
  1932. super().setUp()
  1933. self.smtp_handler.flush_mailbox()
  1934. self.addCleanup(self.smtp_handler.flush_mailbox)
  1935. def flush_mailbox(self):
  1936. self.smtp_handler.flush_mailbox()
  1937. def get_mailbox_content(self):
  1938. return self.smtp_handler.mailbox
  1939. def get_smtp_envelopes(self):
  1940. return self.smtp_handler.smtp_envelopes
  1941. @override_settings(
  1942. EMAIL_HOST_USER="not empty username",
  1943. EMAIL_HOST_PASSWORD="not empty password",
  1944. )
  1945. def test_email_authentication_use_settings(self):
  1946. backend = smtp.EmailBackend()
  1947. self.assertEqual(backend.username, "not empty username")
  1948. self.assertEqual(backend.password, "not empty password")
  1949. @override_settings(
  1950. EMAIL_HOST_USER="not empty username",
  1951. EMAIL_HOST_PASSWORD="not empty password",
  1952. )
  1953. def test_email_authentication_override_settings(self):
  1954. backend = smtp.EmailBackend(username="username", password="password")
  1955. self.assertEqual(backend.username, "username")
  1956. self.assertEqual(backend.password, "password")
  1957. @override_settings(
  1958. EMAIL_HOST_USER="not empty username",
  1959. EMAIL_HOST_PASSWORD="not empty password",
  1960. )
  1961. def test_email_disabled_authentication(self):
  1962. backend = smtp.EmailBackend(username="", password="")
  1963. self.assertEqual(backend.username, "")
  1964. self.assertEqual(backend.password, "")
  1965. def test_auth_attempted(self):
  1966. """
  1967. Opening the backend with non empty username/password tries
  1968. to authenticate against the SMTP server.
  1969. """
  1970. backend = smtp.EmailBackend(
  1971. username="not empty username", password="not empty password"
  1972. )
  1973. with self.assertRaisesMessage(
  1974. SMTPException, "SMTP AUTH extension not supported by server."
  1975. ):
  1976. with backend:
  1977. pass
  1978. def test_server_open(self):
  1979. """
  1980. open() returns whether it opened a connection.
  1981. """
  1982. backend = smtp.EmailBackend(username="", password="")
  1983. self.assertIsNone(backend.connection)
  1984. opened = backend.open()
  1985. backend.close()
  1986. self.assertIs(opened, True)
  1987. def test_reopen_connection(self):
  1988. backend = smtp.EmailBackend()
  1989. # Simulate an already open connection.
  1990. backend.connection = mock.Mock(spec=object())
  1991. self.assertIs(backend.open(), False)
  1992. @override_settings(EMAIL_USE_TLS=True)
  1993. def test_email_tls_use_settings(self):
  1994. backend = smtp.EmailBackend()
  1995. self.assertTrue(backend.use_tls)
  1996. @override_settings(EMAIL_USE_TLS=True)
  1997. def test_email_tls_override_settings(self):
  1998. backend = smtp.EmailBackend(use_tls=False)
  1999. self.assertFalse(backend.use_tls)
  2000. def test_email_tls_default_disabled(self):
  2001. backend = smtp.EmailBackend()
  2002. self.assertFalse(backend.use_tls)
  2003. def test_ssl_tls_mutually_exclusive(self):
  2004. msg = (
  2005. "EMAIL_USE_TLS/EMAIL_USE_SSL are mutually exclusive, so only set "
  2006. "one of those settings to True."
  2007. )
  2008. with self.assertRaisesMessage(ValueError, msg):
  2009. smtp.EmailBackend(use_ssl=True, use_tls=True)
  2010. @override_settings(EMAIL_USE_SSL=True)
  2011. def test_email_ssl_use_settings(self):
  2012. backend = smtp.EmailBackend()
  2013. self.assertTrue(backend.use_ssl)
  2014. @override_settings(EMAIL_USE_SSL=True)
  2015. def test_email_ssl_override_settings(self):
  2016. backend = smtp.EmailBackend(use_ssl=False)
  2017. self.assertFalse(backend.use_ssl)
  2018. def test_email_ssl_default_disabled(self):
  2019. backend = smtp.EmailBackend()
  2020. self.assertFalse(backend.use_ssl)
  2021. @override_settings(EMAIL_SSL_CERTFILE="foo")
  2022. def test_email_ssl_certfile_use_settings(self):
  2023. backend = smtp.EmailBackend()
  2024. self.assertEqual(backend.ssl_certfile, "foo")
  2025. @override_settings(EMAIL_SSL_CERTFILE="foo")
  2026. def test_email_ssl_certfile_override_settings(self):
  2027. backend = smtp.EmailBackend(ssl_certfile="bar")
  2028. self.assertEqual(backend.ssl_certfile, "bar")
  2029. def test_email_ssl_certfile_default_disabled(self):
  2030. backend = smtp.EmailBackend()
  2031. self.assertIsNone(backend.ssl_certfile)
  2032. @override_settings(EMAIL_SSL_KEYFILE="foo")
  2033. def test_email_ssl_keyfile_use_settings(self):
  2034. backend = smtp.EmailBackend()
  2035. self.assertEqual(backend.ssl_keyfile, "foo")
  2036. @override_settings(EMAIL_SSL_KEYFILE="foo")
  2037. def test_email_ssl_keyfile_override_settings(self):
  2038. backend = smtp.EmailBackend(ssl_keyfile="bar")
  2039. self.assertEqual(backend.ssl_keyfile, "bar")
  2040. def test_email_ssl_keyfile_default_disabled(self):
  2041. backend = smtp.EmailBackend()
  2042. self.assertIsNone(backend.ssl_keyfile)
  2043. @override_settings(EMAIL_USE_TLS=True)
  2044. def test_email_tls_attempts_starttls(self):
  2045. backend = smtp.EmailBackend()
  2046. self.assertTrue(backend.use_tls)
  2047. with self.assertRaisesMessage(
  2048. SMTPException, "STARTTLS extension not supported by server."
  2049. ):
  2050. with backend:
  2051. pass
  2052. @override_settings(EMAIL_USE_SSL=True)
  2053. def test_email_ssl_attempts_ssl_connection(self):
  2054. backend = smtp.EmailBackend()
  2055. self.assertTrue(backend.use_ssl)
  2056. with self.assertRaises(SSLError):
  2057. with backend:
  2058. pass
  2059. def test_connection_timeout_default(self):
  2060. """The connection's timeout value is None by default."""
  2061. connection = mail.get_connection("django.core.mail.backends.smtp.EmailBackend")
  2062. self.assertIsNone(connection.timeout)
  2063. def test_connection_timeout_custom(self):
  2064. """The timeout parameter can be customized."""
  2065. class MyEmailBackend(smtp.EmailBackend):
  2066. def __init__(self, *args, **kwargs):
  2067. kwargs.setdefault("timeout", 42)
  2068. super().__init__(*args, **kwargs)
  2069. myemailbackend = MyEmailBackend()
  2070. myemailbackend.open()
  2071. self.assertEqual(myemailbackend.timeout, 42)
  2072. self.assertEqual(myemailbackend.connection.timeout, 42)
  2073. myemailbackend.close()
  2074. @override_settings(EMAIL_TIMEOUT=10)
  2075. def test_email_timeout_override_settings(self):
  2076. backend = smtp.EmailBackend()
  2077. self.assertEqual(backend.timeout, 10)
  2078. def test_email_msg_uses_crlf(self):
  2079. """#23063 -- RFC-compliant messages are sent over SMTP."""
  2080. send = SMTP.send
  2081. try:
  2082. smtp_messages = []
  2083. def mock_send(self, s):
  2084. smtp_messages.append(s)
  2085. return send(self, s)
  2086. SMTP.send = mock_send
  2087. email = EmailMessage(
  2088. "Subject", "Content", "from@example.com", ["to@example.com"]
  2089. )
  2090. mail.get_connection().send_messages([email])
  2091. # Find the actual message
  2092. msg = None
  2093. for i, m in enumerate(smtp_messages):
  2094. if m[:4] == "data":
  2095. msg = smtp_messages[i + 1]
  2096. break
  2097. self.assertTrue(msg)
  2098. msg = msg.decode()
  2099. # The message only contains CRLF and not combinations of CRLF, LF, and CR.
  2100. msg = msg.replace("\r\n", "")
  2101. self.assertNotIn("\r", msg)
  2102. self.assertNotIn("\n", msg)
  2103. finally:
  2104. SMTP.send = send
  2105. def test_send_messages_after_open_failed(self):
  2106. """
  2107. send_messages() shouldn't try to send messages if open() raises an
  2108. exception after initializing the connection.
  2109. """
  2110. backend = smtp.EmailBackend()
  2111. # Simulate connection initialization success and a subsequent
  2112. # connection exception.
  2113. backend.connection = mock.Mock(spec=object())
  2114. backend.open = lambda: None
  2115. email = EmailMessage(to=["to@example.com"])
  2116. self.assertEqual(backend.send_messages([email]), 0)
  2117. def test_send_messages_empty_list(self):
  2118. backend = smtp.EmailBackend()
  2119. backend.connection = mock.Mock(spec=object())
  2120. self.assertEqual(backend.send_messages([]), 0)
  2121. def test_send_messages_zero_sent(self):
  2122. """A message isn't sent if it doesn't have any recipients."""
  2123. backend = smtp.EmailBackend()
  2124. backend.connection = mock.Mock(spec=object())
  2125. email = EmailMessage("Subject", "Content", "from@example.com", to=[])
  2126. sent = backend.send_messages([email])
  2127. self.assertEqual(sent, 0)
  2128. def test_avoids_sending_to_invalid_addresses(self):
  2129. """
  2130. Verify invalid addresses can't sneak into SMTP commands through
  2131. EmailMessage.all_recipients() (which is distinct from message header fields).
  2132. """
  2133. backend = smtp.EmailBackend()
  2134. backend.connection = mock.Mock()
  2135. for email_address in (
  2136. # Invalid address with two @ signs.
  2137. "to@other.com@example.com",
  2138. # Invalid address without the quotes.
  2139. "to@other.com <to@example.com>",
  2140. # Other invalid addresses.
  2141. "@",
  2142. "to@",
  2143. "@example.com",
  2144. # CR/NL in addr-spec. (SMTP strips display-name.)
  2145. '"evil@example.com\r\nto"@example.com',
  2146. "to\nevil@example.com",
  2147. ):
  2148. with self.subTest(email_address=email_address):
  2149. # Use bcc (which is only processed by SMTP backend) to ensure
  2150. # error is coming from SMTP backend, not EmailMessage.message().
  2151. email = EmailMessage(bcc=[email_address])
  2152. with self.assertRaisesMessage(ValueError, "Invalid address"):
  2153. backend.send_messages([email])
  2154. def test_encodes_idna_in_smtp_commands(self):
  2155. """
  2156. SMTP backend must encode non-ASCII domains for the SMTP envelope
  2157. (which can be distinct from the email headers).
  2158. """
  2159. email = EmailMessage(
  2160. from_email="lists@discussão.example.org",
  2161. to=["To Example <to@漢字.example.com>"],
  2162. bcc=["monitor@discussão.example.org"],
  2163. headers={
  2164. "From": "Gestor de listas <lists@discussão.example.org>",
  2165. "To": "Discussão Django <django@discussão.example.org>",
  2166. },
  2167. )
  2168. backend = smtp.EmailBackend()
  2169. backend.send_messages([email])
  2170. envelope = self.get_smtp_envelopes()[0]
  2171. self.assertEqual(envelope["mail_from"], "lists@xn--discusso-xza.example.org")
  2172. self.assertEqual(
  2173. envelope["rcpt_tos"],
  2174. ["to@xn--p8s937b.example.com", "monitor@xn--discusso-xza.example.org"],
  2175. )
  2176. def test_does_not_reencode_idna(self):
  2177. """
  2178. SMTP backend should not downgrade IDNA 2008 to IDNA 2003.
  2179. Django does not currently handle IDNA 2008 encoding, but should retain
  2180. it for addresses that have been pre-encoded.
  2181. """
  2182. # Test all four EmailMessage attrs accessed by the SMTP email backend.
  2183. # These are IDNA 2008 encoded domains that would be different
  2184. # in IDNA 2003, from https://www.unicode.org/reports/tr46/#Deviations.
  2185. email = EmailMessage(
  2186. from_email='"βόλος" <from@xn--fa-hia.example.com>',
  2187. to=['"faß" <to@xn--10cl1a0b660p.example.com>'],
  2188. cc=['"ශ්‍රී" <cc@xn--nxasmm1c.example.com>'],
  2189. bcc=['"نامه‌ای." <bcc@xn--mgba3gch31f060k.example.com>'],
  2190. )
  2191. backend = smtp.EmailBackend()
  2192. backend.send_messages([email])
  2193. envelope = self.get_smtp_envelopes()[0]
  2194. self.assertEqual(envelope["mail_from"], "from@xn--fa-hia.example.com")
  2195. self.assertEqual(
  2196. envelope["rcpt_tos"],
  2197. [
  2198. "to@xn--10cl1a0b660p.example.com",
  2199. "cc@xn--nxasmm1c.example.com",
  2200. "bcc@xn--mgba3gch31f060k.example.com",
  2201. ],
  2202. )
  2203. @skipUnless(HAS_AIOSMTPD, "No aiosmtpd library detected.")
  2204. class SMTPBackendStoppedServerTests(SMTPBackendTestsBase):
  2205. @classmethod
  2206. def setUpClass(cls):
  2207. super().setUpClass()
  2208. cls.backend = smtp.EmailBackend(username="", password="")
  2209. cls.smtp_controller.stop()
  2210. @classmethod
  2211. def stop_smtp(cls):
  2212. # SMTP controller is stopped in setUpClass().
  2213. pass
  2214. def test_server_stopped(self):
  2215. """
  2216. Closing the backend while the SMTP server is stopped doesn't raise an
  2217. exception.
  2218. """
  2219. self.backend.close()
  2220. def test_fail_silently_on_connection_error(self):
  2221. """
  2222. A socket connection error is silenced with fail_silently=True.
  2223. """
  2224. with self.assertRaises(ConnectionError):
  2225. self.backend.open()
  2226. self.backend.fail_silently = True
  2227. self.backend.open()