import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import os import datetime def find_newest_file(current_dir): # 获取当前目录中所有文件的信息 files = os.listdir(current_dir) # 初始化最近修改时间和对应的文件名 latest_time = None latest_file = None # 遍历所有文件 for file in files: # 获取文件的路径 file_path = os.path.join(current_dir, file) # 如果是文件而不是文件夹 if os.path.isfile(file_path): # 获取文件的最后修改时间 modification_time = os.path.getmtime(file_path) # 将修改时间转换为可读格式 modification_time = datetime.datetime.fromtimestamp(modification_time) # 判断是否是第一个文件或者当前文件的修改时间更晚 if (latest_time is None or modification_time > latest_time) and file_path.endswith('.html'): latest_time = modification_time latest_file = file return latest_file #发送邮件 def send_email(report_name): #定义SMTP的服务器 smtpserver='smtp.163.com' #发送邮件的用户名和客户端密码 username="liumm_6064@163.com" password="TPVBPYSETVHWTIDH" #接受邮件的邮箱 receiver=['lizhikun@topnet.net.cn'] #创建邮件对象 message=MIMEMultipart('related') #邮件主题 subject="剑鱼自动化测试报告" fujian=MIMEText(open(f'D:\PycharmProjects\jianyu_auto_api\log/{report_name}','rb').read(),'html','utf-8') #把邮件信息组装到邮件对象里面 message['from']=username message['to']= ",".join(receiver) message['subject']=subject message.attach(fujian) #登录smtp服务器并发送邮件 smtp=smtplib.SMTP() smtp.connect(smtpserver) smtp.login(username,password) smtp.sendmail(username,receiver,message.as_string()) smtp.quit() if __name__ == '__main__': dir = r'D:\PycharmProjects\jianyu_auto_api\log' filename = find_newest_file(dir) if filename: send_email(filename)