Skip to content

EmailMessage(policy=SMTPUTF8).as_bytes() fails to encode non-ASCII Subject in 3.12 #133442

Open
@JimmyLuojun

Description

@JimmyLuojun

Bug report

Bug description:

# Add a code block here, if required
# test_subject_encoding.py
from email.message import EmailMessage
from email.policy import SMTPUTF8
import sys

# Use one of the subject strings that caused issues
# Make sure this is the exact string causing Mojibake
subject = 'Vectorsentinel与Drone Volt合作共赢,探索无人机安防新机遇'

print(f"Python Version: {sys.version}")
print(f"Testing subject: {repr(subject)}")

msg = EmailMessage(policy=SMTPUTF8)
msg['From'] = '[email protected]'
msg['To'] = '[email protected]'
# Use standard assignment
msg['Subject'] = subject
msg.set_content('Test body content.')

print("\n--- Message As String ---")
try:
    # Use as_string() which should also trigger encoding
    print(msg.as_string())
except Exception as e:
    print(f"Error during as_string(): {e}\n")

print("\n--- Message As Bytes (Decoded) ---")
try:
    # Use as_bytes() and decode for printing
    # We are primarily interested in the Subject: line format
    message_bytes = msg.as_bytes()
    print(message_bytes.decode('utf-8', 'replace')) # Use utf-8 decode
except Exception as e:
    print(f"Error during as_bytes(): {e}\n")
Python Version: 3.12.0 (main, Jan  4 2025, 13:42:56) [Clang 16.0.0 (clang-1600.0.26.6)]
Testing subject: 'Vectorsentinel与Drone Volt合作共赢,探索无人机安防新机遇'

--- Message As String ---
From: [email protected]
To: [email protected]
Subject: Vectorsentinel与Drone Volt合作共赢,探索无人机安防新机遇
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 7bit
MIME-Version: 1.0

Test body content.


--- Message As Bytes (Decoded) ---
From: [email protected]
To: [email protected]
Subject: Vectorsentinel与Drone Volt合作共赢,探索无人机安防新机遇
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 7bit
MIME-Version: 1.0

Test body content.

CPython versions tested on:

3.12

Operating systems tested on:

macOS

Metadata

Metadata

Assignees

No one assigned

    Labels

    pendingThe issue will be closed if no feedback is providedstdlibPython modules in the Lib dirtopic-emailtype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions