Python smtplib只发送消息体

时间:2016-11-18 21:34:59

标签: python email smtp smtplib

使用Python,我写了一个简单的计时器,当计时器达到0时发送一封电子邮件。但是发送的邮件的唯一部分是正文。未发送发件人地址,收件人地址和主题。这是代码:

#Coffee timer
import smtplib

#Set timer for 00:03:00
from time import sleep
for i in range(0,180):
print(180 - i),
sleep(1)
print("Coffee is ready")

print("Sending E-mail")

SUBJECT = 'Coffee timer'
msg = '\nCoffee is ready'
TO = 'email-B@email.com'
FROM = 'email-A@email.com'

server = smtplib.SMTP('192.168.1.8')
server.sendmail(FROM, TO, msg, SUBJECT)
server.quit()

print("Done") 

任何人都可以解释为什么会这样做/我可以做些什么来解决它?

1 个答案:

答案 0 :(得分:1)

在将消息传递给.sendmail()之前,您必须将消息格式化为“RFC822”消息。 (它被命名为Internet email message format标准的原始版本和现在已过时版本。该标准的当前版本为RFC5322。)

创建RFC822消息的一种简单方法是使用Python的email.message类型层次结构。在您的情况下,子类email.mime.text.MIMEText将很好地完成。

试试这个:

#Coffee timer
import smtplib
from email.mime.text import MIMEText

print("Coffee is ready")

print("Sending E-mail")

SUBJECT = 'Coffee timer'
msg = 'Coffee is ready'
TO = 'email-B@email.com'
FROM = 'email-A@email.com'

msg = MIMEText(msg)
msg['Subject'] = SUBJECT
msg['To'] = TO
msg['From'] = FROM

server = smtplib.SMTP('192.168.1.8')
server.sendmail(FROM, TO, msg.as_string())
server.quit()

print("Done")

作为.sendmail()的便捷替代方案,您可以使用.send_message(),如下所示:

# Exactly the same code as above, until we get to smtplib:
server = smtplib.SMTP('192.168.1.8')
server.send_message(msg)
server.quit()
相关问题