一、目录结构
#coding=utf-8from email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipartimport smtplib,osdef get_report_file(report_path):"""获取最新的测试报告:param report_path::return:"""lists = os.listdir(report_path)lists.sort(key=lambda fn: os.path.getmtime(os.path.join(report_path, fn)))print(u'最新测试生成的报告: '+lists[-1])# 找到最新生成的报告文件report_file = os.path.join(report_path, lists[-1])return report_filedef send_mail(sender, psw, receiver, cc_receiver, smtpserver, report_file, port):"""发送最新的测试报告内容"""with open(report_file, "rb") as f:mail_body = f.read()# 定义邮件内容msg = MIMEMultipart()body = MIMEText(mail_body, _subtype='html', _charset='utf-8')msg['Subject'] = u"接口自动化测试报告"msg["from"] = sendermsg["to"] = ",".join(receiver)msg["Cc"] = ",".join(cc_receiver)msg.attach(body)# 添加附件att = MIMEText(open(report_file, "rb").read(), "base64", "utf-8")att["Content-Type"] = "application/octet-stream"att["Content-Disposition"] = 'attachment; filename= "report.html"'msg.attach(att)smtp = smtplib.SMTP()smtp.connect(smtpserver, port)# 用户名密码smtp.login(sender, psw)smtp.sendmail(sender, receiver+cc_receiver, msg.as_string())smtp.quit()print('Test report email has send to {} !'.format(receiver))def main():# 获取最新的测试报告文件report_path = os.path.join(cur_path, "report") # 测试报告文件夹report_file = get_report_file(report_path) # 获取最新的测试报告print('report_file: ', report_file)# 邮箱配置sender = readconfig.senderpsw = readconfig.pswsmtp_server = readconfig.smtp_serverport = readconfig.portreceivers = readconfig.receiver.split(',')cc_receiver = _receiver.split(',')# 发送报告send_mail(sender, psw, receivers, cc_receiver, smtp_server, report_file, port) if __name__ == "__main__":main()