在 Python 中使用非 ASCII 字符对邮件主题 (SMTP) 进行编码
我使用 Python 模块 MimeWriter
构建消息,并使用 smtplib 发送邮件 构建的消息是:
file msg.txt:
-----------------------
Content-Type: multipart/mixed;
from: me<[email protected]>
to: [email protected]
subject: 主題
Content-Type: text/plain;charset=utf-8
主題
我使用下面的代码发送邮件:
import smtplib
s=smtplib.SMTP('smtp.abc.com')
toList = ['[email protected]']
f=open('msg.txt') #above msg in msg.txt file
msg=f.read()
f.close()
s.sendmail('[email protected]',toList,msg)
我正确获取邮件正文,但主题不正确,
subject: some junk characters
主題 <- body is correct.
请提出建议?有没有办法指定用于主题的解码, 正如为身体指定的那样。如何正确解码主题?
I am using Python module MimeWriter
to construct a message and smtplib to send a mail constructed message is:
file msg.txt:
-----------------------
Content-Type: multipart/mixed;
from: me<[email protected]>
to: [email protected]
subject: 主題
Content-Type: text/plain;charset=utf-8
主題
I use the code below to send a mail:
import smtplib
s=smtplib.SMTP('smtp.abc.com')
toList = ['[email protected]']
f=open('msg.txt') #above msg in msg.txt file
msg=f.read()
f.close()
s.sendmail('[email protected]',toList,msg)
I get mail body correctly but subject is not proper,
subject: some junk characters
主題 <- body is correct.
Please suggest? Is there any way to specify the decoding to be used for the subject also,
as being specified for the body. How can I get the subject decoded correctly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
来自 http://docs.python.org/library/email.header.html
更简单:
作为补码解码可以使用:
参考:
Python - 电子邮件标头解码 UTF-8
From http://docs.python.org/library/email.header.html
more simple:
as complement decode may made with:
Reference:
Python - email header decoding UTF-8
主题作为 SMTP 标头传输,并且它们必须仅是 ASCII。为了支持主题中的编码,您需要在主题前加上您想要使用的任何编码的前缀。对于您的情况,我建议在主题前加上“UTF-8”B?这意味着 UTF-8,Base64 编码。
换句话说,我相信你的主题头应该或多或少看起来像这样:
在 PHP 中,你可以这样处理:
在 Python 中:
The subject is transmitted as an SMTP header, and they are required to be ASCII-only. To support encodings in the subject you need to prefix the subject with whatever encoding you want to use. In your case, I would suggest prefix the subject with ?UTF-8?B? which means UTF-8, Base64 encoded.
In other words, I believe your subject header should more or less look like this:
In PHP you could go about it like this:
In Python:
简而言之,如果您使用
EmailMessage
API,您应该像这样编写代码:@Sérgio 的回答不能在
EmailMessage
API 中使用,因为仅字符串对象< /strong> 可以分配给EmailMessage()["Subject"]
,但不能分配给email.header.Header
对象。In short, if you use the
EmailMessage
API, you should code like this:Answer from @Sérgio cannot be used in the
EmailMessage
API, cause only string object can be assigned toEmailMessage()["Subject"]
, but not anemail.header.Header
object.