美文网首页
UI自动化(十)邮件发送

UI自动化(十)邮件发送

作者: 社会主义顶梁鹿 | 来源:发表于2021-01-18 18:19 被阅读0次

介绍一下使用smtplib实现的邮件发送。

SMTP也就是简单邮件传输协议,用于在邮件服务器之间发送电子邮件和路由电子邮件。

以下为本人当前简单实现的代码,可借鉴学习。

import smtplib

from email.mime.textimport MIMEText

from email.mime.multipartimport MIMEMultipart

from email.mime.applicationimport MIMEApplication# 发送附件

def send_email(subject="自动化脚本异常反馈", body="试运行阶段~~~"):

    # ------构建邮件-------

    # 主题

    msg = MIMEMultipart()

    msg["from"] = SENDER

    msg["to"] =','.join(RECEIVER)

    msg["subject"] = subject

    # 正文

    the_body = MIMEText(body, "plain", "utf-8")

    msg.attach(the_body)

    # 压缩文件

    zip_for_file(ERROR_IMG_PATH, ZIP_IMG_PATH)

    attach_name = ["error_log", "error_img"]

    attach_file = [LOG_PATH, ZIP_IMG_PATH]

    for iin range(2):

    # 加入日志附件/图片附件

        part_attach1 = MIMEApplication(open(attach_file[i], 'rb').read())# 打开附件

        part_attach1.add_header('Content-Disposition', 'attachment', filename=attach_name[i])# 为附件命名

        msg.attach(part_attach1)

    # ------发送邮件-------

    try:

        smtp = smtplib.SMTP()

        smtp.connect(SMTP_SEVER)# 连接服务器

        smtp.login(SENDER, AUTH_CODE)

    except:

        smtp = smtplib.SMTP_SSL(SMTP_SEVER, PORT, timeout=20)

        smtp.login(SENDER, AUTH_CODE)# 登录

        smtp.sendmail(SENDER, msg["to"].split(','), msg.as_string())# 发送

        smtp.quit()

    print("邮件发送完毕")

掌握以上就够用了,后续空闲之后尝试并补充其他的方法。

相关文章

网友评论

      本文标题:UI自动化(十)邮件发送

      本文链接:https://www.haomeiwen.com/subject/mxixzktx.html