Jidey
Jidey

Reputation: 359

Flask render_template() return raw HTML, not processed

I'm workin with flask mail, I want to insert a rendered HTML in my mail.

Here is the code :

Controller :

        msg = Message("test", sender='[email protected]', recipients=[user.get("email")])
        msg.body = render_template('/assets/views/emailing/notification.html', name=user.get("name"))
        mail.send(msg)

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

{% if name %}
  <h1>Hello {{ name }}!</h1>
{% else %}
  <h1>Hello, World!</h1>
{% endif %}

</body>
</html>

So I expect a rendered email, or at least the html as text but with the keys replaced by values.

Here is what i got :

https://i.sstatic.net/L515n.png

Any clue of what is happening ?

Upvotes: 0

Views: 1003

Answers (1)

Bovarysme
Bovarysme

Reputation: 453

As you are sending an HTML email, you need to set the html attribute instead of body, like so:

html = render_template('/assets/views/emailing/notification.html', name=user.get("name"))
msg = Message("test", sender='[email protected]', recipients=[user.get("email")], html=html)
mail.send(msg)

Upvotes: 4

Related Questions