【Python学习】之yagmail库实现发送邮件

 

上代码:

import yagmail

sendmail = 'xxx@126.com'
sendpswd = 'xxx'
receivemail = 'xxx@qq.com'

# 连接邮箱服务器
yag = yagmail.SMTP(user=sendmail, password=sendpswd, host='smtp.126.com')
# ①普通邮件正文
contents = ['第一段', '自动化', '报告邮件']

# ②发送html邮件正文
# 读取邮件模板
file_object = open('mailcontent.html')
try:
    contentsbody = file_object.read()
finally:
    file_object.close()
contents = contentsbody

# 附件地址
fujian = ["/Users/zhan/zhan/Autotest/report/2018-09-11_09_52_24_report.html"]
# 发送邮件附件
yag.send(receivemail, '《自动化报告》', contents,fujian)

参考:《利用yagmail实现邮件自动发送

 

老的发送邮箱写法:

from smtplib import SMTP
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.header import Header
from email.mime.text import MIMEText


def getNewReport(report_url):
    '''
    获取最新生成的测试报告
    :param report_url:
    :return:
    '''
    lists = os.listdir(report_url)
    lists.sort(key= lambda fn: os.path.getmtime(report_url + fn))
    newReport = os.path.join(report_url,lists[-1])
    return newReport


def sendMail(newReport,report_name):
    '''
    ①普通发送邮件
    :param newReport:
    :param report_name:
    :return:
    '''
    sendMail = 'xxx@126.com'
    sendpswd = 'xxx'
    receiveMail = 'xxx@qq.com'


    # 创建邮件信息
    msg = MIMEMultipart()
    # 读取最新报告文件
    f = open(newReport,'rb').read()
    # 设置邮件主体
    mailBody =  MIMEText(f,'html','utf-8')
    # 邮件主体放入到消息中
    msg.attach(mailBody)
    # 邮件标题
    msg['Subject'] = Header("《自动化测试报告邮件》",'utf-8')
    msg['From'] = sendMail
    msg['To'] = receiveMail

    # 邮件附件
    att = MIMEApplication(f)
    att['Content-Type'] = 'application/octet-stream'
    att.add_header('Content-Disposition','attachment',filename=report_name)
    msg.attach(att)


    smtp = SMTP()
    # 连接邮箱
    smtp.connect('smtp.126.com')
    # 邮箱登录
    smtp.login(sendMail,sendpswd)
    # 发送邮件
    smtp.sendmail(sendMail,receiveMail,msg.as_string())
View Code

 

posted @ 2018-09-11 13:55  Owen_ET  阅读(512)  评论(0编辑  收藏  举报