使用 html_message 发送电子邮件

Send Emails with html_message

我想发送 HTML-email,使用像这样的 Django 模板:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    Hello <strong>{{ message }}</strong> - your account is activated.
</body>
</html>

我也想用Email从后端发送数据。在此示例中,我想使用电子邮件模板从后端发送消息。

这是我的看法:

def home(request):
    message_name = "NAME"
    message_email = "EMAIL"
    message = "USER"
    msg_html = render_to_string('email/email.html')

    send_mail(
        'message from ' + message_name,  # subject
        message,  # message
        message_email,  # from email
        ['myemail@outlook.de'],  # To Email
        html_message=msg_html,
    )
    context = {'message': message, 'message_name': message_name, 'message_email': message_email}
    return render(request, 'email/email.html', context)

当我收到电子邮件时,我只收到文本,而不是 {{ message }},在此示例中为 USER

您需要将上下文传递到您的 render_to_string 调用中。 render_to_string 使用模板和 returns HTML 传递的上下文。然后你可以传递给 send_mail。所以把代码改成:

[...]
message_name = 'NAME'
message_email = 'EMAIL'
message = 'USER'
context = {'message': message, 'message_name': message_name, 'message_email': message_email}
msg_html = render_to_string('email/email.html', context=context)
[...]