我正在尝试使用 Django 制作一个电子邮件通知系统,但是有一个问题。电子邮件正文不会呈现 html 标签,而是以长行形式显示 html 标签和消息。即使消息包含 ,它不会创建新行,而是创建 在电子邮件正文中不可见
这是我的电子邮件模板
<!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 标签没有正确渲染吗?
同样的原因为什么下面的代码片段在一行中写着“hello world”。
<div>
hello
world
</div>
使用 Django 的 linebreaksbr 过滤器在换行符处添加
<br>
标签,即 {{ body | linebreaksbr }}
你最终会得到
<div>
hello<br>
<br>
world
</div>