使用 Django 创建电子邮件模板 [英] Creating email templates with Django
问题描述
我想发送 HTML 电子邮件,使用 Django 模板,如下所示:
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?
推荐答案
来自 the docs,发送 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屋!