2016-09-16 47 views
0

我想用主題和消息使用GMAIL發送電子郵件。我成功地使用GMAIL發送了一封電子郵件,但沒有執行subject,並且也能夠接收電子郵件。但是,每當我嘗試添加主題時,該程序都無法正常工作。如何將主題添加到與Gmail一起發送的電子郵件?

import smtplib 
fromx = '[email protected]' 
to = '[email protected]' 
subject = 'subject' #Line that causes trouble 
msg = 'example' 
server = smtplib.SMTP('smtp.gmail.com:587') 
server.starttls() 
server.ehlo() 
server.login('[email protected]', 'password') 
server.sendmail(fromx, to, subject , msg) #'subject'Causes trouble 
server.quit() 

錯誤行:

server.sendmail(fromx, to, subject , msg) #'subject'Causes trouble 
+0

RTFM安裝? https://docs.python.org/2/library/smtplib.html#smtplib.SMTP.sendmail:'(from_addr,to_addr,msg,mail_options)'。 –

+0

閱讀用python自動化無聊的東西https://automatetheboringstuff.com/chapter16/ – danidee

回答

3

smtplib.SMTP.sendmail()調用不採取subject參數。有關如何調用它的說明,請參閱the doc

主題行以及所有其他標題作爲消息的一部分以RFC822格式的格式包含在最初定義格式的現已過時的文檔之後。讓您的信息符合上面的格式,比如:

import smtplib 
fromx = '[email protected]' 
to = '[email protected]' 
subject = 'subject' #Line that causes trouble 
msg = 'Subject:{}\n\nexample'.format(subject) 
server = smtplib.SMTP('smtp.gmail.com:587') 
server.starttls() 
server.ehlo() 
server.login('[email protected]', 'xxx') 
server.sendmail(fromx, to, msg) 
server.quit() 

當然,更簡單的方法,以符合您的消息給所有適當的標準是使用Python email.message標準庫,就像這樣:

import smtplib 
from email.mime.text import MIMEText 

fromx = '[email protected]' 
to = '[email protected]' 
msg = MIMEText('example') 
msg['Subject'] = 'subject' 
msg['From'] = fromx 
msg['To'] = to 

server = smtplib.SMTP('smtp.gmail.com:587') 
server.starttls() 
server.ehlo() 
server.login('[email protected]', 'xxx') 
server.sendmail(fromx, to, msg.as_string()) 
server.quit() 

Other examples也可用。

+0

感謝羅!很好的解釋!不夠感謝你! – ThatOnePythonNoob

0

或者只是使用像yagmail這樣的軟件包。免責聲明:我是維護者。

import yagmail 
yag = yagmail.SMTP("email.gmail.com", "password") 
yag.send("email1.gmail.com", "subject", "contents") 

pip install yagmail

+0

我之前確實嘗試過。似乎沒有工作。 – ThatOnePythonNoob

+0

會對這個錯誤信息感到好奇。 – PascalVKooten

相關問題