• 【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
  • 相关阅读:
    在仅有的一次生命里活出自己最大的可能
    每个人都渴望赞美
    历练领导力的八字要诀
    爱情语录
    Ps
    别跟我要钱,我是教授
    改变人生的五个问题
    纪晓岚妙用口才
    智慧和智商
    经典
  • 原文地址:https://www.cnblogs.com/Owen-ET/p/9627192.html
Copyright © 2020-2023  润新知