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

tfv*_*tfv 4 python smtplib

我想使用 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"
Run Code Online (Sandbox Code Playgroud)

[编辑]

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

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"  
Run Code Online (Sandbox Code Playgroud)

tfv*_*tfv 12

在消息中添加一个明确的日期字段可以解决问题,感谢 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"
Run Code Online (Sandbox Code Playgroud)