python 发送邮件,附件中文命名,怎么破
发布网友
发布时间:2022-05-01 02:18
我来回答
共2个回答
热心网友
时间:2022-05-11 04:38
不知道你是不是用的smtp来发的,我的发中文的附件没问题
#coding=utf-8
'''
Created on 2014-11-03
@author: Neo
'''
import smtplib
from email.mime.text import MIMEText
import email.mime.multipart
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email import Encoders
#你自己修改下xxx的部分
mailto_list = ['xxx@xxx.com']
mail_host = "smtp.xxx.com" # 设置服务器
mail_user = "xxxx" # 用户名
mail_pass = "xxxxx" # 口令
mail_postfix = "xxxx.com" # 发件箱的后缀
def send_mail():
me = "Hello" + "<" + mail_user + "@" + mail_postfix + ">" # 这里的hello可以任意设置,收到信后,将按照设置显示
content = 'Plz get the attachment!'
msg = MIMEMultipart()
body = MIMEText(content, _subtype='html', _charset='gb2312') # 创建一个实例,这里设置为html格式邮件
msg.attach(body)
msg['Subject'] = "Test" # 设置主题
msg['From'] = me
msg['To'] = ";".join(mailto_list)
part = MIMEBase('application', 'octet-stream')
# 读入文件内容并格式化,此处文件为当前目录下,也可指定目录 例如:open(r'/tmp/123.txt','rb')
part.set_payload(open(u'test中文.txt','rb').read())
Encoders.encode_base64(part)
## 设置附件头
part.add_header('Content-Disposition', u'attachment; filename="test中文.txt"')
msg.attach(part)
try:
s = smtplib.SMTP()
s.connect(mail_host) # 连接smtp服务器
s.login(mail_user, mail_pass) # 登陆服务器
s.sendmail(me, mailto_list, msg.as_string()) # 发送邮件
s.close()
print 'send mail sucess'
return True
except Exception, e:
print str(e)
return False
send_mail()
测试,发送ok
热心网友
时间:2022-05-11 05:56
from email.header import make_header
file_msg = MIMEText(open(file,'rb').read(), 'base64', 'UTF-8')
file_msg["Content-Type"] = 'application/octet-stream;name="%s"'% make_header([(file,'UTF-8')]).encode('UTF-8')
file_msg["Content-Disposition"] = 'attachment;filename= "%s"' % make_header([(file, 'UTF-8')]).encode('UTF-8')
msg.attach(file_msg)