我想使用Django模板发送HTML邮箱,如下所示:

<html>
<body>
hello <strong>{{username}}</strong>
your account activated.
<img src="mysite.com/logo.gif" />
</body>

我找不到任何关于send_mail的东西,而且Django-Mailer只发送HTML模板,没有动态数据.

如何使用Django的模板引擎生成邮箱?

推荐答案

the docs开始,要发送HTML邮箱,您需要使用其他内容类型,如下所示:

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()

您的邮箱可能需要两个模板-纯文本模板,如下所示,存储在Templates目录下的email.txt下:

Hello {{ username }} - your account is activated.

还有一个HTMLy的,存储在email.html以下:

Hello <strong>{{ username }}</strong> - your account is activated.

然后,您可以使用这两个模板通过使用get_template发送邮箱,如下所示:

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相关问答推荐

为什么当对字段使用自定义序列化器时,Django Rest框架中Inbox字段会消失?

Djnago admin中 Select 字段的自定义查询

在Django测试get方法中获取HttpResponseNotFound

使用 Pytest 在 Django 中编写测试用例时如何加载特定目录中的所有固定装置

Playframework 和 Django

ModelForm 的 Django TextField max_length 验证

什么时候在 django rest 框架序列化程序中调用创建和更新?

为 Django 模型生成非顺序 ID/PK

如何在 forms.Form 子类上动态设置 models.ModelChoiceField 的查询集

无法通过 pip 安装 Django 2.0

magic有什么问题?

手动触发 Django 邮件错误报告

__init__() 得到了一个意外的关键字参数user

Python:获取异常的错误消息

Django unique=True 不工作

Django Rest Framework - 缺少静态目录

Django查询否定

如何在 Django/Python 中减go 两个日期?

django.urls.path中name参数的作用是什么?

APIView 类和视图集类之间的区别?