永发信息网

python 发送邮件,附件中文命名,怎么破

答案:1  悬赏:40  手机版
解决时间 2021-02-16 02:22
  • 提问者网友:欺烟
  • 2021-02-15 07:51
python 发送邮件,附件中文命名,怎么破
最佳答案
  • 五星知识达人网友:佘樂
  • 2021-02-15 09:22
不知道你是不是用的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
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯