Python-自动发送各种类型附件的邮件

发送邮件的基本思路就是使用MIMEMultipart来组装(attach)各个部分:邮件主题,邮件发送者,邮件接收者,邮件正文以及附件等等,其中附件需要add_header加入附件声明

继承关系如下:

MIMEBase

--MIMENonMultipart

--MIMEApplication

--MIMEAudio

--MIMEImage

--MIMEMessage

--MIMEText

--MIMEMultipart

一般来说,不会直接使用到MIMEBase类,而是直接使用它的继承类。MIMEMultipart有attach方法,而MIMENonMultipart没有,只能被attach,MIME有很多种类型,而最终只提供(音频: MIMEAudio;图片: MIMEImage; 文本:MIMEText),如果是其它类型,如word,excel,html就不知道该用哪种类型

作者的附件类型是HTML,使用MIMIText一直不尽如人意,如下图:

针对以上问题解决方案:

不管什么类型的附件,都用MIMEApplication,它的默认子类型是application/octet-stream(二进制文件),客户端比如qq邮箱,收到这个声明后,会根据扩展名来猜测

贴作者代码:

#coding: utf-8
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
from email.mime.application import MIMEApplication
import time
from project_prctice.common import dir_config as Dir
import os
from project_prctice.common.logger import FrameLog as log

class SendMail:
    def __init__(self):
        self.file = self.find_newest_file()

    def find_newest_file(self):
        '''
        查找目录下最新的文件
        :return:
        '''
        file_list = os.listdir(Dir.reports_dir)
        file_list.sort()
        filepath = os.path.join(Dir.reports_dir, file_list[-2])    #因该文件夹下有__init__文件,因此为固定输出结果
        return filepath

    def send_mail_html(self):
        '''
        发送html内容邮件
        :param file:
        :return:
        '''
        msg = MIMEMultipart()
        #邮箱服务器
        smtpserver = "smtp.qq.com"
        #发送邮箱地址
        msg_from = "****@qq.com"
        # 发送方邮箱授权码
        password = "rdtghsmihar"
        #接收邮箱
        msg_to= "****@qq.com"
        #发送邮件主题
        t = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        subject = "自动化测试报告_" + t      #主题
        content = "系统自动发出邮件,请勿回复"      #邮件正文内容
        msg.attach(MIMEText(content, 'plain', 'utf-8'))    #实例化一个MIMEText邮件对象,该对象需要写进三个参数,分别是邮件正文,文本格式和编码
        msg['Subject'] = Header(subject,'utf-8')
        msg['From'] = msg_from
        msg['To'] = msg_to

        #---这是附件部分-----
        #xlsx类型附件
        # attachment = MIMEApplication(open('file.xlsx', 'rb').read())
        # attachment.add_header('Content-Disposition', 'attachment', filename='file.xlsx')
        # msg.attach(attachment)

        #jpg类型附件
        # attachment = MIMEApplication(open('file.jpg', 'rb').read())
        # attachment.add_header('Content-Disposition', 'attachment', filename='file.jpg')
        # msg.attach(attachment)

        #mp4类型附件
        # attachment = MIMEApplication(open('file.mp4', 'rb').read())
        # attachment.add_header('Content-Disposition', 'attachment', filename='file.mp4')
        # msg.attach(attachment)

        #HTML附件
        attachment = MIMEApplication(open(self.file, 'rb').read())
        attachment.add_header('Content-Disposition','attachment',filename ='自动化测试报告.html')
        msg.attach(attachment)

        #登录并发送邮件
        try:
            smtp = smtplib.SMTP_SSL(smtpserver,smtplib.SMTP_SSL_PORT)
            log().getLogger().info(f"{smtp}连接成功")
            smtp.login(msg_from, password)
            log().getLogger().info(f"{smtp}登陆成功")
            smtp.sendmail(msg_from, msg_to, msg.as_string())
            log().getLogger().info(f"{smtp}发送邮件成功")
            smtp.quit()
        except smtplib.SMTPException as e:
            log().getLogger().error("发送邮件失败")


if __name__ == '__main__':
    SendMail().send_mail_html()

效果如下图:

posted @ 2021-12-08 16:01  美女爱找茬  阅读(401)  评论(0编辑  收藏  举报