Cronjob上的SMTPLIBemail失败

2024-04-24 10:04:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图通过smtplib从cronjob发送电子邮件。以用户或根用户身份运行python脚本可以正常工作,但是作为cron作业,我“认为”连接到服务器时会遇到问题。 代码本身如下:

import smtplib, ssl
from datetime import datetime

def send_mail(subject, mail_text, to_addr):
    FROM = "myaddress@gmail.com"
    SUBJECT = subject

    TEXT = (mail_text)

    mail_user=FROM
    mail_password="<password>"
    message = """From: %s\nTo: %s\nSubject: %s\n\n%s
    """ % (FROM, TO, SUBJECT, TEXT)
    print("message")
    print(message)
    try:
        print("a")
        server = smtplib.SMTP_SSL("smtp.gmail.com", 465)
        print(server)
        print("b")
        print(server.ehlo())
        print("Login on Server")
        print(server.login(mail_user, mail_password))
        print("Sending Mail")
        print(server.sendmail(FROM, TO, message))
        print("Closing Connection")
        server.close()
        print('Successfully sent the mail')
    except Exception as e:
        print( "failed to send mail")


subject="Start-Test"
mail_text="Cron-Job started"
to_addr="somewhere@example.com"
print ("Job started:")
print datetime.now()

send_mail(subject, mail_text, to_addr)

如果我通过“python”从命令行运行代码,我会得到以下输出:

<module 'smtplib' from '/usr/lib/python2.7/smtplib.pyc'> 
Job started: 2020-01-02 14:06:31.20274

message From: myaddress@gmail.com 
To: somewhere@example.com 
Subject: Start-Test 
Cron-Job started 
a 
<smtplib.SMTP_SSL instance at 0x76bbab48> 
b 
(250, 'smtp.gmail.com at your service, [92.211.42.193]\nSIZE 35882577\n8BITMIME\nAUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH\nENHANCEDSTATUSCODES\nPIPELINING\nCHUNKING\nSMTPUTF8') 
Login on Server (235, '2.7.0 Accepted') 
Sending Mail {} 
Closing Connection

但是,如果从cronjob运行相同的脚本并将输出打印到文件中,则会得到以下结果:

<module 'smtplib' from '/usr/lib/python2.7/smtplib.pyc'>
Job started:
2020-01-02 14:06:53.229564
message
From: myaddress@gmail.com
To: somewhere@example.com
Subject: Start-Test

Cron-Job started

a
failed to send mail

无论是哪种方式,我的行为都是一样的: “sudo crontab-e”或“crontab-e”。 在两个crontab中,我都有以下条目(一次一个):

@重启python/my_脚本.py&燃气轮机/日志文件.txt

在另一个脚本中,我打印了PATH变量,这在命令行和cron选项卡之间是相同的。你知道吗

知道哪里出了问题吗?smtplib似乎是基于print语句(也是python解释器)找到的。 提前多谢了!你知道吗

莫阿德尔


Tags: totextfrom脚本comsendmessageserver
1条回答
网友
1楼 · 发布于 2024-04-24 10:04:33

我的答案被删除了,虽然我认为它仍然是正确的答案,也许让弗朗索瓦是更明智的,可以张贴一个正确的答复/评论,而不是删除我的。你知道吗

所以我会转贴。。。你知道吗


当脚本在重新启动后运行时,网络可能还不可用,因此smtplib无法连接到SMTP服务器。您可以在cronjob中添加短暂的睡眠,或者在python脚本中添加重试。你知道吗

为了知道到底出了什么问题,您可以打印您的异常。你知道吗


Network is unreachable仍然与网络故障有关,您只是通过硬编码IP忽略了DNS解析错误(Temporary failure in name resolution)。你知道吗

为了进行双重检查,只需使用ping -c 4 8.8.8.8 > /tmp/ping_result运行@reboot cron。你知道吗

相关问题 更多 >