Python smtplib 只发送消息正文

Python smtplib only sending message body

使用 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") 

任何人都可以解释为什么这是 happening/what 我可以做些什么来解决它吗?

在将消息传递给 .sendmail(), you must format the message as an "RFC822" message. (It is named that after the original and now obsolete version of the Internet email message format standard. The current version of that standard is RFC5322 之前。)

创建 RFC822 消息的一种简单方法是使用 Python 的 email.message type heirarchy. In your case, the subclass 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()