在 Python 中使用非 ASCII 字符编码邮件主题 (SMTP)
问题描述
我使用 Python 模块 MimeWriter
构造消息和 smtplib 发送邮件构造消息是:
文件 msg.txt:----------------------内容类型:多部分/混合;来自:我<me@abc.com>至:me@abc.com主题:主题内容类型:text/plain;charset=utf-8主题
我使用下面的代码发送邮件:
导入 smtplibs=smtplib.SMTP('smtp.abc.com')toList = ['me@abc.com']f=open('msg.txt') #高于 msg.txt 文件中的 msg味精=f.read()f.close()s.sendmail('me@abc.com',toList,msg)
我的邮件正文正确,但主题不正确,
主题:一些垃圾字符主题 <- 正文是正确的.
请建议?有没有办法指定用于主题的解码,为身体指定.如何正确解码主题?
解决方案来自 http://docs.python.org/library/email.header.html
从 email.message 导入消息从 email.header 导入标头味精=消息()msg['Subject'] = Header('主题', 'utf-8')打印 msg.as_string()
<块引用>
主题:=?utf-8?b?5Li76aGM?=
更简单:
from email.header import Headerprint Header('主题', 'utf-8').encode()
<块引用>
=?utf-8?b?5Li76aGM?=
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<me@abc.com>
to: me@abc.com
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 = ['me@abc.com']
f=open('msg.txt') #above msg in msg.txt file
msg=f.read()
f.close()
s.sendmail('me@abc.com',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?
解决方案From http://docs.python.org/library/email.header.html
from email.message import Message
from email.header import Header
msg = Message()
msg['Subject'] = Header('主題', 'utf-8')
print msg.as_string()
Subject: =?utf-8?b?5Li76aGM?=
more simple:
from email.header import Header
print Header('主題', 'utf-8').encode()
=?utf-8?b?5Li76aGM?=
相关文章