I am trying to send an email from a cronjob via smtplib. Running the python-script as user or as root works correctly, however as a cron-job I "think" I get problems connecting to the server. The code itself is the following:
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)
If I run the code from the command-line via "python " I get the following output:
<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
However if I run the same script from the cronjob with printing the outputs into a file I get the following:
<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
The behaviour is identical whether I have the cronjob brought in either way: "sudo crontab -e" or "crontab -e". In both crontabs I have the following entry (one at a time):
@reboot python /my_script.py > /logfile.txt
In another script I printed the PATH-variable and that is identical between the command-line and the cron-tab.
Any idea where this is going wrong? The smtplib seems to be correctly found based on the print-statement, also the python-interpreter. Thanks a lot already in advance!
Moadl