2010-06-09 83 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')