我想使用这样的 Django 模板发送 HTML 电子邮件:
<html> <body> hello <strong>{{username}}</strong> your account activated. <img src="mysite.com/logo.gif" /> </body>
我找不到任何关于的内容send_mail,并且 django-mailer 只发送 HTML 模板,没有动态数据。
send_mail
如何使用 Django 的模板引擎生成电子邮件?
在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()
您可能需要两个用于电子邮件的模板 - 一个看起来像这样的纯文本模板,存储在您的模板目录下email.txt:
email.txt
Hello {{ username }} - your account is activated.
和一个HTMLy,存储在email.html:
email.html
Hello <strong>{{ username }}</strong> - your account is activated.
然后,您可以使用这两个模板发送电子邮件get_template,如下所示:
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()