2016-11-18 89 views
1

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

#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 protected]' 
FROM = '[email protected]' 

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

print("Done") 

任何人都可以解释为什么发生这种情况/我能做些什么来解决它?

回答

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 protected]' 
FROM = '[email protected]' 

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()