2016-11-18 96 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()