如何在Django中发送包含动态内容的HTML邮件?

82 投票
7 回答
102137 浏览
提问于 2025-04-15 23:44

有没有人能帮我发送带有动态内容的HTML邮件?一种方法是把整个HTML代码复制到一个变量里,然后在Django的视图中填充动态内容,但这样做似乎不是个好主意,因为这个HTML文件非常大。

我会很感激任何建议。

谢谢。

7 个回答

19

对于2020年查看这个内容并使用django v3.x的人来说(我不知道这个功能是什么时候引入的,所以可能也适用于更早的版本)。

注意:我只想包含一个html版本,而不需要纯文本版本。我的django视图代码如下:

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

# import html message.html file
html_template = 'path/to/message.html'

html_message = render_to_string(html_template, { 'context': context, })

message = EmailMessage(subject, html_message, from_email, [to_email])
message.content_subtype = 'html' # this is required because there is no plain text email message
message.send()

我的html文件(message.html)看起来是这样的:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <title>Order received</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<body style="margin: 0; padding: 0;">
  <table align="center" border="0" cellpadding="0" cellspacing="0" width="320" style="border: none; border-collapse: collapse; font-family:  Arial, sans-serif; font-size: 14px; line-height: 1.5;">
...
content
...
</table>
</body>
</html>

更多细节请查看:从 django文档 发送替代内容类型

76

示例:

from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from django.utils.html import strip_tags

subject, from_email, to = 'Subject', 'from@xxx.com', 'to@xxx.com'

html_content = render_to_string('mail_template.html', {'varname':'value'}) # render with dynamic value
text_content = strip_tags(html_content) # Strip the html tag. So people can see the pure text at least.

# create the email, and attach the HTML version as well.
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()
174

Django现在有了一个叫做 django.core.mail.send_mail 的方法(2018年开始),你不需要直接使用 EmailMultiAlternatives 这个类了。你可以这样做:

from django.core import mail
from django.template.loader import render_to_string
from django.utils.html import strip_tags

subject = 'Subject'
html_message = render_to_string('mail_template.html', {'context': 'values'})
plain_message = strip_tags(html_message)
from_email = 'From <from@example.com>'
to = 'to@example.com'

mail.send_mail(subject, plain_message, from_email, [to], html_message=html_message)

这样发送的邮件在支持HTML的浏览器中可以正常显示,同时在一些功能较弱的邮件查看器中也能显示普通文本。

撰写回答