python smtp 发送邮件 带附件

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


def send_email():

    # 依次为:邮件服务器地址、端口、发件人、授权码、接收人
    server = "smtp.163.com"
    port = 465
    sender = "****@163.com"
    psw = "********"
    receiver = "****@qq.com"

    # 添加写信模板
    msg = MIMEMultipart()
    # 发件人
    msg["From"] = sender
    # 收件人
    msg["To"] = receiver
    # 邮件主题
    msg["Subject"] = u"自动化测试报告。"

    # 打开附件
    f = open(r'E:\report\report.html', encoding='utf-8')
    mail_body = f.read()
    f.close()

    # 添加附件
    att = MIMEText(mail_body, "base64", "utf-8")
    att["Content-Type"] = "application/octet-stream"
    att["Content-Disposition"] = "attachment; filename='report.html'"
    msg.attach(att)

    # 添加邮件正文
    body = MIMEText(mail_body, 'html', 'utf-8')
    msg.attach(body)

    # 写信流程 授权码登录
    smtp = smtplib.SMTP_SSL(server, port)
    smtp.login(sender, psw)
    smtp.sendmail(sender, receiver, msg.as_string())
    smtp.quit()


if __name__ == '__main__':
    send_email()

猜你喜欢

转载自blog.csdn.net/showgea/article/details/90755097