diff --git a/tests/mail/tests.py b/tests/mail/tests.py index dd6b72ab49..9e55398d60 100644 --- a/tests/mail/tests.py +++ b/tests/mail/tests.py @@ -92,6 +92,37 @@ class MailTests(HeadersCheckMixin, SimpleTestCase): 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",