python 发送邮件(附件名称为中文)

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

mailto_list = ["to_name@163.com"]
mail_host = "smtp.163.com"
mail_user = "user_name@163.com"
mail_pass = "password"
# mail_subject = "python发送邮件测试"  # 邮件的标题
# mail_context = "这是邮件内容-----XXOO"

def send_main(mail_subject, Filename):
    msg = MIMEMultipart()
    msg["From"] = mail_user   # 发件人
    msg["To"] = ";".join(mailto_list)  # 收件人
    msg["Subject"] = mail_subject   # 邮件标题
    # 邮件正文
    with open(Filename, "rb") as f:
        fc = f.read()
    txt = MIMEText(fc, 'html', 'utf-8')
    msg.attach(txt)
    # 构造附件
    att = MIMEText(open(Filename, "rb").read(), "base64", "utf-8")
    att["Content-Type"] = "application/octet-stream"
    # 附件名称为中文时的写法
    att.add_header("Content-Disposition", "attachment", filename=("gbk", "", "5.3版本接口详细测试结果.html"))
    # 附件名称非中文时的写法
    # att["Content-Disposition"] = 'attachment; filename="test.html")'
    print(1)
    msg.attach(att)

    smtp = smtplib.SMTP()
    smtp.connect(mail_host)
    smtp.login(mail_user, mail_pass)
    smtp.sendmail(mail_user, mailto_list, msg.as_string())
    smtp.quit()
    print("邮件发送成功")
原文地址:https://www.cnblogs.com/wang1122/p/8059193.html