tests.py 67 KB

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