python - 在 Python 中使用非 ASCII 字符编码邮件主题 (SMTP)

标签 python utf-8 character-encoding smtp cjk

我使用 Python 模块 MimeWriter 构造消息和 smtplib 发送邮件构造消息是:

file msg.txt:
-----------------------
Content-Type: multipart/mixed;
from: me<me@abc.com>
to: me@abc.com
subject: 主題

Content-Type: text/plain;charset=utf-8

主題

我使用下面的代码发送邮件:

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)

我的邮件正文正确,但主题不正确,

subject: some junk characters

主題           <- body is correct.

请建议?有没有办法指定用于主题的解码, 为 body 指定。如何正确解码主题?

最佳答案

来自 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?=

更简单:

from email.header import Header
print Header('主題', 'utf-8').encode()

=?utf-8?b?5Li76aGM?=

关于python - 在 Python 中使用非 ASCII 字符编码邮件主题 (SMTP),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6913170/

相关文章:

python - 如何在不使用 num2word 库的情况下将数字转换为单词?

python - 当我的用户使用 gae-simpleauth 登录时,如何从 Google 帐户检索电子邮件地址并将其存储在我的应用程序的用户个人资料中?

python - 如何使用beautifulsoup从网页中正确提取特殊字符?

unit-testing - 是否有一组 "Lorem ipsums"文件用于测试字符编码问题?

python - 如何对整数的大小施加(重要的)限制? (Python)

python - 从 python 读取 excel 工作表单元格的背景颜色?

html - 阿拉伯文字显示不正确

utf-8 - MySql导入备份-UTF8问题

Python 3.x 请求使用 unicode 字符进行重定向

java - 在 Java 中将 UTF-8 转换为 ISO-8859-1