我想用Django模板发送html邮件:
<!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>
我还想从电子邮件后端发送数据。在这个例子中,我想用电子邮件模板从后端发送一条消息。
这是我的视图:
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)
当我收到电子邮件时,我只得到文本而不是{{消息}},这将是USER在这个例子中
您需要将上下文传递到render_to_string
调用中。render_to_string
接受模板并返回带有传递的上下文的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)
[...]