用Django创建电子邮件模板?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (124)

我想使用这样的Django模板发送HTML-电子邮件:

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

找不到任何关于send_mail,Django-mailer只发送HTML模板,没有动态数据。

提问于
用户回答回答于

可以:

from django.core.mail import send_mail
from django.template.loader import render_to_string


msg_plain = render_to_string('templates/email.txt', {'some_params': some_params})
msg_html = render_to_string('templates/email.html', {'some_params': some_params})

send_mail(
    'email title',
    msg_plain,
    'some@sender.com',
    ['some@receiver.com'],
    html_message=msg_html,
)
用户回答回答于

若要发送HTML电子邮件,请使

from django.core.mail import EmailMultiAlternat用其他内容类型,如下所示:ives

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:

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

扫码关注云+社区

领取腾讯云代金券