sendemail.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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=['lizhikun@topnet.net.cn']
  36. #创建邮件对象
  37. message=MIMEMultipart('related')
  38. #邮件主题
  39. subject="剑鱼自动化测试报告"
  40. fujian=MIMEText(open(f'D:\PycharmProjects\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()
  48. smtp.connect(smtpserver)
  49. smtp.login(username,password)
  50. smtp.sendmail(username,receiver,message.as_string())
  51. smtp.quit()
  52. if __name__ == '__main__':
  53. dir = r'D:\PycharmProjects\jianyu_auto_api\log'
  54. filename = find_newest_file(dir)
  55. if filename:
  56. send_email(filename)