Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending mail via smtplib loses time

Tags:

python

smtplib

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"  
like image 324
tfv Avatar asked Dec 10 '22 17:12

tfv


1 Answers

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"
like image 52
tfv Avatar answered Dec 13 '22 06:12

tfv