Python 发送带有中文附件的邮件

之前在网上找了半天没找到解决方案,后来通过看源码偶然找到了一种解决方法,如有相同问题的,不妨试试!

# coding=gbk
import os
import sys
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

path = r'D:\test'
file_name = '测试.xlsx'

msg = MIMEMultipart('related')
msg['From'] = '*******@cardvalue.cn'
msg['To'] = '*******@qq.com'
msg['Subject'] = os.path.basename(file_name)

# 邮件正文
text = MIMEText('测试!', 'plain', 'gbk')
msg.attach(text)

# 邮件附件
att = MIMEText(open(os.path.join(path, file_name), 'rb').read(), 'base64', 'gbk')
att["Content-Type"] = 'application/octet-stream'
att.add_header('Content-Disposition', 'attachment', filename=('gbk', '', file_name))
msg.attach(att)
smtp = smtplib.SMTP()
smtp.connect('smtp.ym.163.com', '25')
smtp.login('*******@cardvalue.cn', '******')
smtp.sendmail(msg['From'], msg['To'], msg.as_string())
smtp.quit()

你可能感兴趣的:(Python)