使用smtplib+crontab自动发邮件出现重复发送(4次)问题求助
邮件重复发送4次问题排查(smtplib + crontab)
我通过smtplib包结合Linux系统的crontab定时任务自动发送文件,近期更新邮件分发列表后,邮件不再仅发送一次,而是重复发送4次,恳请协助排查解决。
以下是我的代码:
import smtplib from email.message import EmailMessage def Emailer(): files = ['file1.csv', 'file2.csv', 'file3.csv', 'file.log'] new_attach = [f"file1{today}.csv",f"file2{today}.csv",'file3.csv', 'file.log' ] new_ref = {orig_file: new_file for orig_file, new_file in zip(files, new_attach)} msg = EmailMessage() msg['Subject'] = "Subject" msg['From'] = 'from@from.com' msg['To'] = ['user1@user.com', 'user2@user.com', 'user3@user.com', 'user4@user.com'] msg['Cc'] = ['user5@user.com', 'user6@user.com', 'user7@user.com', 'user8@user.com', 'user9@user.com', \ 'user11@user.com', 'user111@user.com', 'user1111@user.com'] msg.set_content( f""" <p>Message content here!</p>""", subtype='html') for filename in files: with open(filename, 'rb') as file: file_data = file.read() new_name = new_ref[file.name] msg.add_attachment(file_data, maintype='application', subtype='octet-stream', filename=new_name) try: with smtplib.SMTP('sendsmtp.server.com', 25) as s: s.send_message(msg) # s.set_debuglevel(2) print('email has been sent') except Exception as ex: print(ex, "Message was not sent!")
排查方向
- 检查crontab定时任务:执行
crontab -l查看是否存在多条相同的定时任务,或者任务的时间规则是否会重复触发脚本。 - 记录脚本执行次数:在脚本开头添加日志记录,比如
echo "$(date) 脚本执行" >> /tmp/email_script_run.log,通过日志确认是crontab重复触发还是脚本内部问题。 - 验证SMTP发送逻辑:确认代码中
Emailer()函数是否被多次调用,同时如果有权限,查看SMTP服务器日志,判断是客户端发送了4次请求还是服务器重复投递。 - 排查收件人列表:检查更新后的
To/Cc列表是否有重复地址,或者是否存在邮箱自动转发导致重复接收的情况,可临时将收件人改为自己的邮箱做测试。 - 检查脚本异常:代码中
today变量未定义,可能导致脚本报错退出,crontab若检测到脚本非零退出可能会重复执行,建议检查脚本执行日志是否有报错信息。
内容的提问来源于stack exchange,提问作者aero8991
相关产品推荐
相关产品推荐

