Debian Codegraph @

tests/mail/tests.py

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