[ Sending mail via smtplib loses time ]
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 = 'abc@def.com'
receivers = ['z@def.com']
message = """From: Sender <abc@def.com>
To: Receiver<z@def.com>
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"
Answer 1
You might have to specify more information in the headers of your message. Try using the email
module to build your message instead of assembling the text yourself.
Answer 2
Perhaps it's stupid, but do you have correct date and time on the server?
Answer 3
Adding an explicit Date field to the message did the trick, thank you to Serge Ballesta for the idea:
import smtplib
from email.mime.text import MIMEText
from email.Utils import formatdate
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"