2012-06-20 18 views
0

我有一個帶通知模塊的web.py項目 - 系統會通過發送HTML格式的電子郵件來通知用戶。我知道如何在python中發送HTML格式的電子郵件(同樣在此Q sendmail with HTML message中描述),並且也知道web.py(版本0.37)中的sendmail()函數。如何在python中僅使用web.py發送郵件?

import web 

web.config.smtp_server = 'smtp.gmail.com' 
web.config.smtp_port = 587     
web.config.smtp_username = '[email protected]' 
web.config.smtp_password = '*********'  
web.config.smtp_starttls = True 

web.sendmail('[email protected]',['[email protected]'],'Hello nodexy','This email is from web.py !') 

我想到:

web.sendmail('[email protected]',['[email protected]'],'Hello nodexy', '<html><img src="hello.png"/></html>') 

現在,我怎麼在web.py解決這一問題?我確定我無法將HTML字符串設置爲sendmail()函數。在web.py utils.py

web.sendmail(from_address, to_address, subject, msg, headers={'Content-Type':'text/html;charset=utf-8'}) 

,看到_EmailMessage的prepare_message方法:

+0

你有一些例外情況嗎? – iMom0

+0

上面的代碼是可以的。但問題是如何在web.py中發送HTML郵件?也許不使用sendmail()?任何其他功能? –

+0

我從web.py幫助信息中獲得了它。只需導入web和幫助(web.sendmail):)。不管怎麼說,還是要謝謝你 ! –

回答

1

發送HTML郵件,添加一鍵頭

def prepare_message(self): 
    for k, v in self.headers.iteritems(): 
     if k.lower() == "content-type": 
      self.message.set_type(v) 
     else: 
      self.message.add_header(k, v) 

    self.headers = {} 
+0

謝謝!我看到它:) https://github.com/webpy/webpy/blob/master/web/utils.py –

0

我得到它從幫助(web.sendmail )在web.py!

>>> import web 
>>> help(web.sendmail) 

幫助的sendmail的功能模塊web.utils:

sendmail(from_address, to_address, subject, message, headers=None, **kw) 

發送電子郵件message用郵件和信封頭 從from_address_to_addresssubject。 其他電子郵件標題可以用字典 `標題指定。

可以將cc,bcc和附件指定爲關鍵字參數。 附件必須是可迭代的,每個附件可以是 文件名或文件對象或帶有文件名,內容和 (可選)內容類型鍵的字典。

作爲@ number23_cn的答案,只需將這個鍵'Content-Type'添加到標題。