python3第三方使用smtp发送邮件附带xlsx文件【已解决中文名报错】

来源:互联网 发布:上海网络整合营销公司 编辑:程序博客网 时间:2024/05/21 20:03

正在做的一个项目的后端开发遇到的问题,查了好久的资料,应该是邮箱编码的问题,换成gbk就可以了

参考代码如下:

# -*- coding:utf-8 -*- ''' @Author:      GETF @Email:       GETF_own@163.com @DateTime:    2017-10-25 00:25:02 @Description: Description '''import smtplibfrom email.mime.image import MIMEImagefrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextfrom email.header import Headerfrom email.utils import formataddrfrom email.mime.application import MIMEApplicationimport osimport xlsxwriterdef Email(request):     #table_name是我生成文件时(忽略)的命名,这里解释下    name=table_name+'.xlsx'    #第二步发送文件    sender='12345@qq.com'    # 发件人邮箱账号    my_pass = 'XXXXX'              # 发件人授权码    receiver='12345@qq.com'      # 收件人邮箱账号,我这边发送给自己    def mail():        ret=True        try:            msg = MIMEMultipart()            msg['From']=formataddr(["便捷账本",sender])  # 括号里的对应发件人邮箱昵称、发件人邮箱账号            msg['To']=formataddr(["账本用户",receiver])              # 括号里的对应收件人邮箱昵称、收件人邮箱账号            msg['Subject']="导出数据[便捷记账本]" # 邮件的主题,也可以说是标题            filepath='DIR'+name#绝对路径            xlsxpart = MIMEApplication(open(filepath, 'rb').read())             basename = "账本.xlsx"            xlsxpart.add_header('Content-Disposition', 'attachment', filename=('gbk', '', basename))#注意:此处basename要转换为gbk编码,否则中文会有乱码。             msg.attach(xlsxpart)                             server=smtplib.SMTP_SSL("smtp.qq.com", 465)  # 发件人邮箱中的SMTP服务器,端口是25            server.login(sender, my_pass)  # 括号中对应的是发件人邮箱账号、邮箱授权码            server.sendmail(sender,receiver,msg.as_string())  # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件            server.quit()  # 关闭连接            os.remove(filepath)#删除文件        except Exception:  # 如果 try 中的语句没有执行,则会执行下面的 ret=False            ret=False        return ret         ret=mail()        return JsonResponse({'flag':ret})