sendemail.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import smtplib
  2. from email.mime.multipart import MIMEMultipart
  3. from email.mime.text import MIMEText
  4. import os
  5. import datetime
  6. def find_newest_file(current_dir):
  7. # 获取当前目录中所有文件的信息
  8. files = os.listdir(current_dir)
  9. # 初始化最近修改时间和对应的文件名
  10. latest_time = None
  11. latest_file = None
  12. # 遍历所有文件
  13. for file in files:
  14. # 获取文件的路径
  15. file_path = os.path.join(current_dir, file)
  16. # 如果是文件而不是文件夹
  17. if os.path.isfile(file_path):
  18. # 获取文件的最后修改时间
  19. modification_time = os.path.getmtime(file_path)
  20. # 将修改时间转换为可读格式
  21. modification_time = datetime.datetime.fromtimestamp(modification_time)
  22. # 判断是否是第一个文件或者当前文件的修改时间更晚
  23. if (latest_time is None or modification_time > latest_time) and file_path.endswith('.html'):
  24. latest_time = modification_time
  25. latest_file = file
  26. return latest_file
  27. #发送邮件
  28. def send_email(report_name):
  29. #定义SMTP的服务器
  30. smtpserver='smtp.163.com'
  31. #发送邮件的用户名和客户端密码
  32. username="liumm_6064@163.com"
  33. password="TPVBPYSETVHWTIDH"
  34. #接受邮件的邮箱
  35. receiver=['yanpeizhu@topnet.net.cn','renzheng@topnet.net.cn','lianbingjie@topnet.net.cn','lizhikun@topnet.net.cn','jialuyao@topnet.net.cn','liumiaomiao@topnet.net.cn','luwenna@topnet.net.cn','zangyamei@topnet.net.cn','yuanyuan@topnet.net.cn']
  36. #创建邮件对象
  37. message=MIMEMultipart('related')
  38. #邮件主题
  39. subject="剑鱼自动化测试报告"
  40. fujian=MIMEText(open(f'/mnt/jianyu_auto_api/log/{report_name}','rb').read(),'html','utf-8')
  41. #把邮件信息组装到邮件对象里面
  42. message['from']=username
  43. message['to']= ",".join(receiver)
  44. message['subject']=subject
  45. message.attach(fujian)
  46. #登录smtp服务器并发送邮件
  47. smtp=smtplib.SMTP_SSL(smtpserver,465)
  48. smtp.login(username,password)
  49. smtp.sendmail(username,receiver,message.as_string())
  50. smtp.quit()
  51. if __name__ == '__main__':
  52. dir = r'/mnt/jianyu_auto_api/log'
  53. filename = find_newest_file(dir)
  54. if filename:
  55. send_email(filename)