Python SMTP发送邮件

SMTP(Simple Mail Transfer Protocol)即简单邮件传输协议,它是一组用于由源地址到目的地址传送邮件的规则,由它来控制信件的中转方式。
SMTP使用 sendmail 方法发送邮件,其语法为smtp.sendmail(sender,receiver,msg)

sender为发送人;
receiver为接收人;
msg是字符串,为发送的消息,即邮件(包括标题,发信人,收件人,邮件内容,附件等)

我们可以使用其他邮件服务商的 SMTP 访问,要先设置邮箱服务器,将邮件发送到该邮箱服务器,再由其进行代发,发送给接收人
以下为实例,将自动化测试生成的测试报告自动发送邮件

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
import os


# 定义发送邮件(带附件)
def send_mail(file_new):
    f = open(file_new,'rb')
    # 读取测试报告
    mail_body=f.read()
    f.close()
    # 发送邮箱服务器(QQ邮箱)
    smtpserver = "smtp.qq.com"
    # 发送人邮箱
    sender = "XXX@qq.com"
    # 发件人邮箱授权码(在QQ邮箱设置-账户里开启POP3/SMTP服务,获得16位授权码)
    password = "XXX"		
    # 接收人邮箱
    receiver = "XXX@163.com"

    msg = MIMEMultipart()
    # 邮件正文-测试报告
    text = MIMEText(mail_body,"html","utf-8")
    msg.attach(text)
    # 邮件标题
    msg["Subject"] = Header("自动化测试报告","utf-8")
    # 附件内容-测试报告
    msg_file = MIMEText(mail_body,"html","utf-8")
    msg_file["Content-Type"] = "application/octet-stream"
    # filename为邮件附件名称,可更改
    msg_file["Content-Disposition"] = 'attachment; filename="AutoTestReport.html"'
    msg.attach(msg_file)

    try:
        smtp = smtplib.SMTP()
        smtp.connect(smtpserver)
        smtp.login(sender,password)
        smtp.sendmail(sender,receiver,msg.as_string())
        smtp.quit()
        print "发送成功"
    except:
        print "发送失败"

# 查找出最新的测试报告
def new_report(testreport):
    dirs = os.listdir(testreport)
    dirs.sort()
    newreportname = dirs[-1]
    print "找到最新自动化测试报告,即将发送邮件"
    file_new = os.path.join(testreport,newreportname)
    return file_new


if __name__ == '__main__':
    test_report = "XXX"			# 为自动化测试报告存放的地址
    new_report = new_report(test_report)
    send_mail(new_report)

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值