如果我以這種方式創建訊息(當然,使用真實地址):
msg = email.message.EmailMessage()
msg['From'] = "[email protected]"
msg['To'] = "[email protected]"
msg['Subject'] = "Ayons asperges pour le déjeuner"
msg.set_content("Cela ressemble à un excellent recipie déjeuner.")
我可以使用smtplib. 正文中的 Unicode 字符沒有問題。收到的訊息具有以下標頭:
Content-Type: text/plain; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: quoted-printable
如果我嘗試以這種替代方式創建相同的訊息:
msgsource = """\
From: [email protected]
To: [email protected]
Subject: Ayons asperges pour le déjeuner
Cela ressemble à un excellent recipie déjeuner.
"""
msg = email.parser.Parser(policy=email.policy.default).parsestr(msgsource)
我無法發送。send_message()從smtplib失敗
UnicodeEncodeError: 'ascii' codec can't encode character '\xe0' in position 15: ordinal not in range(128)
并且顯然需要 ascii,而不是 Unicode。是什么導致了差異以及如何正確修復它?
(代碼基于這些示例)
uj5u.com熱心網友回復:
可以通過編碼msgsource然后決議結果位元組來避免錯誤:
msgsource = msgsource.encode('utf-8')
msg = email.message_from_bytes(msgsource, policy=policy.default)
print(msg)
產出
From: [email protected]
To: [email protected]
Subject: Ayons asperges pour le =?unknown-8bit?q?d=C3=A9jeuner?=
Cela ressemble ?? un excellent recipie d??jeuner.
將它發送到 Python 的 SMTP DebuggingServer 產生
b'From: [email protected]'
b'To: [email protected]'
b'Subject: Ayons asperges pour le d\xc3\xa9jeuner'
b'X-Peer: ::1'
b''
b'Cela ressemble \xc3\xa0 un excellent recipie d\xc3\xa9jeuner.'
請注意,沒有寫入編碼頭:我猜測決議器會盡可能忠實地從源字串或位元組中重現訊息,并盡可能少做額外的假設。決議器檔案
[決議器是]一種API,當訊息的完整內容在[字串/位元組/檔案]中可用時,可用于決議訊息
在我看來,支持這種解釋。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/312936.html
