通过 smtplib 发送邮件会浪费时间

Sending mail via smtplib loses time

我想使用 smtplib 的 cron 作业每天发送一次状态邮件。

邮件发送正常,但是发送时间和日期似乎总是我阅读邮件的时间和日期,而不是邮件发送时的时间和日期。这可能是 6 小时后。

我没有找到有关向 smtplib 提供发送时间以及消息数据的提示。我是否遗漏了什么或者这是我的邮件服务器配置的问题?但是,通过 Thunderbird 提交的其他邮件不会显示此帐户的此效果。

我的 python 程序(已删除登录数据)如下所示:

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"

[编辑]

按照建议使用电子邮件包进行编码,但收件箱中显示的时间仍然是阅读时间而不是发送时间。

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"  

您可能需要在消息的 headers 中指定更多信息。尝试使用 email module 构建您的消息,而不是自己组装文本。

也许这很愚蠢,但是你在服务器上有正确的日期和时间吗?

在消息中添加一个明确的日期字段就成功了,感谢 Serge Ballesta 的想法:

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"