summaryrefslogtreecommitdiff
path: root/django/core
diff options
context:
space:
mode:
authorMike Edmunds <medmunds@gmail.com>2025-06-18 20:34:34 -0700
committerSarah Boyce <42296566+sarahboyce@users.noreply.github.com>2025-06-26 08:54:01 +0200
commit23529b662793cdf4725d5f8ff58f0df94b343365 (patch)
tree4d7d62237ce8f57c64e7d7c9f77e89fec3cdb59a /django/core
parent68a45d9a8078db642f0aca7ddab33af6df7ebeb3 (diff)
Fixed #36478 -- Fixed inconsistent mail attachment handling.
Fixed an inconsistency between EmailMessage.attach() and .attachments when attaching bytes content with a text/* mimetype. The attach() function decodes UTF-8 bytes if possible and otherwise changes the mimetype to application/octet-stream to preserve the content's unknown encoding (refs #27007). Providing equivalent content directly in EmailMessage.attachments did not apply the same logic, leading to an "AttributeError: 'bytes' object has no attribute 'encode'" in SafeMIMEText.set_payload(). Updated EmailMessage._create_mime_attachment() to match attach()'s handling for text/* mimetypes with bytes content. Updated test cases to accurately cover behavior on both paths.
Diffstat (limited to 'django/core')
-rw-r--r--django/core/mail/message.py9
1 files changed, 9 insertions, 0 deletions
diff --git a/django/core/mail/message.py b/django/core/mail/message.py
index 421e353bfa..51af560b12 100644
--- a/django/core/mail/message.py
+++ b/django/core/mail/message.py
@@ -387,6 +387,15 @@ class EmailMessage:
email.Message or EmailMessage object, as well as a str.
"""
basetype, subtype = mimetype.split("/", 1)
+ if basetype == "text" and isinstance(content, bytes):
+ # This duplicates logic from EmailMessage.attach() to properly
+ # handle EmailMessage.attachments not created through attach().
+ try:
+ content = content.decode()
+ except UnicodeDecodeError:
+ mimetype = DEFAULT_ATTACHMENT_MIME_TYPE
+ basetype, subtype = mimetype.split("/", 1)
+
if basetype == "text":
encoding = self.encoding or settings.DEFAULT_CHARSET
attachment = SafeMIMEText(content, subtype, encoding)