美文网首页
发送邮件正文并添加附件xd

发送邮件正文并添加附件xd

作者: Chaweys | 来源:发表于2021-04-06 08:37 被阅读0次

sendmail.py

#coding=utf-8
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart  #多媒体测试报告
import smtplib
import configparser
import os

class SendMialTest:
    @classmethod  #声明为类方法后,可直接:类名.方法名() 调用
    def send_mail(cls):
        cf=configparser.ConfigParser()
        cf.read('./config/conf.ini')
        mail_server=cf.get("email","mail_server")
        sender=cf.get("email","sender")
        authcode=cf.get("email","authcode")
        receivers=cf.get("email","receivers")

        subject='XD邮件测试'


        #查找最新的测试报告
        repoert_list=os.listdir('./report')
        repoert_list.sort(key=lambda e: os.path.getatime(os.path.join('./report',e)))
        new_report=repoert_list[-1]
        with open(os.path.join('./report',new_report),'rb') as f:
            mail_content=f.read()

        #这是邮件正文
        html=MIMEText(mail_content,'html','utf-8')


        #这是邮件附件
        att=MIMEText(mail_content,'base64','utf-8')
        att["Content-type"]="application/octet-stream"
        att["Content-Disposition"]="attachment;filename='result.html'"  #filename定义附件的文件名称

        #将邮件正文和邮件附件都加入到多媒体报告
        msg=MIMEMultipart()
        msg['Subject'] = subject
        msg['From'] = sender
        msg['To'] = receivers
        msg.attach(att)   #将附件加载msg里
        msg.attach(html)  #将邮件正文加载msg里

        smtp=smtplib.SMTP_SSL(mail_server,465)
        smtp.helo(mail_server)
        smtp.ehlo(mail_server)
        smtp.login(sender,authcode)
        smtp.sendmail(sender,receivers,msg.as_string())

        smtp.quit()
        print('邮件发送成功')

if __name__ == '__main__':
    SendMialTest.send_mail()

相关文章

网友评论

      本文标题:发送邮件正文并添加附件xd

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