首页 > 编程语言 >python(8):python发送邮件

python(8):python发送邮件

时间:2022-12-04 15:35:51浏览次数:48  
标签:zip python self smtp 发送 file msg path 邮件

邮件发送测试报告

前置条件:开通QQ邮箱第三方登录,并拿到密码;

 

步骤1:编写测试代码,先发送一个文本的邮件

在sample文件中编写线性代码:

 

 

步骤2:编写一个带附件的邮件

 

 

 

 代码示例:

import os
import smtplib
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email import encoders


# 先准备附件
current_path = os.path.dirname(__file__)
smtp_file_path = os.path.join(current_path,'..','reports/禅道UI自动化测试V1.0.zip')

# 登录账号密码,发件人和收件人,邮件标题,邮件内容,邮件服务器域名
# 开通QQ邮箱第三方登录,并拿到密码
smtp_server = 'smtp.qq.com'
smtp_sender = '[email protected]'
smtp_senderpassword = 'gmyiulsymlzvdcdd'
smtp_receiver = '[email protected]'
smtp_cc = '[email protected]'
smtp_subject = '禅道自动化测试报告'
smtp_body = '来自禅道自动化测试的结果'
smtp_file = smtp_file_path

# 发压缩包的邮件
msg = MIMEMultipart()
with open(smtp_file,'rb') as f:
    mime = MIMEBase('zip','zip',filname=smtp_file.split('/')[-1])
    mime.add_header('Content-Disposition', 'attachment',
                    filename=('gb2312', '',smtp_file.split('/')[-1]))
    mime.add_header('Content-ID', '<0>')
    mime.add_header('X-Attachment-Id', '0')
    mime.set_payload(f.read())
    encoders.encode_base64(mime)
    msg.attach(mime)

msg.attach(MIMEText(smtp_body,'html','utf-8'))
msg['from'] = smtp_sender
msg['to'] = smtp_receiver
msg['Cc'] = smtp_cc
msg['subject'] = smtp_subject

# # 邮件文本消息
# msg = MIMEText(smtp_body,'html','utf-8')  # 邮件消息对象
# msg['from'] = smtp_sender
# msg['to'] = smtp_receiver
# msg['Cc'] = smtp_cc
# msg['subject'] = smtp_subject

# 发送邮件
smtp = smtplib.SMTP()
smtp.connect(smtp_server)
smtp.login(user=smtp_sender,password=smtp_senderpassword)
smtp.sendmail(smtp_sender,smtp_receiver.split(',') + smtp_cc.split(','),msg.as_string())

 

查看邮件:

步骤3:封装压缩文件夹的代码

在common文件下新建zip_utils.py文件,编写压缩文件的代码

 

 代码示例:

import os
import zipfile


def zip_dir(dir_path,zip_path):
    """

    :param dir_path: 源文件夹路径
    :param zip_path: 压缩后的文件夹路径
    :return:
    """
    zip = zipfile.ZipFile(zip_path,'w',zipfile.ZIP_DEFLATED)
    for root,dirnames,filenames in os.walk(dir_path):
        file_path = root.replace(dir_path, '')  # 去掉根路径,只对目标文件夹下的文件及文件夹进行压缩
        # 循环出一个个文件名
        for filename in filenames:
            zip.write(os.path.join(root,filename), os.path.join(file_path,filename))
    zip.close()


current_path = os.path.abspath(os.path.dirname(__file__))
dir_path = os.path.join(current_path,'../reports/禅道UI自动化测试V1.0')
smtp_file_path = os.path.join(current_path,'../reports/禅道UI自动化测试报告.zip')
zip_dir(dir_path,smtp_file_path)
print('已压缩')

 

步骤4:把邮件的用户名,密码等信息分离到配置文件中

先把邮件的信息放到config.ini文件中;

 

 

在config_utils文件中调用ini文件中的信息;

 

 

代码示例:

# 邮件配置信息
    @property
    def get_smtp_server(self):
        """获取ini文件中邮件的服务器"""
        value = self.cfg.get('email','smtp_server')
        return value

    @property
    def get_smtp_sender(self):
        """获取ini文件中邮件的发送人"""
        value = self.cfg.get('email','smtp_sender')
        return value

    @property
    def get_smtp_senderpassword(self):
        """获取ini文件中邮箱登录密码"""
        value = self.cfg.get('email','smtp_senderpassword')
        return value

    @property
    def get_smtp_receiver(self):
        """获取ini文件中邮件的接收人"""
        value = self.cfg.get('email','smtp_receiver')
        return value

    @property
    def get_smtp_cc(self):
        """获取ini文件中邮件的抄送人"""
        value = self.cfg.get('email','smtp_cc')
        return value

    @property
    def get_smtp_subject(self):
        """获取ini文件中邮件的标题"""
        value = self.cfg.get('email','smtp_subject')
        return value

 

查看执行结果:

 

 

步骤5:封装发送邮件的代码

在common文件下新建email_utils.py;

 

 

 

 

 

 

代码示例:

# encoding: utf-8
# @author: Jeffrey
# @file: email_utils.py
# @time: 2022/7/22 23:24
# @desc: 邮件封装
import os
import smtplib
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from common.config_utils import local_config
from common import zip_utils


class EmailUtils:
    def __init__(self, smtp_body, smtp_file_path=None):
        self.smtp_server = local_config.get_smtp_server
        self.smtp_sender = local_config.get_smtp_sender
        self.smtp_senderpassword = local_config.get_smtp_senderpassword
        self.smtp_receiver = local_config.get_smtp_receiver
        self.smtp_cc = local_config.get_smtp_cc
        self.smtp_subject = local_config.get_smtp_subject
        self.smtp_body = smtp_body
        self.smtp_file = smtp_file_path

    def mail_content(self):
        """
        邮件内容
        :return:
        """
        if self.smtp_file != None:
            if self.smtp_file.split('.')[-1].__eq__('zip'):
                return self.__mail_zip_content()
            # elif 扩展
        else:
            return self.__mail_text_content()

    def mail_content_by_zip(self):
        """对文件进行压缩"""
        report_zip_path = self.smtp_file + '/../禅道UI自动化测试报告.zip'
        zip_utils.zip_dir(self.smtp_file, report_zip_path)
        self.smtp_file = report_zip_path  # 压缩后修改为压缩路径
        msg = self.mail_content()
        return msg

    def __mail_text_content(self):
        """邮件文本信息"""
        msg = MIMEText(self.smtp_body, "html", "utf-8")
        msg['from'] = self.smtp_sender
        msg['to'] = self.smtp_receiver
        msg['Cc'] = self.smtp_cc
        msg['subject'] = self.smtp_subject
        return msg

    def __mail_zip_content(self):

        msg = MIMEMultipart()
        with open(self.smtp_file, 'rb') as f:
            mime = MIMEBase('zip', 'zip', filename=self.smtp_file.split('/')[-1])
            mime.add_header('Content-Disposition', 'attachment',
                            filename=('gb2312', '', self.smtp_file.split('/')[-1]))
            mime.add_header('Content-ID', '<0>')
            mime.add_header('X-Attachment-Id', '0')
            mime.set_payload(f.read())
            encoders.encode_base64(mime)
            msg.attach(mime)
        msg.attach(MIMEText(self.smtp_body, "html", "utf-8"))
        msg['from'] = self.smtp_sender
        msg['to'] = self.smtp_receiver
        msg['Cc'] = self.smtp_cc
        msg['subject'] = self.smtp_subject
        return msg


    def send_mail(self):
        """发送普通邮件,不带附件压缩包"""
        try:
            smtp = smtplib.SMTP()
            smtp.connect(self.smtp_server)
            smtp.login(user=self.smtp_sender, password=self.smtp_senderpassword)
        except:
            smtp = smtplib.SMTP_SSL()
            smtp.login(user=self.smtp_sender, password=self.smtp_senderpassword)
        mail_content = self.mail_content()
        try:
            smtp.sendmail(self.smtp_sender, self.smtp_receiver.split(',') + self.smtp_cc.split(','),
                          mail_content.as_string())
        except Exception as e:
            print('发送失败')
        smtp.quit()

    def zip_send_mail(self):
        """发送带压缩包的邮件"""
        try:
            smtp = smtplib.SMTP()
            smtp.connect(self.smtp_server)
            smtp.login(user=self.smtp_sender, password=self.smtp_senderpassword)
        except:
            smtp = smtplib.SMTP_SSL()
            smtp.login(user=self.smtp_sender, password=self.smtp_senderpassword)
        mail_content = self.mail_content_by_zip()
        try:
            smtp.sendmail(self.smtp_sender, self.smtp_receiver.split(',') + self.smtp_cc.split(','),
                          mail_content.as_string())
        except Exception as e:
            print('发送失败')
        smtp.quit()

步骤6:把压缩文件代码和发送邮件代码整合到run_all_cases.py框架中

导包:

from common.zip_utils import zip_dir

from common.email_utils import EmailUtils

 

 

代码示例:

import os
import unittest

from common import HTMLTestReportCN
from common.config_utils import local_config
from common.zip_utils import zip_dir
from common.email_utils import EmailUtils


current_path = os.path.dirname(__file__)
case_path = os.path.join(current_path,'..',local_config.get_case_path)
report_path = os.path.join(current_path,'..',local_config.get_report_path)


class RunAllCase:

    def __init__(self):
        self.test_case_path = case_path
        self.report_path = report_path
        self.title = '禅道UI自动化测试'
        self.description = 'newdream_tester'

    def run(self):
        discover = unittest.defaultTestLoader.discover(start_dir=self.test_case_path,
                                            pattern='*_case.py',
                                            top_level_dir=self.test_case_path)
        all_suite = unittest.TestSuite()
        all_suite.addTest(discover)

        report_dir = HTMLTestReportCN.ReportDirectory(self.report_path)
        report_dir.create_dir(self.title)
        dir_path = HTMLTestReportCN.GlobalMsg.get_value('dir_path')
        report_path = HTMLTestReportCN.GlobalMsg.get_value('report_path')
        fp = open(report_path,'wb')
        runner = HTMLTestReportCN.HTMLTestRunner(stream=fp,
                                                 title=self.title,
                                                 description=self.description,
                                                 tester='newdream_jeffrey')
        runner.run(all_suite)
        fp.close()
        return dir_path

if __name__ == '__main__':
    dir_path = RunAllCase().run()
    report_zip_path = dir_path+'/../禅道UI自动化测试报告.zip'
    zip_dir(dir_path,report_zip_path)
EmailUtils('Python+selenium+unittest框架自动化测试报告',report_zip_path).send_mail()

执行run_all_cases.py查看执行结果:

 

 

步骤7:把压缩文件打包功能封装到发送邮件中(详细代码见步骤5)

 

 

 

 

步骤8:执行,检查是否可以收到邮件,附件为测试结果打包的文件夹

执行run_all_cases.py,查收邮件

 

 

查看执行结果:

 

标签:zip,python,self,smtp,发送,file,msg,path,邮件
From: https://www.cnblogs.com/YouJeffrey/p/16949932.html

相关文章

  • python分布式框架celery(二)
    一、什么是Celery1.1、celery是什么Celery是一个简单、灵活且可靠的,处理大量消息的分布式系统,专注于实时处理的异步任务队列,同时也支持任务调度。Celery的架构由三......
  • python(7):python连接mysql数据库并获取数据
    python连接mysql数据库下载pymysql:pipinstallpymysql编写代码:importpymysqlclassMysqlUtils:def__init__(self):self.conn_obj=pymysql.conne......
  • 关于python深拷贝,deepcopy和 copy的知识随手记
    Python中copy模块下的deepcopy函数使用,采用的深层拷贝,并开辟新的空间   如果用copy函数,  如果拷贝的是不可变类型: ......
  • 网页返回unicode源码 python解码详细步骤
    刚入门python!记录一下网页返回源码,中文部分被unicode编码,python如何处理1.先提取编码后的数据(如果不提取正篇源码直接unicode解码,解码方法无法识别)这个步骤属于逻辑......
  • python3的re正则的简单使用
    importre#match----------------------------------------------------print(re.match(r'www','www.runoob.com').span())#(0,3)print(re.match('com','www.ru......
  • 零基础学习python的第一天整理——python的安装以及pycharm安装
    ​一.python的安装首先我们来谈一谈python的安装,python的官网地址:WelcometoPython.org​编辑 进入官网后点击Downloads,然后选择自己对应的系统,比如:你的电脑是Windows......
  • python3遇到的error
    SyntaxError:(unicodeerror)‘unicodeescape’codeccan’tdecodebytesinposition原始代码forxinos.listdir('C:\Users\Administrator\Desktop\files'):......
  • Python学习(七):JupyterNoteBook的使用
    1.JupyterNoteBook的安装:pipinstalljupyternotebook  2.打开jupyternotebook:2.1默认打开jupyternotebook,操作记录会保存在C盘或默认目录;  2.2......
  • PYTHON 函数
    1.1函数函数是可以反复执行的代码块,具有函数名,参数,返回值。1.2定义函数函数必须先定义后执行。def函数名(参数列表):函数体return返回值没的返回数据......
  • Python标准库-Configparser-配置文件解析器
    简介官方文档开发中INI格式的配置文件使用还是有必要的。如果某些配置项需要在运行时由用户来修改指定,比如数据库用户信息等等,这种配置项如果使用INI格式的配置文件来操......