123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085 |
- import mimetypes
- import os
- import shutil
- import socket
- import sys
- import tempfile
- from email import charset, message_from_binary_file, message_from_bytes
- from email.header import Header
- from email.mime.text import MIMEText
- from email.utils import parseaddr
- from io import StringIO
- from pathlib import Path
- from smtplib import SMTP, SMTPException
- from ssl import SSLError
- from unittest import mock, skipUnless
- from django.core import mail
- from django.core.mail import (
- DNS_NAME,
- EmailMessage,
- EmailMultiAlternatives,
- mail_admins,
- mail_managers,
- send_mail,
- send_mass_mail,
- )
- from django.core.mail.backends import console, dummy, filebased, locmem, smtp
- from django.core.mail.message import BadHeaderError, sanitize_address
- from django.test import SimpleTestCase, override_settings
- from django.test.utils import requires_tz_support
- from django.utils.translation import gettext_lazy
- try:
- from aiosmtpd.controller import Controller
- HAS_AIOSMTPD = True
- except ImportError:
- HAS_AIOSMTPD = False
- class HeadersCheckMixin:
- def assertMessageHasHeaders(self, message, headers):
- """
- Asserts that the `message` has all `headers`.
- message: can be an instance of an email.Message subclass or a string
- with the contents of an email message.
- headers: should be a set of (header-name, header-value) tuples.
- """
- if isinstance(message, bytes):
- message = message_from_bytes(message)
- msg_headers = set(message.items())
- self.assertTrue(
- headers.issubset(msg_headers),
- msg="Message is missing "
- "the following headers: %s" % (headers - msg_headers),
- )
- class MailTests(HeadersCheckMixin, SimpleTestCase):
- """
- Non-backend specific tests.
- """
- def get_decoded_attachments(self, django_message):
- """
- Encode the specified django.core.mail.message.EmailMessage, then decode
- it using Python's email.parser module and, for each attachment of the
- message, return a list of tuples with (filename, content, mimetype).
- """
- msg_bytes = django_message.message().as_bytes()
- email_message = message_from_bytes(msg_bytes)
- def iter_attachments():
- for i in email_message.walk():
- if i.get_content_disposition() == "attachment":
- filename = i.get_filename()
- content = i.get_payload(decode=True)
- mimetype = i.get_content_type()
- yield filename, content, mimetype
- return list(iter_attachments())
- def test_ascii(self):
- email = EmailMessage(
- "Subject", "Content", "from@example.com", ["to@example.com"]
- )
- message = email.message()
- self.assertEqual(message["Subject"], "Subject")
- self.assertEqual(message.get_payload(), "Content")
- self.assertEqual(message["From"], "from@example.com")
- self.assertEqual(message["To"], "to@example.com")
- @mock.patch("django.core.mail.message.MIMEText.set_payload")
- def test_nonascii_as_string_with_ascii_charset(self, mock_set_payload):
- """Line length check should encode the payload supporting `surrogateescape`.
- Following https://github.com/python/cpython/issues/76511, newer
- versions of Python (3.11.9, 3.12.3 and 3.13) ensure that a message's
- payload is encoded with the provided charset and `surrogateescape` is
- used as the error handling strategy.
- This test is heavily based on the test from the fix for the bug above.
- Line length checks in SafeMIMEText's set_payload should also use the
- same error handling strategy to avoid errors such as:
- UnicodeEncodeError: 'utf-8' codec can't encode <...>: surrogates not allowed
- """
- def simplified_set_payload(instance, payload, charset):
- instance._payload = payload
- mock_set_payload.side_effect = simplified_set_payload
- text = (
- "Text heavily based in Python's text for non-ascii messages: Föö bär"
- ).encode("iso-8859-1")
- body = text.decode("ascii", errors="surrogateescape")
- email = EmailMessage("Subject", body, "from@example.com", ["to@example.com"])
- message = email.message()
- mock_set_payload.assert_called_once()
- self.assertEqual(message.get_payload(decode=True), text)
- def test_multiple_recipients(self):
- email = EmailMessage(
- "Subject",
- "Content",
- "from@example.com",
- ["to@example.com", "other@example.com"],
- )
- message = email.message()
- self.assertEqual(message["Subject"], "Subject")
- self.assertEqual(message.get_payload(), "Content")
- self.assertEqual(message["From"], "from@example.com")
- self.assertEqual(message["To"], "to@example.com, other@example.com")
- def test_header_omitted_for_no_to_recipients(self):
- message = EmailMessage(
- "Subject", "Content", "from@example.com", cc=["cc@example.com"]
- ).message()
- self.assertNotIn("To", message)
- def test_recipients_with_empty_strings(self):
- """
- Empty strings in various recipient arguments are always stripped
- off the final recipient list.
- """
- email = EmailMessage(
- "Subject",
- "Content",
- "from@example.com",
- ["to@example.com", ""],
- cc=["cc@example.com", ""],
- bcc=["", "bcc@example.com"],
- reply_to=["", None],
- )
- self.assertEqual(
- email.recipients(), ["to@example.com", "cc@example.com", "bcc@example.com"]
- )
- def test_cc(self):
- """Regression test for #7722"""
- email = EmailMessage(
- "Subject",
- "Content",
- "from@example.com",
- ["to@example.com"],
- cc=["cc@example.com"],
- )
- message = email.message()
- self.assertEqual(message["Cc"], "cc@example.com")
- self.assertEqual(email.recipients(), ["to@example.com", "cc@example.com"])
- # Test multiple CC with multiple To
- email = EmailMessage(
- "Subject",
- "Content",
- "from@example.com",
- ["to@example.com", "other@example.com"],
- cc=["cc@example.com", "cc.other@example.com"],
- )
- message = email.message()
- self.assertEqual(message["Cc"], "cc@example.com, cc.other@example.com")
- self.assertEqual(
- email.recipients(),
- [
- "to@example.com",
- "other@example.com",
- "cc@example.com",
- "cc.other@example.com",
- ],
- )
- # Testing with Bcc
- email = EmailMessage(
- "Subject",
- "Content",
- "from@example.com",
- ["to@example.com", "other@example.com"],
- cc=["cc@example.com", "cc.other@example.com"],
- bcc=["bcc@example.com"],
- )
- message = email.message()
- self.assertEqual(message["Cc"], "cc@example.com, cc.other@example.com")
- self.assertEqual(
- email.recipients(),
- [
- "to@example.com",
- "other@example.com",
- "cc@example.com",
- "cc.other@example.com",
- "bcc@example.com",
- ],
- )
- def test_cc_headers(self):
- message = EmailMessage(
- "Subject",
- "Content",
- "bounce@example.com",
- ["to@example.com"],
- cc=["foo@example.com"],
- headers={"Cc": "override@example.com"},
- ).message()
- self.assertEqual(message["Cc"], "override@example.com")
- def test_cc_in_headers_only(self):
- message = EmailMessage(
- "Subject",
- "Content",
- "bounce@example.com",
- ["to@example.com"],
- headers={"Cc": "foo@example.com"},
- ).message()
- self.assertEqual(message["Cc"], "foo@example.com")
- def test_reply_to(self):
- email = EmailMessage(
- "Subject",
- "Content",
- "from@example.com",
- ["to@example.com"],
- reply_to=["reply_to@example.com"],
- )
- message = email.message()
- self.assertEqual(message["Reply-To"], "reply_to@example.com")
- email = EmailMessage(
- "Subject",
- "Content",
- "from@example.com",
- ["to@example.com"],
- reply_to=["reply_to1@example.com", "reply_to2@example.com"],
- )
- message = email.message()
- self.assertEqual(
- message["Reply-To"], "reply_to1@example.com, reply_to2@example.com"
- )
- def test_recipients_as_tuple(self):
- email = EmailMessage(
- "Subject",
- "Content",
- "from@example.com",
- ("to@example.com", "other@example.com"),
- cc=("cc@example.com", "cc.other@example.com"),
- bcc=("bcc@example.com",),
- )
- message = email.message()
- self.assertEqual(message["Cc"], "cc@example.com, cc.other@example.com")
- self.assertEqual(
- email.recipients(),
- [
- "to@example.com",
- "other@example.com",
- "cc@example.com",
- "cc.other@example.com",
- "bcc@example.com",
- ],
- )
- def test_recipients_as_string(self):
- with self.assertRaisesMessage(
- TypeError, '"to" argument must be a list or tuple'
- ):
- EmailMessage(to="foo@example.com")
- with self.assertRaisesMessage(
- TypeError, '"cc" argument must be a list or tuple'
- ):
- EmailMessage(cc="foo@example.com")
- with self.assertRaisesMessage(
- TypeError, '"bcc" argument must be a list or tuple'
- ):
- EmailMessage(bcc="foo@example.com")
- with self.assertRaisesMessage(
- TypeError, '"reply_to" argument must be a list or tuple'
- ):
- EmailMessage(reply_to="reply_to@example.com")
- def test_header_injection(self):
- msg = "Header values can't contain newlines "
- email = EmailMessage(
- "Subject\nInjection Test", "Content", "from@example.com", ["to@example.com"]
- )
- with self.assertRaisesMessage(BadHeaderError, msg):
- email.message()
- email = EmailMessage(
- gettext_lazy("Subject\nInjection Test"),
- "Content",
- "from@example.com",
- ["to@example.com"],
- )
- with self.assertRaisesMessage(BadHeaderError, msg):
- email.message()
- with self.assertRaisesMessage(BadHeaderError, msg):
- EmailMessage(
- "Subject",
- "Content",
- "from@example.com",
- ["Name\nInjection test <to@example.com>"],
- ).message()
- def test_space_continuation(self):
- """
- Test for space continuation character in long (ASCII) subject headers (#7747)
- """
- email = EmailMessage(
- "Long subject lines that get wrapped should contain a space continuation "
- "character to get expected behavior in Outlook and Thunderbird",
- "Content",
- "from@example.com",
- ["to@example.com"],
- )
- message = email.message()
- self.assertEqual(
- message["Subject"].encode(),
- b"Long subject lines that get wrapped should contain a space continuation\n"
- b" character to get expected behavior in Outlook and Thunderbird",
- )
- def test_message_header_overrides(self):
- """
- Specifying dates or message-ids in the extra headers overrides the
- default values (#9233)
- """
- headers = {"date": "Fri, 09 Nov 2001 01:08:47 -0000", "Message-ID": "foo"}
- email = EmailMessage(
- "subject",
- "content",
- "from@example.com",
- ["to@example.com"],
- headers=headers,
- )
- self.assertMessageHasHeaders(
- email.message(),
- {
- ("Content-Transfer-Encoding", "7bit"),
- ("Content-Type", 'text/plain; charset="utf-8"'),
- ("From", "from@example.com"),
- ("MIME-Version", "1.0"),
- ("Message-ID", "foo"),
- ("Subject", "subject"),
- ("To", "to@example.com"),
- ("date", "Fri, 09 Nov 2001 01:08:47 -0000"),
- },
- )
- def test_from_header(self):
- """
- Make sure we can manually set the From header (#9214)
- """
- email = EmailMessage(
- "Subject",
- "Content",
- "bounce@example.com",
- ["to@example.com"],
- headers={"From": "from@example.com"},
- )
- message = email.message()
- self.assertEqual(message["From"], "from@example.com")
- def test_to_header(self):
- """
- Make sure we can manually set the To header (#17444)
- """
- email = EmailMessage(
- "Subject",
- "Content",
- "bounce@example.com",
- ["list-subscriber@example.com", "list-subscriber2@example.com"],
- headers={"To": "mailing-list@example.com"},
- )
- message = email.message()
- self.assertEqual(message["To"], "mailing-list@example.com")
- self.assertEqual(
- email.to, ["list-subscriber@example.com", "list-subscriber2@example.com"]
- )
- # If we don't set the To header manually, it should default to the `to`
- # argument to the constructor.
- email = EmailMessage(
- "Subject",
- "Content",
- "bounce@example.com",
- ["list-subscriber@example.com", "list-subscriber2@example.com"],
- )
- message = email.message()
- self.assertEqual(
- message["To"], "list-subscriber@example.com, list-subscriber2@example.com"
- )
- self.assertEqual(
- email.to, ["list-subscriber@example.com", "list-subscriber2@example.com"]
- )
- def test_to_in_headers_only(self):
- message = EmailMessage(
- "Subject",
- "Content",
- "bounce@example.com",
- headers={"To": "to@example.com"},
- ).message()
- self.assertEqual(message["To"], "to@example.com")
- def test_reply_to_header(self):
- """
- Specifying 'Reply-To' in headers should override reply_to.
- """
- email = EmailMessage(
- "Subject",
- "Content",
- "bounce@example.com",
- ["to@example.com"],
- reply_to=["foo@example.com"],
- headers={"Reply-To": "override@example.com"},
- )
- message = email.message()
- self.assertEqual(message["Reply-To"], "override@example.com")
- def test_reply_to_in_headers_only(self):
- message = EmailMessage(
- "Subject",
- "Content",
- "from@example.com",
- ["to@example.com"],
- headers={"Reply-To": "reply_to@example.com"},
- ).message()
- self.assertEqual(message["Reply-To"], "reply_to@example.com")
- def test_multiple_message_call(self):
- """
- Regression for #13259 - Make sure that headers are not changed when
- calling EmailMessage.message()
- """
- email = EmailMessage(
- "Subject",
- "Content",
- "bounce@example.com",
- ["to@example.com"],
- headers={"From": "from@example.com"},
- )
- message = email.message()
- self.assertEqual(message["From"], "from@example.com")
- message = email.message()
- self.assertEqual(message["From"], "from@example.com")
- def test_unicode_address_header(self):
- """
- Regression for #11144 - When a to/from/cc header contains Unicode,
- make sure the email addresses are parsed correctly (especially with
- regards to commas)
- """
- email = EmailMessage(
- "Subject",
- "Content",
- "from@example.com",
- ['"Firstname Sürname" <to@example.com>', "other@example.com"],
- )
- self.assertEqual(
- email.message()["To"],
- "=?utf-8?q?Firstname_S=C3=BCrname?= <to@example.com>, other@example.com",
- )
- email = EmailMessage(
- "Subject",
- "Content",
- "from@example.com",
- ['"Sürname, Firstname" <to@example.com>', "other@example.com"],
- )
- self.assertEqual(
- email.message()["To"],
- "=?utf-8?q?S=C3=BCrname=2C_Firstname?= <to@example.com>, other@example.com",
- )
- def test_unicode_headers(self):
- email = EmailMessage(
- "Gżegżółka",
- "Content",
- "from@example.com",
- ["to@example.com"],
- headers={
- "Sender": '"Firstname Sürname" <sender@example.com>',
- "Comments": "My Sürname is non-ASCII",
- },
- )
- message = email.message()
- self.assertEqual(message["Subject"], "=?utf-8?b?R8W8ZWfFvMOzxYJrYQ==?=")
- self.assertEqual(
- message["Sender"], "=?utf-8?q?Firstname_S=C3=BCrname?= <sender@example.com>"
- )
- self.assertEqual(
- message["Comments"], "=?utf-8?q?My_S=C3=BCrname_is_non-ASCII?="
- )
- def test_safe_mime_multipart(self):
- """
- Make sure headers can be set with a different encoding than utf-8 in
- SafeMIMEMultipart as well
- """
- headers = {"Date": "Fri, 09 Nov 2001 01:08:47 -0000", "Message-ID": "foo"}
- from_email, to = "from@example.com", '"Sürname, Firstname" <to@example.com>'
- text_content = "This is an important message."
- html_content = "<p>This is an <strong>important</strong> message.</p>"
- msg = EmailMultiAlternatives(
- "Message from Firstname Sürname",
- text_content,
- from_email,
- [to],
- headers=headers,
- )
- msg.attach_alternative(html_content, "text/html")
- msg.encoding = "iso-8859-1"
- self.assertEqual(
- msg.message()["To"],
- "=?iso-8859-1?q?S=FCrname=2C_Firstname?= <to@example.com>",
- )
- self.assertEqual(
- msg.message()["Subject"],
- "=?iso-8859-1?q?Message_from_Firstname_S=FCrname?=",
- )
- def test_safe_mime_multipart_with_attachments(self):
- """
- EmailMultiAlternatives includes alternatives if the body is empty and
- it has attachments.
- """
- msg = EmailMultiAlternatives(body="")
- html_content = "<p>This is <strong>html</strong></p>"
- msg.attach_alternative(html_content, "text/html")
- msg.attach("example.txt", "Text file content", "text/plain")
- self.assertIn(html_content, msg.message().as_string())
- def test_alternatives(self):
- msg = EmailMultiAlternatives()
- html_content = "<p>This is <strong>html</strong></p>"
- mime_type = "text/html"
- msg.attach_alternative(html_content, mime_type)
- self.assertEqual(msg.alternatives[0][0], html_content)
- self.assertEqual(msg.alternatives[0].content, html_content)
- self.assertEqual(msg.alternatives[0][1], mime_type)
- self.assertEqual(msg.alternatives[0].mimetype, mime_type)
- def test_none_body(self):
- msg = EmailMessage("subject", None, "from@example.com", ["to@example.com"])
- self.assertEqual(msg.body, "")
- self.assertEqual(msg.message().get_payload(), "")
- @mock.patch("socket.getfqdn", return_value="漢字")
- def test_non_ascii_dns_non_unicode_email(self, mocked_getfqdn):
- delattr(DNS_NAME, "_fqdn")
- email = EmailMessage(
- "subject", "content", "from@example.com", ["to@example.com"]
- )
- email.encoding = "iso-8859-1"
- self.assertIn("@xn--p8s937b>", email.message()["Message-ID"])
- def test_encoding(self):
- """
- Regression for #12791 - Encode body correctly with other encodings
- than utf-8
- """
- email = EmailMessage(
- "Subject",
- "Firstname Sürname is a great guy.",
- "from@example.com",
- ["other@example.com"],
- )
- email.encoding = "iso-8859-1"
- message = email.message()
- self.assertMessageHasHeaders(
- message,
- {
- ("MIME-Version", "1.0"),
- ("Content-Type", 'text/plain; charset="iso-8859-1"'),
- ("Content-Transfer-Encoding", "quoted-printable"),
- ("Subject", "Subject"),
- ("From", "from@example.com"),
- ("To", "other@example.com"),
- },
- )
- self.assertEqual(message.get_payload(), "Firstname S=FCrname is a great guy.")
- # MIME attachments works correctly with other encodings than utf-8.
- text_content = "Firstname Sürname is a great guy."
- html_content = "<p>Firstname Sürname is a <strong>great</strong> guy.</p>"
- msg = EmailMultiAlternatives(
- "Subject", text_content, "from@example.com", ["to@example.com"]
- )
- msg.encoding = "iso-8859-1"
- msg.attach_alternative(html_content, "text/html")
- payload0 = msg.message().get_payload(0)
- self.assertMessageHasHeaders(
- payload0,
- {
- ("MIME-Version", "1.0"),
- ("Content-Type", 'text/plain; charset="iso-8859-1"'),
- ("Content-Transfer-Encoding", "quoted-printable"),
- },
- )
- self.assertTrue(
- payload0.as_bytes().endswith(b"\n\nFirstname S=FCrname is a great guy.")
- )
- payload1 = msg.message().get_payload(1)
- self.assertMessageHasHeaders(
- payload1,
- {
- ("MIME-Version", "1.0"),
- ("Content-Type", 'text/html; charset="iso-8859-1"'),
- ("Content-Transfer-Encoding", "quoted-printable"),
- },
- )
- self.assertTrue(
- payload1.as_bytes().endswith(
- b"\n\n<p>Firstname S=FCrname is a <strong>great</strong> guy.</p>"
- )
- )
- def test_attachments(self):
- msg = EmailMessage()
- file_name = "example.txt"
- file_content = "Text file content"
- mime_type = "text/plain"
- msg.attach(file_name, file_content, mime_type)
- self.assertEqual(msg.attachments[0][0], file_name)
- self.assertEqual(msg.attachments[0].filename, file_name)
- self.assertEqual(msg.attachments[0][1], file_content)
- self.assertEqual(msg.attachments[0].content, file_content)
- self.assertEqual(msg.attachments[0][2], mime_type)
- self.assertEqual(msg.attachments[0].mimetype, mime_type)
- def test_decoded_attachments(self):
- """Regression test for #9367"""
- headers = {"Date": "Fri, 09 Nov 2001 01:08:47 -0000", "Message-ID": "foo"}
- subject, from_email, to = "hello", "from@example.com", "to@example.com"
- text_content = "This is an important message."
- html_content = "<p>This is an <strong>important</strong> message.</p>"
- msg = EmailMultiAlternatives(
- subject, text_content, from_email, [to], headers=headers
- )
- msg.attach_alternative(html_content, "text/html")
- msg.attach("an attachment.pdf", b"%PDF-1.4.%...", mimetype="application/pdf")
- msg_bytes = msg.message().as_bytes()
- message = message_from_bytes(msg_bytes)
- self.assertTrue(message.is_multipart())
- self.assertEqual(message.get_content_type(), "multipart/mixed")
- self.assertEqual(message.get_default_type(), "text/plain")
- payload = message.get_payload()
- self.assertEqual(payload[0].get_content_type(), "multipart/alternative")
- self.assertEqual(payload[1].get_content_type(), "application/pdf")
- def test_decoded_attachments_two_tuple(self):
- msg = EmailMessage(attachments=[("filename1", "content1")])
- filename, content, mimetype = self.get_decoded_attachments(msg)[0]
- self.assertEqual(filename, "filename1")
- self.assertEqual(content, b"content1")
- self.assertEqual(mimetype, "application/octet-stream")
- def test_decoded_attachments_MIMEText(self):
- txt = MIMEText("content1")
- msg = EmailMessage(attachments=[txt])
- payload = msg.message().get_payload()
- self.assertEqual(payload[0], txt)
- def test_non_ascii_attachment_filename(self):
- """Regression test for #14964"""
- headers = {"Date": "Fri, 09 Nov 2001 01:08:47 -0000", "Message-ID": "foo"}
- subject, from_email, to = "hello", "from@example.com", "to@example.com"
- content = "This is the message."
- msg = EmailMessage(subject, content, from_email, [to], headers=headers)
- # Unicode in file name
- msg.attach("une pièce jointe.pdf", b"%PDF-1.4.%...", mimetype="application/pdf")
- msg_bytes = msg.message().as_bytes()
- message = message_from_bytes(msg_bytes)
- payload = message.get_payload()
- self.assertEqual(payload[1].get_filename(), "une pièce jointe.pdf")
- def test_attach_file(self):
- """
- Test attaching a file against different mimetypes and make sure that
- a file will be attached and sent properly even if an invalid mimetype
- is specified.
- """
- files = (
- # filename, actual mimetype
- ("file.txt", "text/plain"),
- ("file.png", "image/png"),
- ("file_txt", None),
- ("file_png", None),
- ("file_txt.png", "image/png"),
- ("file_png.txt", "text/plain"),
- ("file.eml", "message/rfc822"),
- )
- test_mimetypes = ["text/plain", "image/png", None]
- for basename, real_mimetype in files:
- for mimetype in test_mimetypes:
- email = EmailMessage(
- "subject", "body", "from@example.com", ["to@example.com"]
- )
- self.assertEqual(mimetypes.guess_type(basename)[0], real_mimetype)
- self.assertEqual(email.attachments, [])
- file_path = os.path.join(
- os.path.dirname(__file__), "attachments", basename
- )
- email.attach_file(file_path, mimetype=mimetype)
- self.assertEqual(len(email.attachments), 1)
- self.assertIn(basename, email.attachments[0])
- msgs_sent_num = email.send()
- self.assertEqual(msgs_sent_num, 1)
- def test_attach_text_as_bytes(self):
- msg = EmailMessage("subject", "body", "from@example.com", ["to@example.com"])
- msg.attach("file.txt", b"file content")
- sent_num = msg.send()
- self.assertEqual(sent_num, 1)
- filename, content, mimetype = self.get_decoded_attachments(msg)[0]
- self.assertEqual(filename, "file.txt")
- self.assertEqual(content, b"file content")
- self.assertEqual(mimetype, "text/plain")
- def test_attach_utf8_text_as_bytes(self):
- """
- Non-ASCII characters encoded as valid UTF-8 are correctly transported
- and decoded.
- """
- msg = EmailMessage("subject", "body", "from@example.com", ["to@example.com"])
- msg.attach("file.txt", b"\xc3\xa4") # UTF-8 encoded a umlaut.
- filename, content, mimetype = self.get_decoded_attachments(msg)[0]
- self.assertEqual(filename, "file.txt")
- self.assertEqual(content, b"\xc3\xa4")
- self.assertEqual(mimetype, "text/plain")
- def test_attach_non_utf8_text_as_bytes(self):
- """
- Binary data that can't be decoded as UTF-8 overrides the MIME type
- instead of decoding the data.
- """
- msg = EmailMessage("subject", "body", "from@example.com", ["to@example.com"])
- msg.attach("file.txt", b"\xff") # Invalid UTF-8.
- filename, content, mimetype = self.get_decoded_attachments(msg)[0]
- self.assertEqual(filename, "file.txt")
- # Content should be passed through unmodified.
- self.assertEqual(content, b"\xff")
- self.assertEqual(mimetype, "application/octet-stream")
- def test_attach_mimetext_content_mimetype(self):
- email_msg = EmailMessage()
- txt = MIMEText("content")
- msg = (
- "content and mimetype must not be given when a MIMEBase instance "
- "is provided."
- )
- with self.assertRaisesMessage(ValueError, msg):
- email_msg.attach(txt, content="content")
- with self.assertRaisesMessage(ValueError, msg):
- email_msg.attach(txt, mimetype="text/plain")
- def test_attach_content_none(self):
- email_msg = EmailMessage()
- msg = "content must be provided."
- with self.assertRaisesMessage(ValueError, msg):
- email_msg.attach("file.txt", mimetype="application/pdf")
- def test_dummy_backend(self):
- """
- Make sure that dummy backends returns correct number of sent messages
- """
- connection = dummy.EmailBackend()
- email = EmailMessage(
- "Subject",
- "Content",
- "bounce@example.com",
- ["to@example.com"],
- headers={"From": "from@example.com"},
- )
- self.assertEqual(connection.send_messages([email, email, email]), 3)
- def test_arbitrary_keyword(self):
- """
- Make sure that get_connection() accepts arbitrary keyword that might be
- used with custom backends.
- """
- c = mail.get_connection(fail_silently=True, foo="bar")
- self.assertTrue(c.fail_silently)
- def test_custom_backend(self):
- """Test custom backend defined in this suite."""
- conn = mail.get_connection("mail.custombackend.EmailBackend")
- self.assertTrue(hasattr(conn, "test_outbox"))
- email = EmailMessage(
- "Subject",
- "Content",
- "bounce@example.com",
- ["to@example.com"],
- headers={"From": "from@example.com"},
- )
- conn.send_messages([email])
- self.assertEqual(len(conn.test_outbox), 1)
- def test_backend_arg(self):
- """Test backend argument of mail.get_connection()"""
- self.assertIsInstance(
- mail.get_connection("django.core.mail.backends.smtp.EmailBackend"),
- smtp.EmailBackend,
- )
- self.assertIsInstance(
- mail.get_connection("django.core.mail.backends.locmem.EmailBackend"),
- locmem.EmailBackend,
- )
- self.assertIsInstance(
- mail.get_connection("django.core.mail.backends.dummy.EmailBackend"),
- dummy.EmailBackend,
- )
- self.assertIsInstance(
- mail.get_connection("django.core.mail.backends.console.EmailBackend"),
- console.EmailBackend,
- )
- with tempfile.TemporaryDirectory() as tmp_dir:
- self.assertIsInstance(
- mail.get_connection(
- "django.core.mail.backends.filebased.EmailBackend",
- file_path=tmp_dir,
- ),
- filebased.EmailBackend,
- )
- msg = " not object"
- with self.assertRaisesMessage(TypeError, msg):
- mail.get_connection(
- "django.core.mail.backends.filebased.EmailBackend", file_path=object()
- )
- self.assertIsInstance(mail.get_connection(), locmem.EmailBackend)
- @override_settings(
- EMAIL_BACKEND="django.core.mail.backends.locmem.EmailBackend",
- ADMINS=[("nobody", "nobody@example.com")],
- MANAGERS=[("nobody", "nobody@example.com")],
- )
- def test_connection_arg(self):
- """Test connection argument to send_mail(), et. al."""
- mail.outbox = []
- # Send using non-default connection
- connection = mail.get_connection("mail.custombackend.EmailBackend")
- send_mail(
- "Subject",
- "Content",
- "from@example.com",
- ["to@example.com"],
- connection=connection,
- )
- self.assertEqual(mail.outbox, [])
- self.assertEqual(len(connection.test_outbox), 1)
- self.assertEqual(connection.test_outbox[0].subject, "Subject")
- connection = mail.get_connection("mail.custombackend.EmailBackend")
- send_mass_mail(
- [
- ("Subject1", "Content1", "from1@example.com", ["to1@example.com"]),
- ("Subject2", "Content2", "from2@example.com", ["to2@example.com"]),
- ],
- connection=connection,
- )
- self.assertEqual(mail.outbox, [])
- self.assertEqual(len(connection.test_outbox), 2)
- self.assertEqual(connection.test_outbox[0].subject, "Subject1")
- self.assertEqual(connection.test_outbox[1].subject, "Subject2")
- connection = mail.get_connection("mail.custombackend.EmailBackend")
- mail_admins("Admin message", "Content", connection=connection)
- self.assertEqual(mail.outbox, [])
- self.assertEqual(len(connection.test_outbox), 1)
- self.assertEqual(connection.test_outbox[0].subject, "[Django] Admin message")
- connection = mail.get_connection("mail.custombackend.EmailBackend")
- mail_managers("Manager message", "Content", connection=connection)
- self.assertEqual(mail.outbox, [])
- self.assertEqual(len(connection.test_outbox), 1)
- self.assertEqual(connection.test_outbox[0].subject, "[Django] Manager message")
- def test_dont_mangle_from_in_body(self):
- # Regression for #13433 - Make sure that EmailMessage doesn't mangle
- # 'From ' in message body.
- email = EmailMessage(
- "Subject",
- "From the future",
- "bounce@example.com",
- ["to@example.com"],
- headers={"From": "from@example.com"},
- )
- self.assertNotIn(b">From the future", email.message().as_bytes())
- def test_dont_base64_encode(self):
- # Ticket #3472
- # Shouldn't use Base64 encoding at all
- msg = EmailMessage(
- "Subject",
- "UTF-8 encoded body",
- "bounce@example.com",
- ["to@example.com"],
- headers={"From": "from@example.com"},
- )
- self.assertIn(b"Content-Transfer-Encoding: 7bit", msg.message().as_bytes())
- # Ticket #11212
- # Shouldn't use quoted printable, should detect it can represent
- # content with 7 bit data.
- msg = EmailMessage(
- "Subject",
- "Body with only ASCII characters.",
- "bounce@example.com",
- ["to@example.com"],
- headers={"From": "from@example.com"},
- )
- s = msg.message().as_bytes()
- self.assertIn(b"Content-Transfer-Encoding: 7bit", s)
- # Shouldn't use quoted printable, should detect it can represent
- # content with 8 bit data.
- msg = EmailMessage(
- "Subject",
- "Body with latin characters: àáä.",
- "bounce@example.com",
- ["to@example.com"],
- headers={"From": "from@example.com"},
- )
- s = msg.message().as_bytes()
- self.assertIn(b"Content-Transfer-Encoding: 8bit", s)
- s = msg.message().as_string()
- self.assertIn("Content-Transfer-Encoding: 8bit", s)
- msg = EmailMessage(
- "Subject",
- "Body with non latin characters: А Б В Г Д Е Ж Ѕ З И І К Л М Н О П.",
- "bounce@example.com",
- ["to@example.com"],
- headers={"From": "from@example.com"},
- )
- s = msg.message().as_bytes()
- self.assertIn(b"Content-Transfer-Encoding: 8bit", s)
- s = msg.message().as_string()
- self.assertIn("Content-Transfer-Encoding: 8bit", s)
- def test_dont_base64_encode_message_rfc822(self):
- # Ticket #18967
- # Shouldn't use base64 encoding for a child EmailMessage attachment.
- # Create a child message first
- child_msg = EmailMessage(
- "Child Subject",
- "Some body of child message",
- "bounce@example.com",
- ["to@example.com"],
- headers={"From": "from@example.com"},
- )
- child_s = child_msg.message().as_string()
- # Now create a parent
- parent_msg = EmailMessage(
- "Parent Subject",
- "Some parent body",
- "bounce@example.com",
- ["to@example.com"],
- headers={"From": "from@example.com"},
- )
- # Attach to parent as a string
- parent_msg.attach(content=child_s, mimetype="message/rfc822")
- parent_s = parent_msg.message().as_string()
- # The child message header is not base64 encoded
- self.assertIn("Child Subject", parent_s)
- # Feature test: try attaching email.Message object directly to the mail.
- parent_msg = EmailMessage(
- "Parent Subject",
- "Some parent body",
- "bounce@example.com",
- ["to@example.com"],
- headers={"From": "from@example.com"},
- )
- parent_msg.attach(content=child_msg.message(), mimetype="message/rfc822")
- parent_s = parent_msg.message().as_string()
- # The child message header is not base64 encoded
- self.assertIn("Child Subject", parent_s)
- # Feature test: try attaching Django's EmailMessage object directly to the mail.
- parent_msg = EmailMessage(
- "Parent Subject",
- "Some parent body",
- "bounce@example.com",
- ["to@example.com"],
- headers={"From": "from@example.com"},
- )
- parent_msg.attach(content=child_msg, mimetype="message/rfc822")
- parent_s = parent_msg.message().as_string()
- # The child message header is not base64 encoded
- self.assertIn("Child Subject", parent_s)
- def test_custom_utf8_encoding(self):
- """A UTF-8 charset with a custom body encoding is respected."""
- body = "Body with latin characters: àáä."
- msg = EmailMessage("Subject", body, "bounce@example.com", ["to@example.com"])
- encoding = charset.Charset("utf-8")
- encoding.body_encoding = charset.QP
- msg.encoding = encoding
- message = msg.message()
- self.assertMessageHasHeaders(
- message,
- {
- ("MIME-Version", "1.0"),
- ("Content-Type", 'text/plain; charset="utf-8"'),
- ("Content-Transfer-Encoding", "quoted-printable"),
- },
- )
- self.assertEqual(message.get_payload(), encoding.body_encode(body))
- def test_sanitize_address(self):
- """Email addresses are properly sanitized."""
- for email_address, encoding, expected_result in (
- # ASCII addresses.
- ("to@example.com", "ascii", "to@example.com"),
- ("to@example.com", "utf-8", "to@example.com"),
- (("A name", "to@example.com"), "ascii", "A name <to@example.com>"),
- (
- ("A name", "to@example.com"),
- "utf-8",
- "A name <to@example.com>",
- ),
- ("localpartonly", "ascii", "localpartonly"),
- # ASCII addresses with display names.
- ("A name <to@example.com>", "ascii", "A name <to@example.com>"),
- ("A name <to@example.com>", "utf-8", "A name <to@example.com>"),
- ('"A name" <to@example.com>', "ascii", "A name <to@example.com>"),
- ('"A name" <to@example.com>', "utf-8", "A name <to@example.com>"),
- # Unicode addresses (supported per RFC-6532).
- ("tó@example.com", "utf-8", "=?utf-8?b?dMOz?=@example.com"),
- ("to@éxample.com", "utf-8", "to@xn--xample-9ua.com"),
- (
- ("Tó Example", "tó@example.com"),
- "utf-8",
- "=?utf-8?q?T=C3=B3_Example?= <=?utf-8?b?dMOz?=@example.com>",
- ),
- # Unicode addresses with display names.
- (
- "Tó Example <tó@example.com>",
- "utf-8",
- "=?utf-8?q?T=C3=B3_Example?= <=?utf-8?b?dMOz?=@example.com>",
- ),
- (
- "To Example <to@éxample.com>",
- "ascii",
- "To Example <to@xn--xample-9ua.com>",
- ),
- (
- "To Example <to@éxample.com>",
- "utf-8",
- "To Example <to@xn--xample-9ua.com>",
- ),
- # Addresses with two @ signs.
- ('"to@other.com"@example.com', "utf-8", r'"to@other.com"@example.com'),
- (
- '"to@other.com" <to@example.com>',
- "utf-8",
- '"to@other.com" <to@example.com>',
- ),
- (
- ("To Example", "to@other.com@example.com"),
- "utf-8",
- 'To Example <"to@other.com"@example.com>',
- ),
- # Addresses with long unicode display names.
- (
- "Tó Example very long" * 4 + " <to@example.com>",
- "utf-8",
- "=?utf-8?q?T=C3=B3_Example_very_longT=C3=B3_Example_very_longT"
- "=C3=B3_Example_?=\n"
- " =?utf-8?q?very_longT=C3=B3_Example_very_long?= "
- "<to@example.com>",
- ),
- (
- ("Tó Example very long" * 4, "to@example.com"),
- "utf-8",
- "=?utf-8?q?T=C3=B3_Example_very_longT=C3=B3_Example_very_longT"
- "=C3=B3_Example_?=\n"
- " =?utf-8?q?very_longT=C3=B3_Example_very_long?= "
- "<to@example.com>",
- ),
- # Address with long display name and unicode domain.
- (
- ("To Example very long" * 4, "to@exampl€.com"),
- "utf-8",
- "To Example very longTo Example very longTo Example very longT"
- "o Example very\n"
- " long <to@xn--exampl-nc1c.com>",
- ),
- ):
- with self.subTest(email_address=email_address, encoding=encoding):
- self.assertEqual(
- sanitize_address(email_address, encoding), expected_result
- )
- def test_sanitize_address_invalid(self):
- for email_address in (
- # Invalid address with two @ signs.
- "to@other.com@example.com",
- # Invalid address without the quotes.
- "to@other.com <to@example.com>",
- # Other invalid addresses.
- "@",
- "to@",
- "@example.com",
- ("", ""),
- ):
- with self.subTest(email_address=email_address):
- with self.assertRaisesMessage(ValueError, "Invalid address"):
- sanitize_address(email_address, encoding="utf-8")
- def test_sanitize_address_header_injection(self):
- msg = "Invalid address; address parts cannot contain newlines."
- tests = [
- "Name\nInjection <to@example.com>",
- ("Name\nInjection", "to@xample.com"),
- "Name <to\ninjection@example.com>",
- ("Name", "to\ninjection@example.com"),
- ]
- for email_address in tests:
- with self.subTest(email_address=email_address):
- with self.assertRaisesMessage(ValueError, msg):
- sanitize_address(email_address, encoding="utf-8")
- def test_email_multi_alternatives_content_mimetype_none(self):
- email_msg = EmailMultiAlternatives()
- msg = "Both content and mimetype must be provided."
- with self.assertRaisesMessage(ValueError, msg):
- email_msg.attach_alternative(None, "text/html")
- with self.assertRaisesMessage(ValueError, msg):
- email_msg.attach_alternative("<p>content</p>", None)
- def test_body_contains(self):
- email_msg = EmailMultiAlternatives()
- email_msg.body = "I am content."
- self.assertIs(email_msg.body_contains("I am"), True)
- self.assertIs(email_msg.body_contains("I am content."), True)
- email_msg.attach_alternative("<p>I am different content.</p>", "text/html")
- self.assertIs(email_msg.body_contains("I am"), True)
- self.assertIs(email_msg.body_contains("I am content."), False)
- self.assertIs(email_msg.body_contains("<p>I am different content.</p>"), False)
- def test_body_contains_alternative_non_text(self):
- email_msg = EmailMultiAlternatives()
- email_msg.body = "I am content."
- email_msg.attach_alternative("I am content.", "text/html")
- email_msg.attach_alternative(b"I am a song.", "audio/mpeg")
- self.assertIs(email_msg.body_contains("I am content"), True)
- @requires_tz_support
- class MailTimeZoneTests(SimpleTestCase):
- @override_settings(
- EMAIL_USE_LOCALTIME=False, USE_TZ=True, TIME_ZONE="Africa/Algiers"
- )
- def test_date_header_utc(self):
- """
- EMAIL_USE_LOCALTIME=False creates a datetime in UTC.
- """
- email = EmailMessage(
- "Subject", "Body", "bounce@example.com", ["to@example.com"]
- )
- self.assertTrue(email.message()["Date"].endswith("-0000"))
- @override_settings(
- EMAIL_USE_LOCALTIME=True, USE_TZ=True, TIME_ZONE="Africa/Algiers"
- )
- def test_date_header_localtime(self):
- """
- EMAIL_USE_LOCALTIME=True creates a datetime in the local time zone.
- """
- email = EmailMessage(
- "Subject", "Body", "bounce@example.com", ["to@example.com"]
- )
- self.assertTrue(
- email.message()["Date"].endswith("+0100")
- ) # Africa/Algiers is UTC+1
- class PythonGlobalState(SimpleTestCase):
- """
- Tests for #12422 -- Django smarts (#2472/#11212) with charset of utf-8 text
- parts shouldn't pollute global email Python package charset registry when
- django.mail.message is imported.
- """
- def test_utf8(self):
- txt = MIMEText("UTF-8 encoded body", "plain", "utf-8")
- self.assertIn("Content-Transfer-Encoding: base64", txt.as_string())
- def test_7bit(self):
- txt = MIMEText("Body with only ASCII characters.", "plain", "utf-8")
- self.assertIn("Content-Transfer-Encoding: base64", txt.as_string())
- def test_8bit_latin(self):
- txt = MIMEText("Body with latin characters: àáä.", "plain", "utf-8")
- self.assertIn("Content-Transfer-Encoding: base64", txt.as_string())
- def test_8bit_non_latin(self):
- txt = MIMEText(
- "Body with non latin characters: А Б В Г Д Е Ж Ѕ З И І К Л М Н О П.",
- "plain",
- "utf-8",
- )
- self.assertIn("Content-Transfer-Encoding: base64", txt.as_string())
- class BaseEmailBackendTests(HeadersCheckMixin):
- email_backend = None
- @classmethod
- def setUpClass(cls):
- cls.enterClassContext(override_settings(EMAIL_BACKEND=cls.email_backend))
- super().setUpClass()
- def assertStartsWith(self, first, second):
- if not first.startswith(second):
- self.longMessage = True
- self.assertEqual(
- first[: len(second)],
- second,
- "First string doesn't start with the second.",
- )
- def get_mailbox_content(self):
- raise NotImplementedError(
- "subclasses of BaseEmailBackendTests must provide a get_mailbox_content() "
- "method"
- )
- def flush_mailbox(self):
- raise NotImplementedError(
- "subclasses of BaseEmailBackendTests may require a flush_mailbox() method"
- )
- def get_the_message(self):
- mailbox = self.get_mailbox_content()
- self.assertEqual(
- len(mailbox),
- 1,
- "Expected exactly one message, got %d.\n%r"
- % (len(mailbox), [m.as_string() for m in mailbox]),
- )
- return mailbox[0]
- def test_send(self):
- email = EmailMessage(
- "Subject", "Content", "from@example.com", ["to@example.com"]
- )
- num_sent = mail.get_connection().send_messages([email])
- self.assertEqual(num_sent, 1)
- message = self.get_the_message()
- self.assertEqual(message["subject"], "Subject")
- self.assertEqual(message.get_payload(), "Content")
- self.assertEqual(message["from"], "from@example.com")
- self.assertEqual(message.get_all("to"), ["to@example.com"])
- def test_send_unicode(self):
- email = EmailMessage(
- "Chère maman", "Je t'aime très fort", "from@example.com", ["to@example.com"]
- )
- num_sent = mail.get_connection().send_messages([email])
- self.assertEqual(num_sent, 1)
- message = self.get_the_message()
- self.assertEqual(message["subject"], "=?utf-8?q?Ch=C3=A8re_maman?=")
- self.assertEqual(
- message.get_payload(decode=True).decode(), "Je t'aime très fort"
- )
- def test_send_long_lines(self):
- """
- Email line length is limited to 998 chars by the RFC 5322 Section
- 2.1.1.
- Message body containing longer lines are converted to Quoted-Printable
- to avoid having to insert newlines, which could be hairy to do properly.
- """
- # Unencoded body length is < 998 (840) but > 998 when utf-8 encoded.
- email = EmailMessage(
- "Subject", "В южных морях " * 60, "from@example.com", ["to@example.com"]
- )
- email.send()
- message = self.get_the_message()
- self.assertMessageHasHeaders(
- message,
- {
- ("MIME-Version", "1.0"),
- ("Content-Type", 'text/plain; charset="utf-8"'),
- ("Content-Transfer-Encoding", "quoted-printable"),
- },
- )
- def test_send_many(self):
- email1 = EmailMessage(
- "Subject", "Content1", "from@example.com", ["to@example.com"]
- )
- email2 = EmailMessage(
- "Subject", "Content2", "from@example.com", ["to@example.com"]
- )
- # send_messages() may take a list or an iterator.
- emails_lists = ([email1, email2], iter((email1, email2)))
- for emails_list in emails_lists:
- num_sent = mail.get_connection().send_messages(emails_list)
- self.assertEqual(num_sent, 2)
- messages = self.get_mailbox_content()
- self.assertEqual(len(messages), 2)
- self.assertEqual(messages[0].get_payload(), "Content1")
- self.assertEqual(messages[1].get_payload(), "Content2")
- self.flush_mailbox()
- def test_send_verbose_name(self):
- email = EmailMessage(
- "Subject",
- "Content",
- '"Firstname Sürname" <from@example.com>',
- ["to@example.com"],
- )
- email.send()
- message = self.get_the_message()
- self.assertEqual(message["subject"], "Subject")
- self.assertEqual(message.get_payload(), "Content")
- self.assertEqual(
- message["from"], "=?utf-8?q?Firstname_S=C3=BCrname?= <from@example.com>"
- )
- def test_plaintext_send_mail(self):
- """
- Test send_mail without the html_message
- regression test for adding html_message parameter to send_mail()
- """
- send_mail("Subject", "Content", "sender@example.com", ["nobody@example.com"])
- message = self.get_the_message()
- self.assertEqual(message.get("subject"), "Subject")
- self.assertEqual(message.get_all("to"), ["nobody@example.com"])
- self.assertFalse(message.is_multipart())
- self.assertEqual(message.get_payload(), "Content")
- self.assertEqual(message.get_content_type(), "text/plain")
- def test_html_send_mail(self):
- """Test html_message argument to send_mail"""
- send_mail(
- "Subject",
- "Content",
- "sender@example.com",
- ["nobody@example.com"],
- html_message="HTML Content",
- )
- message = self.get_the_message()
- self.assertEqual(message.get("subject"), "Subject")
- self.assertEqual(message.get_all("to"), ["nobody@example.com"])
- self.assertTrue(message.is_multipart())
- self.assertEqual(len(message.get_payload()), 2)
- self.assertEqual(message.get_payload(0).get_payload(), "Content")
- self.assertEqual(message.get_payload(0).get_content_type(), "text/plain")
- self.assertEqual(message.get_payload(1).get_payload(), "HTML Content")
- self.assertEqual(message.get_payload(1).get_content_type(), "text/html")
- @override_settings(MANAGERS=[("nobody", "nobody@example.com")])
- def test_html_mail_managers(self):
- """Test html_message argument to mail_managers"""
- mail_managers("Subject", "Content", html_message="HTML Content")
- message = self.get_the_message()
- self.assertEqual(message.get("subject"), "[Django] Subject")
- self.assertEqual(message.get_all("to"), ["nobody@example.com"])
- self.assertTrue(message.is_multipart())
- self.assertEqual(len(message.get_payload()), 2)
- self.assertEqual(message.get_payload(0).get_payload(), "Content")
- self.assertEqual(message.get_payload(0).get_content_type(), "text/plain")
- self.assertEqual(message.get_payload(1).get_payload(), "HTML Content")
- self.assertEqual(message.get_payload(1).get_content_type(), "text/html")
- @override_settings(ADMINS=[("nobody", "nobody@example.com")])
- def test_html_mail_admins(self):
- """Test html_message argument to mail_admins"""
- mail_admins("Subject", "Content", html_message="HTML Content")
- message = self.get_the_message()
- self.assertEqual(message.get("subject"), "[Django] Subject")
- self.assertEqual(message.get_all("to"), ["nobody@example.com"])
- self.assertTrue(message.is_multipart())
- self.assertEqual(len(message.get_payload()), 2)
- self.assertEqual(message.get_payload(0).get_payload(), "Content")
- self.assertEqual(message.get_payload(0).get_content_type(), "text/plain")
- self.assertEqual(message.get_payload(1).get_payload(), "HTML Content")
- self.assertEqual(message.get_payload(1).get_content_type(), "text/html")
- @override_settings(
- ADMINS=[("nobody", "nobody+admin@example.com")],
- MANAGERS=[("nobody", "nobody+manager@example.com")],
- )
- def test_manager_and_admin_mail_prefix(self):
- """
- String prefix + lazy translated subject = bad output
- Regression for #13494
- """
- mail_managers(gettext_lazy("Subject"), "Content")
- message = self.get_the_message()
- self.assertEqual(message.get("subject"), "[Django] Subject")
- self.flush_mailbox()
- mail_admins(gettext_lazy("Subject"), "Content")
- message = self.get_the_message()
- self.assertEqual(message.get("subject"), "[Django] Subject")
- @override_settings(ADMINS=[], MANAGERS=[])
- def test_empty_admins(self):
- """
- mail_admins/mail_managers doesn't connect to the mail server
- if there are no recipients (#9383)
- """
- mail_admins("hi", "there")
- self.assertEqual(self.get_mailbox_content(), [])
- mail_managers("hi", "there")
- self.assertEqual(self.get_mailbox_content(), [])
- def test_wrong_admins_managers(self):
- tests = (
- "test@example.com",
- ("test@example.com",),
- ["test@example.com", "other@example.com"],
- ("test@example.com", "other@example.com"),
- )
- for setting, mail_func in (
- ("ADMINS", mail_admins),
- ("MANAGERS", mail_managers),
- ):
- msg = "The %s setting must be a list of 2-tuples." % setting
- for value in tests:
- with (
- self.subTest(setting=setting, value=value),
- self.settings(**{setting: value}),
- ):
- with self.assertRaisesMessage(ValueError, msg):
- mail_func("subject", "content")
- def test_message_cc_header(self):
- """
- Regression test for #7722
- """
- email = EmailMessage(
- "Subject",
- "Content",
- "from@example.com",
- ["to@example.com"],
- cc=["cc@example.com"],
- )
- mail.get_connection().send_messages([email])
- message = self.get_the_message()
- self.assertMessageHasHeaders(
- message,
- {
- ("MIME-Version", "1.0"),
- ("Content-Type", 'text/plain; charset="utf-8"'),
- ("Content-Transfer-Encoding", "7bit"),
- ("Subject", "Subject"),
- ("From", "from@example.com"),
- ("To", "to@example.com"),
- ("Cc", "cc@example.com"),
- },
- )
- self.assertIn("\nDate: ", message.as_string())
- def test_idn_send(self):
- """
- Regression test for #14301
- """
- self.assertTrue(send_mail("Subject", "Content", "from@öäü.com", ["to@öäü.com"]))
- message = self.get_the_message()
- self.assertEqual(message.get("subject"), "Subject")
- self.assertEqual(message.get("from"), "from@xn--4ca9at.com")
- self.assertEqual(message.get("to"), "to@xn--4ca9at.com")
- self.flush_mailbox()
- m = EmailMessage(
- "Subject", "Content", "from@öäü.com", ["to@öäü.com"], cc=["cc@öäü.com"]
- )
- m.send()
- message = self.get_the_message()
- self.assertEqual(message.get("subject"), "Subject")
- self.assertEqual(message.get("from"), "from@xn--4ca9at.com")
- self.assertEqual(message.get("to"), "to@xn--4ca9at.com")
- self.assertEqual(message.get("cc"), "cc@xn--4ca9at.com")
- def test_recipient_without_domain(self):
- """
- Regression test for #15042
- """
- self.assertTrue(send_mail("Subject", "Content", "tester", ["django"]))
- message = self.get_the_message()
- self.assertEqual(message.get("subject"), "Subject")
- self.assertEqual(message.get("from"), "tester")
- self.assertEqual(message.get("to"), "django")
- def test_lazy_addresses(self):
- """
- Email sending should support lazy email addresses (#24416).
- """
- _ = gettext_lazy
- self.assertTrue(send_mail("Subject", "Content", _("tester"), [_("django")]))
- message = self.get_the_message()
- self.assertEqual(message.get("from"), "tester")
- self.assertEqual(message.get("to"), "django")
- self.flush_mailbox()
- m = EmailMessage(
- "Subject",
- "Content",
- _("tester"),
- [_("to1"), _("to2")],
- cc=[_("cc1"), _("cc2")],
- bcc=[_("bcc")],
- reply_to=[_("reply")],
- )
- self.assertEqual(m.recipients(), ["to1", "to2", "cc1", "cc2", "bcc"])
- m.send()
- message = self.get_the_message()
- self.assertEqual(message.get("from"), "tester")
- self.assertEqual(message.get("to"), "to1, to2")
- self.assertEqual(message.get("cc"), "cc1, cc2")
- self.assertEqual(message.get("Reply-To"), "reply")
- def test_close_connection(self):
- """
- Connection can be closed (even when not explicitly opened)
- """
- conn = mail.get_connection(username="", password="")
- conn.close()
- def test_use_as_contextmanager(self):
- """
- The connection can be used as a contextmanager.
- """
- opened = [False]
- closed = [False]
- conn = mail.get_connection(username="", password="")
- def open():
- opened[0] = True
- conn.open = open
- def close():
- closed[0] = True
- conn.close = close
- with conn as same_conn:
- self.assertTrue(opened[0])
- self.assertIs(same_conn, conn)
- self.assertFalse(closed[0])
- self.assertTrue(closed[0])
- class LocmemBackendTests(BaseEmailBackendTests, SimpleTestCase):
- email_backend = "django.core.mail.backends.locmem.EmailBackend"
- def get_mailbox_content(self):
- return [m.message() for m in mail.outbox]
- def flush_mailbox(self):
- mail.outbox = []
- def tearDown(self):
- super().tearDown()
- mail.outbox = []
- def test_locmem_shared_messages(self):
- """
- Make sure that the locmen backend populates the outbox.
- """
- connection = locmem.EmailBackend()
- connection2 = locmem.EmailBackend()
- email = EmailMessage(
- "Subject",
- "Content",
- "bounce@example.com",
- ["to@example.com"],
- headers={"From": "from@example.com"},
- )
- connection.send_messages([email])
- connection2.send_messages([email])
- self.assertEqual(len(mail.outbox), 2)
- def test_validate_multiline_headers(self):
- # Ticket #18861 - Validate emails when using the locmem backend
- with self.assertRaises(BadHeaderError):
- send_mail(
- "Subject\nMultiline", "Content", "from@example.com", ["to@example.com"]
- )
- def test_outbox_not_mutated_after_send(self):
- email = EmailMessage(
- subject="correct subject",
- body="test body",
- from_email="from@example.com",
- to=["to@example.com"],
- )
- email.send()
- email.subject = "other subject"
- email.to.append("other@example.com")
- self.assertEqual(mail.outbox[0].subject, "correct subject")
- self.assertEqual(mail.outbox[0].to, ["to@example.com"])
- class FileBackendTests(BaseEmailBackendTests, SimpleTestCase):
- email_backend = "django.core.mail.backends.filebased.EmailBackend"
- def setUp(self):
- super().setUp()
- self.tmp_dir = self.mkdtemp()
- self.addCleanup(shutil.rmtree, self.tmp_dir)
- _settings_override = override_settings(EMAIL_FILE_PATH=self.tmp_dir)
- _settings_override.enable()
- self.addCleanup(_settings_override.disable)
- def mkdtemp(self):
- return tempfile.mkdtemp()
- def flush_mailbox(self):
- for filename in os.listdir(self.tmp_dir):
- os.unlink(os.path.join(self.tmp_dir, filename))
- def get_mailbox_content(self):
- messages = []
- for filename in os.listdir(self.tmp_dir):
- with open(os.path.join(self.tmp_dir, filename), "rb") as fp:
- session = fp.read().split(b"\n" + (b"-" * 79) + b"\n")
- messages.extend(message_from_bytes(m) for m in session if m)
- return messages
- def test_file_sessions(self):
- """Make sure opening a connection creates a new file"""
- msg = EmailMessage(
- "Subject",
- "Content",
- "bounce@example.com",
- ["to@example.com"],
- headers={"From": "from@example.com"},
- )
- connection = mail.get_connection()
- connection.send_messages([msg])
- self.assertEqual(len(os.listdir(self.tmp_dir)), 1)
- with open(os.path.join(self.tmp_dir, os.listdir(self.tmp_dir)[0]), "rb") as fp:
- message = message_from_binary_file(fp)
- self.assertEqual(message.get_content_type(), "text/plain")
- self.assertEqual(message.get("subject"), "Subject")
- self.assertEqual(message.get("from"), "from@example.com")
- self.assertEqual(message.get("to"), "to@example.com")
- connection2 = mail.get_connection()
- connection2.send_messages([msg])
- self.assertEqual(len(os.listdir(self.tmp_dir)), 2)
- connection.send_messages([msg])
- self.assertEqual(len(os.listdir(self.tmp_dir)), 2)
- msg.connection = mail.get_connection()
- self.assertTrue(connection.open())
- msg.send()
- self.assertEqual(len(os.listdir(self.tmp_dir)), 3)
- msg.send()
- self.assertEqual(len(os.listdir(self.tmp_dir)), 3)
- connection.close()
- class FileBackendPathLibTests(FileBackendTests):
- def mkdtemp(self):
- tmp_dir = super().mkdtemp()
- return Path(tmp_dir)
- class ConsoleBackendTests(BaseEmailBackendTests, SimpleTestCase):
- email_backend = "django.core.mail.backends.console.EmailBackend"
- def setUp(self):
- super().setUp()
- self.__stdout = sys.stdout
- self.stream = sys.stdout = StringIO()
- def tearDown(self):
- del self.stream
- sys.stdout = self.__stdout
- del self.__stdout
- super().tearDown()
- def flush_mailbox(self):
- self.stream = sys.stdout = StringIO()
- def get_mailbox_content(self):
- messages = self.stream.getvalue().split("\n" + ("-" * 79) + "\n")
- return [message_from_bytes(m.encode()) for m in messages if m]
- def test_console_stream_kwarg(self):
- """
- The console backend can be pointed at an arbitrary stream.
- """
- s = StringIO()
- connection = mail.get_connection(
- "django.core.mail.backends.console.EmailBackend", stream=s
- )
- send_mail(
- "Subject",
- "Content",
- "from@example.com",
- ["to@example.com"],
- connection=connection,
- )
- message = s.getvalue().split("\n" + ("-" * 79) + "\n")[0].encode()
- self.assertMessageHasHeaders(
- message,
- {
- ("MIME-Version", "1.0"),
- ("Content-Type", 'text/plain; charset="utf-8"'),
- ("Content-Transfer-Encoding", "7bit"),
- ("Subject", "Subject"),
- ("From", "from@example.com"),
- ("To", "to@example.com"),
- },
- )
- self.assertIn(b"\nDate: ", message)
- class SMTPHandler:
- def __init__(self, *args, **kwargs):
- self.mailbox = []
- async def handle_DATA(self, server, session, envelope):
- data = envelope.content
- mail_from = envelope.mail_from
- message = message_from_bytes(data.rstrip())
- message_addr = parseaddr(message.get("from"))[1]
- if mail_from != message_addr:
- # According to the spec, mail_from does not necessarily match the
- # From header - this is the case where the local part isn't
- # encoded, so try to correct that.
- lp, domain = mail_from.split("@", 1)
- lp = Header(lp, "utf-8").encode()
- mail_from = "@".join([lp, domain])
- if mail_from != message_addr:
- return f"553 '{mail_from}' != '{message_addr}'"
- self.mailbox.append(message)
- return "250 OK"
- def flush_mailbox(self):
- self.mailbox[:] = []
- @skipUnless(HAS_AIOSMTPD, "No aiosmtpd library detected.")
- class SMTPBackendTestsBase(SimpleTestCase):
- @classmethod
- def setUpClass(cls):
- super().setUpClass()
- # Find a free port.
- with socket.socket() as s:
- s.bind(("127.0.0.1", 0))
- port = s.getsockname()[1]
- cls.smtp_handler = SMTPHandler()
- cls.smtp_controller = Controller(
- cls.smtp_handler,
- hostname="127.0.0.1",
- port=port,
- )
- cls._settings_override = override_settings(
- EMAIL_HOST=cls.smtp_controller.hostname,
- EMAIL_PORT=cls.smtp_controller.port,
- )
- cls._settings_override.enable()
- cls.addClassCleanup(cls._settings_override.disable)
- cls.smtp_controller.start()
- cls.addClassCleanup(cls.stop_smtp)
- @classmethod
- def stop_smtp(cls):
- cls.smtp_controller.stop()
- @skipUnless(HAS_AIOSMTPD, "No aiosmtpd library detected.")
- class SMTPBackendTests(BaseEmailBackendTests, SMTPBackendTestsBase):
- email_backend = "django.core.mail.backends.smtp.EmailBackend"
- def setUp(self):
- super().setUp()
- self.smtp_handler.flush_mailbox()
- self.addCleanup(self.smtp_handler.flush_mailbox)
- def flush_mailbox(self):
- self.smtp_handler.flush_mailbox()
- def get_mailbox_content(self):
- return self.smtp_handler.mailbox
- @override_settings(
- EMAIL_HOST_USER="not empty username",
- EMAIL_HOST_PASSWORD="not empty password",
- )
- def test_email_authentication_use_settings(self):
- backend = smtp.EmailBackend()
- self.assertEqual(backend.username, "not empty username")
- self.assertEqual(backend.password, "not empty password")
- @override_settings(
- EMAIL_HOST_USER="not empty username",
- EMAIL_HOST_PASSWORD="not empty password",
- )
- def test_email_authentication_override_settings(self):
- backend = smtp.EmailBackend(username="username", password="password")
- self.assertEqual(backend.username, "username")
- self.assertEqual(backend.password, "password")
- @override_settings(
- EMAIL_HOST_USER="not empty username",
- EMAIL_HOST_PASSWORD="not empty password",
- )
- def test_email_disabled_authentication(self):
- backend = smtp.EmailBackend(username="", password="")
- self.assertEqual(backend.username, "")
- self.assertEqual(backend.password, "")
- def test_auth_attempted(self):
- """
- Opening the backend with non empty username/password tries
- to authenticate against the SMTP server.
- """
- backend = smtp.EmailBackend(
- username="not empty username", password="not empty password"
- )
- with self.assertRaisesMessage(
- SMTPException, "SMTP AUTH extension not supported by server."
- ):
- with backend:
- pass
- def test_server_open(self):
- """
- open() returns whether it opened a connection.
- """
- backend = smtp.EmailBackend(username="", password="")
- self.assertIsNone(backend.connection)
- opened = backend.open()
- backend.close()
- self.assertIs(opened, True)
- def test_reopen_connection(self):
- backend = smtp.EmailBackend()
- # Simulate an already open connection.
- backend.connection = mock.Mock(spec=object())
- self.assertIs(backend.open(), False)
- @override_settings(EMAIL_USE_TLS=True)
- def test_email_tls_use_settings(self):
- backend = smtp.EmailBackend()
- self.assertTrue(backend.use_tls)
- @override_settings(EMAIL_USE_TLS=True)
- def test_email_tls_override_settings(self):
- backend = smtp.EmailBackend(use_tls=False)
- self.assertFalse(backend.use_tls)
- def test_email_tls_default_disabled(self):
- backend = smtp.EmailBackend()
- self.assertFalse(backend.use_tls)
- def test_ssl_tls_mutually_exclusive(self):
- msg = (
- "EMAIL_USE_TLS/EMAIL_USE_SSL are mutually exclusive, so only set "
- "one of those settings to True."
- )
- with self.assertRaisesMessage(ValueError, msg):
- smtp.EmailBackend(use_ssl=True, use_tls=True)
- @override_settings(EMAIL_USE_SSL=True)
- def test_email_ssl_use_settings(self):
- backend = smtp.EmailBackend()
- self.assertTrue(backend.use_ssl)
- @override_settings(EMAIL_USE_SSL=True)
- def test_email_ssl_override_settings(self):
- backend = smtp.EmailBackend(use_ssl=False)
- self.assertFalse(backend.use_ssl)
- def test_email_ssl_default_disabled(self):
- backend = smtp.EmailBackend()
- self.assertFalse(backend.use_ssl)
- @override_settings(EMAIL_SSL_CERTFILE="foo")
- def test_email_ssl_certfile_use_settings(self):
- backend = smtp.EmailBackend()
- self.assertEqual(backend.ssl_certfile, "foo")
- @override_settings(EMAIL_SSL_CERTFILE="foo")
- def test_email_ssl_certfile_override_settings(self):
- backend = smtp.EmailBackend(ssl_certfile="bar")
- self.assertEqual(backend.ssl_certfile, "bar")
- def test_email_ssl_certfile_default_disabled(self):
- backend = smtp.EmailBackend()
- self.assertIsNone(backend.ssl_certfile)
- @override_settings(EMAIL_SSL_KEYFILE="foo")
- def test_email_ssl_keyfile_use_settings(self):
- backend = smtp.EmailBackend()
- self.assertEqual(backend.ssl_keyfile, "foo")
- @override_settings(EMAIL_SSL_KEYFILE="foo")
- def test_email_ssl_keyfile_override_settings(self):
- backend = smtp.EmailBackend(ssl_keyfile="bar")
- self.assertEqual(backend.ssl_keyfile, "bar")
- def test_email_ssl_keyfile_default_disabled(self):
- backend = smtp.EmailBackend()
- self.assertIsNone(backend.ssl_keyfile)
- @override_settings(EMAIL_USE_TLS=True)
- def test_email_tls_attempts_starttls(self):
- backend = smtp.EmailBackend()
- self.assertTrue(backend.use_tls)
- with self.assertRaisesMessage(
- SMTPException, "STARTTLS extension not supported by server."
- ):
- with backend:
- pass
- @override_settings(EMAIL_USE_SSL=True)
- def test_email_ssl_attempts_ssl_connection(self):
- backend = smtp.EmailBackend()
- self.assertTrue(backend.use_ssl)
- with self.assertRaises(SSLError):
- with backend:
- pass
- def test_connection_timeout_default(self):
- """The connection's timeout value is None by default."""
- connection = mail.get_connection("django.core.mail.backends.smtp.EmailBackend")
- self.assertIsNone(connection.timeout)
- def test_connection_timeout_custom(self):
- """The timeout parameter can be customized."""
- class MyEmailBackend(smtp.EmailBackend):
- def __init__(self, *args, **kwargs):
- kwargs.setdefault("timeout", 42)
- super().__init__(*args, **kwargs)
- myemailbackend = MyEmailBackend()
- myemailbackend.open()
- self.assertEqual(myemailbackend.timeout, 42)
- self.assertEqual(myemailbackend.connection.timeout, 42)
- myemailbackend.close()
- @override_settings(EMAIL_TIMEOUT=10)
- def test_email_timeout_override_settings(self):
- backend = smtp.EmailBackend()
- self.assertEqual(backend.timeout, 10)
- def test_email_msg_uses_crlf(self):
- """#23063 -- RFC-compliant messages are sent over SMTP."""
- send = SMTP.send
- try:
- smtp_messages = []
- def mock_send(self, s):
- smtp_messages.append(s)
- return send(self, s)
- SMTP.send = mock_send
- email = EmailMessage(
- "Subject", "Content", "from@example.com", ["to@example.com"]
- )
- mail.get_connection().send_messages([email])
- # Find the actual message
- msg = None
- for i, m in enumerate(smtp_messages):
- if m[:4] == "data":
- msg = smtp_messages[i + 1]
- break
- self.assertTrue(msg)
- msg = msg.decode()
- # The message only contains CRLF and not combinations of CRLF, LF, and CR.
- msg = msg.replace("\r\n", "")
- self.assertNotIn("\r", msg)
- self.assertNotIn("\n", msg)
- finally:
- SMTP.send = send
- def test_send_messages_after_open_failed(self):
- """
- send_messages() shouldn't try to send messages if open() raises an
- exception after initializing the connection.
- """
- backend = smtp.EmailBackend()
- # Simulate connection initialization success and a subsequent
- # connection exception.
- backend.connection = mock.Mock(spec=object())
- backend.open = lambda: None
- email = EmailMessage(
- "Subject", "Content", "from@example.com", ["to@example.com"]
- )
- self.assertEqual(backend.send_messages([email]), 0)
- def test_send_messages_empty_list(self):
- backend = smtp.EmailBackend()
- backend.connection = mock.Mock(spec=object())
- self.assertEqual(backend.send_messages([]), 0)
- def test_send_messages_zero_sent(self):
- """A message isn't sent if it doesn't have any recipients."""
- backend = smtp.EmailBackend()
- backend.connection = mock.Mock(spec=object())
- email = EmailMessage("Subject", "Content", "from@example.com", to=[])
- sent = backend.send_messages([email])
- self.assertEqual(sent, 0)
- @skipUnless(HAS_AIOSMTPD, "No aiosmtpd library detected.")
- class SMTPBackendStoppedServerTests(SMTPBackendTestsBase):
- @classmethod
- def setUpClass(cls):
- super().setUpClass()
- cls.backend = smtp.EmailBackend(username="", password="")
- cls.smtp_controller.stop()
- @classmethod
- def stop_smtp(cls):
- # SMTP controller is stopped in setUpClass().
- pass
- def test_server_stopped(self):
- """
- Closing the backend while the SMTP server is stopped doesn't raise an
- exception.
- """
- self.backend.close()
- def test_fail_silently_on_connection_error(self):
- """
- A socket connection error is silenced with fail_silently=True.
- """
- with self.assertRaises(ConnectionError):
- self.backend.open()
- self.backend.fail_silently = True
- self.backend.open()
|