2010-06-09 35 views
12

任何人都可以請幫助我發送動態內容的HTML電子郵件。一種方法是將整個html代碼複製到一個變量中,並在Django視圖中填充動態代碼,但這似乎不是一個好主意,因爲它是一個非常大的html文件。如何發送帶有動態內容的django html郵件?

我將不勝感激任何建議。

謝謝。

+2

爲什麼不像Django中的其他任何HTML呈現一樣使用模板? – 2010-06-09 11:07:00

+0

我正在使用一個模板,並已成功呈現變量,但問題是如何將該呈現的模板作爲電子郵件發送? – 2010-06-09 11:22:25

+2

使用render_to_string – KillianDS 2010-06-09 11:23:15

回答

8

這應該做你想要什麼:

from django.core.mail import EmailMessage 
from django.template import Context 
from django.template.loader import get_template 


template = get_template('myapp/email.html') 
context = Context({'user': user, 'other_info': info}) 
content = template.render(context) 
if not user.email: 
    raise BadHeaderError('No email address given for {0}'.format(user)) 
msg = EmailMessage(subject, content, from, to=[user.email,]) 
msg.send() 

更多請見django mail docs

+4

或者正如我所說的,對於前3行,使用render_to_string快捷方式,它存在的原因。 – KillianDS 2010-06-10 13:53:47

+0

謝謝,我將在我的項目中使用它,並且(如果我記得的話)在我測試過它之後編輯我的答案。 – blokeley 2010-06-11 11:42:41

32

實施例:

from django.core.mail import EmailMultiAlternatives 
from django.template.loader import render_to_string 
from django.utils.html import strip_tags 

subject, from_email, to = 'Subject', '[email protected]', '[email protected]' 

html_content = render_to_string('mail_template.html', {'varname':'value'}) # render with dynamic value 
text_content = strip_tags(html_content) # Strip the html tag. So people can see the pure text at least. 

# create the email, and attach the HTML version as well. 
msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) 
msg.attach_alternative(html_content, "text/html") 
msg.send() 

參考

http://www.djangofoo.com/250/sending-html-email/comment-page-1#comment-11401

+1

+1 EmailMultiAlternatives。官方文檔:https://docs.djangoproject.com/en/1.8/topics/email/#sending-alternative-content-types – dokkaebi 2015-08-31 16:33:34

3

嘗試此::::

https://godjango.com/19-using-templates-for-sending-emails/

sample code link

# views.py 

from django.http import HttpResponse 
from django.template import Context 
from django.template.loader import render_to_string, get_template 
from django.core.mail import EmailMessage 

def email_one(request): 
    subject = "I am a text email" 
    to = ['[email protected]'] 
    from_email = '[email protected]' 

    ctx = { 
     'user': 'buddy', 
     'purchase': 'Books' 
    } 

    message = render_to_string('main/email/email.txt', ctx) 

    EmailMessage(subject, message, to=to, from_email=from_email).send() 

    return HttpResponse('email_one') 

def email_two(request): 
    subject = "I am an HTML email" 
    to = ['[email protected]'] 
    from_email = '[email protected]' 

    ctx = { 
     'user': 'buddy', 
     'purchase': 'Books' 
    } 

    message = get_template('main/email/email.html').render(Context(ctx)) 
    msg = EmailMessage(subject, message, to=to, from_email=from_email) 
    msg.content_subtype = 'html' 
    msg.send() 

    return HttpResponse('email_two') 
相關問題