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