2012-06-20 52 views
2

我想發送一個包含某些數據的簡單HTML文件。我希望用戶能夠接收呈現的HTML。我試過這個解決方案:在電子郵件正文中呈現HTML

b = render_to_string('mail_body.html',{'name':request.POST['name']}) 
send_mail(email_subject,b,'[email protected]', ['[email protected]'], 
    fail_silently=False) 

但我沒有在郵件正文中呈現HTML,用戶可以看到所有的HTML標籤!

或者,當我使用下面的代碼我只是得到我的HTML文件的路徑,在郵件正文:

params = {} 
params['name'] = request.POST['name'] 
context = Context(params) 
t = Template('mail_body.html') 
send_mail(email_subject,t.render(context), '[email protected]', 
    ['[email protected]'], fail_silently=False) 
+0

我在想,這些樣式全部內嵌在.html – zinking

+1

我推薦使用http://code.activestate.com/recipes/473810-send-an-html-email-with-embedded-image-and-plain -t/- 處理html/attachments/images等的格式化,並提供一種發送純文本的方式 - 我已經在幾個項目中使用它 –

回答

2

你可以嘗試這樣的事:

from django.core.mail import EmailMultiAlternatives 
body = render_to_string(template_name, locals(), 
         context_instance=RequestContext(request)) 
email = EmailMultiAlternatives(subject, body, mail_sender, [contact_request.email], headers={'Reply-To': '[email protected]'}) 
email.content_subtype='html' 
email.send(fail_silently=False) 

希望這會導致到正確的方向。請注意,這裏有很多來自我自己編程的變量。

1

的問題是,你需要告訴用戶的郵件客戶端,你是把他們一個HTML電子郵件,否則它只會顯示HTML,就好像它是文本一樣。

該設置稱爲MIME類型,您可以在python user guides中閱讀更多關於如何設置(以及發送python中的HTML電子郵件)的信息。