python(8):python发送邮件
邮件发送测试报告
前置条件:开通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 = '2798413941@qq.com' smtp_senderpassword = 'gmyiulsymlzvdcdd' smtp_receiver = 'zz1196999489@163.com' smtp_cc = '1196999489@qq.com' 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,查收邮件
查看执行结果: