提问人:Sushi Wolf 提问时间:9/30/2023 更新时间:9/30/2023 访问量:44
Django Email 不呈现 HTML 标签
Django Email doesn't render HTML tags
问:
我正在尝试使用 Django 制作电子邮件通知系统,但有一个问题。电子邮件的正文不会呈现 html 标记,而是在长行中显示 html 标记和邮件。即使邮件包含 \n,它也不会创建新行,但 \n 在电子邮件正文中不可见
这是我的电子邮件模板
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{subject}}</title>
</head>
<body>
{{body}}
</body>
</html>
这是我发送电子邮件的代码
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from django.utils.html import strip_tags
from django.conf import settings
class SendNotification:
@staticmethod
def by_email(instance):
subject = instance.subject
to = list(instance.receivers.values_list("to", flat=True))
html_content = render_to_string("email.html", {'subject': subject, "body": instance.message})
text_content = strip_tags(html_content)
try:
email = EmailMultiAlternatives(
subject,
text_content,
settings.EMAIL_HOST_USER,
to,
)
email.attach_alternative(html_content, 'text/html')
email.send()
instance.counter += 1
instance.save()
instance.receivers.all().update(status=True)
知道为什么 HTML 标签没有正确呈现吗?
答:
0赞
AKX
9/30/2023
#1
与以下代码片段在一行上说“hello world”的原因相同。
<div>
hello
world
</div>
使用 Django 的换行符 filter 在换行符所在的位置添加标签,即<br>
{{ body | linebreaksbr }}
你最终会得到
<div>
hello<br>
<br>
world
</div>
另一方面,如果您本身已经有 HTML 标签,则需要使用安全
过滤器对其进行标记。body
1赞
cluex4
9/30/2023
#2
AKX的最后一点是我解释你的问题时的正确答案。
如果 body 中有 HTML,你需要把它作为 ,否则 Django 会用 < 替换 等等。{{body | safe}}
<
Safe 表示“此内容可以安全呈现,我知道我在做什么”,而默认值为“不安全”,这意味着任何<、>和其他一些零碎的东西都将被转义,因为它们可能是用户提供的内容,导致 XSS 攻击(参见 https://owasp.org/www-community/attacks/xss/)。
如果只是将其视为电子邮件,则风险低于浏览器,但值得考虑电子邮件模板的所有数据源以及可能引入错误或恶意输入的位置。
与您的问题无关,但根据受众的不同,您可能要考虑密件抄送而不是密件抄送,并且标题可以方便地停止收到一堆外出电子邮件来回复您的邮件(可能会导致一个大的 ol' 电子邮件循环)。Precedence: Bulk
评论