GAE Python - 如何在邮件正文中编码特殊字符?
我想在谷歌应用引擎上用Python发送订单通知。问题是邮件的内容可能包含一些特殊字符,比如'öäü',但我找不到修改内容类型中字符集的办法。
有没有办法把字符集从charset="us-ascii"改成比如"utf-8",同时还能继续使用谷歌应用引擎的邮件API,或者有没有其他的解决办法?比如添加一个参数Content-transfer-encoding: quoted-printable?
这是我发送通知的尝试:
from google.appengine.ext import db
from google.appengine.api import mail
from email.header import Header
def encode_mail_header(line):
return Header(line, 'utf-8').encode()
msg = u"Message with some chars like öäüßéèô..."
subject = encode_mail_header(u"Hans Müller your Ticket")
sender = "My Service <notification+@localhost.de>"
to = encode_mail_header(u"Hans Müller")
to += " <hans.mueller@localhost>"
message = mail.EmailMessage(sender=sender,
to=to,
subject=subject,
body=msg)
message.send()
从我的开发服务器收到的邮件代码:
Received: from spooler by localhost (Mercury/32 v4.62); 26 Mar 2013 10:50:35 +0100
X-Envelope-To: <hans.mueller@localhost>
Return-path: <notification+@localhost.de>
Received: from [192.168.56.1] (127.0.0.1) by localhost (Mercury/32 v4.62) with ESMTP ID MG000011;
26 Mar 2013 10:50:24 +0100
Content-Type: multipart/mixed; boundary="===============1598388400=="
MIME-Version: 1.0
To: =?utf-8?q?Hans_M=C3=BCller?= <hans.mueller@localhost>
From: My Service <notification+@localhost.de>
Reply-To:
Subject: =?utf-8?q?Hans_M=C3=BCller_your_Ticket?=
X-UC-Weight: [# ] 51
X-CC-Diagnostic: Not Header "Date" Exists (51)
--===============1598388400==
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 8bit
Message with some chars like öäüßéèô...
--===============1598388400==--
谢谢你的帮助
1 个回答
1
我们使用以下代码:
message = mail.EmailMessage()
message.subject = "=?utf-8?B?%s?=" % base64.b64encode( u"üäö".encode("UTF-8") )
message.html = u"üäö".encode('ascii', 'xmlcharrefreplace')
这段代码的意思是,我们在创建一个邮件消息。首先,我们用 mail.EmailMessage()
来生成一个新的邮件对象。
接着,我们设置邮件的主题。这里的主题使用了一种特殊的编码方式,确保即使是包含特殊字符(比如“ü”、“ä”、“ö”)的内容也能正确显示。我们先把这些字符用 UTF-8 编码,然后再用 base64 编码,这样就能把它们转成一种安全的格式。
最后,我们设置邮件的 HTML 内容。这里我们把同样的字符用另一种方式编码成 ASCII 格式,并用一种叫做“xmlcharrefreplace”的方法来处理那些不能直接用 ASCII 表示的字符,这样可以确保邮件在不同的邮件客户端中都能正确显示。