通过smtplib发送邮件会丢失时间

2024-09-24 22:26:57 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

我没有找到关于向smtplib提供发送时间和消息数据的提示。我遗漏了什么吗?还是邮件服务器配置有问题?但是,通过雷鸟提交的其他邮件在这个账户上没有显示这种效果。在

我的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"

[编辑]

代码使用电子邮件包,但我的收件箱显示的时间仍然是阅读时间而不是发送时间。在

^{pr2}$

Tags: 数据commessageemaildef时间邮件sender
3条回答

您可能需要在邮件头中指定更多信息。尝试使用^{} 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"

相关问题 更多 >