使用Django创建电子邮件模板 [英] Creating email templates with Django
问题描述
我想使用这样的Django模板发送HTML电子邮件:
I want to send HTML-emails, using Django templates like this:
<html>
<body>
hello <strong>{{username}}</strong>
your account activated.
<img src="mysite.com/logo.gif" />
</body>
我找不到关于 send_mail的任何内容
,并且django-mailer只发送HTML模板,没有动态数据。
I can't find anything about send_mail
, and django-mailer only sends HTML templates, without dynamic data.
如何使用Django的模板引擎生成电子邮件?
How do I use Django's template engine to generate e-mails?
推荐答案
从文档,要发送要使用其他内容类型的HTML电子邮件,如下所示:
From the docs, to send HTML e-mail you want to use alternative content-types, like this:
from django.core.mail import EmailMultiAlternatives
subject, from_email, to = 'hello', 'from@example.com', 'to@example.com'
text_content = 'This is an important message.'
html_content = '<p>This is an <strong>important</strong> message.</p>'
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()
您可能需要两个模板用于您的电子邮件 - 一个纯文本,看起来像如下所示,存储在您的模板目录下, email.txt
:
You'll probably want two templates for your e-mail - a plain text one that looks something like this, stored in your templates directory under email.txt
:
Hello {{ username }} - your account is activated.
和一个HTMLy的,存储在 email.html
:
and an HTMLy one, stored under email.html
:
Hello <strong>{{ username }}</strong> - your account is activated.
然后您可以使用这两个模板发送电子邮件,使用 get_template
,如下所示:
You can then send an e-mail using both those templates by making use of get_template
, like this:
from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
from django.template import Context
plaintext = get_template('email.txt')
htmly = get_template('email.html')
d = Context({ 'username': username })
subject, from_email, to = 'hello', 'from@example.com', 'to@example.com'
text_content = plaintext.render(d)
html_content = htmly.render(d)
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()
这篇关于使用Django创建电子邮件模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!