使用非ASCII字符在Python中编码邮件主题(SMTP) [英] Encoding mail subject (SMTP) in Python with non-ASCII characters

查看:401
本文介绍了使用非ASCII字符在Python中编码邮件主题(SMTP)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Python模块 MimeWriter 构造一个消息,smtplib发送邮件构造的消息是:

 文件msg.txt:
-----------------------
Content-Type: multipart / mixed;
从:me< me@abc.com>
to:me@abc.com
主题:主题

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)

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

 主题:一些垃圾字符

主题< - 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()




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


更简单:

 来自email.header import Header 
print标题('主题','utf-8')。encode()
/ pre>


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

这篇关于使用非ASCII字符在Python中编码邮件主题(SMTP)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆