I want to send a status mail once a day using a cron job using smtplib.
Sending of the mail works well, however the sending time and date always seems to be the time and date when I read the mail, but not when the mail is sent. This may be 6 hours later.
I have not found hints on providing a sending time to smtplib, together with the message data. Am I missing anything or is this a problem with my mail server configuration? However, other mails handed in via Thunderbird do not show this effect with this account.
My python program (with login data removed) is listed below:
import smtplib
sender = '[email protected]'
receivers = ['[email protected]']
message = """From: Sender <[email protected]>
To: Receiver<[email protected]>
Subject: Testmail
Hello World.
"""
try:
smtpObj = smtplib.SMTP('mailprovider.mailprovider.com')
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email"
except SMTPException:
print "Error: unable to send email"
[EDIT]
Code using email package as suggested, but still the time shown in my inbox is reading time and not sending time.
import smtplib
from email.mime.text import MIMEText
sender = ..
receiver = ..
message = "Hello World"
msg = MIMEText(message)
msg['Subject'] = 'Testmessage'
msg['From'] = sender
msg['To'] = receiver
try:
s = smtplib.SMTP(..)
s.sendmail(sender, receiver, msg.as_string())
s.quit()
print "Successfully sent email"
except SMTPException:
print "Error: unable to send email"
Adding an explicit Date field to the message did the trick, thank you to Serge Ballesta for the idea:
import smtplib
from email.utils import formatdate
from email.mime.text import MIMEText
sender = ..
receiver = ..
message = "Hello World"
msg = MIMEText(message)
msg['Subject'] = 'Testmessage'
msg['From'] = sender
msg['To'] = receiver
msg["Date"] = formatdate(localtime=True)
try:
s = smtplib.SMTP(..)
s.sendmail(sender, receiver, msg.as_string())
s.quit()
print "Successfully sent email"
except SMTPException:
print "Error: unable to send email"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With