If I create a message this way (using real addresses, of course):
msg = email.message.EmailMessage()
msg['From'] = "sender@example.com"
msg['To'] = "recipient@example.com"
msg['Subject'] = "Ayons asperges pour le déjeuner"
msg.set_content("Cela ressemble à un excellent recipie déjeuner.")
I can successfully send it using smtplib. No problem with the Unicode characters in the body. The received message has these headers:
Content-Type: text/plain; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: quoted-printable
If I try to create the same message in this alternative way:
msgsource = """\
From: sender@example.com
To: recipient@example.com
Subject: Ayons asperges pour le déjeuner
Cela ressemble à un excellent recipie déjeuner.
"""
msg = email.parser.Parser(policy=email.policy.default).parsestr(msgsource)
I can't send it. send_message() from smtplib fails with
UnicodeEncodeError: 'ascii' codec can't encode character '\xe0' in position 15: ordinal not in range(128)
and obviously expects ascii, not Unicode. What causes the difference and how to fix it properly?
(code is based on these examples)