0

I am trying to send an email using sendgrid. For this I created an html file and I want to format some variables into it.

Very basic test.html example:

<html>
    <head>
    </head>

    <body>
        Hello World, {name}!
    </body>
</html>

Now in my Python code I am trying to do something like this:

html = open("test.html", "r")
text = html.read()

msg = MIMEText(text, "html")
msg['name'] = 'Boris'

and then proceed to send the email

Sadly, this does not seem to be working. Any way to make this work?

  • 1
    Using [Jinja2](https://jinja.palletsprojects.com/en/2.10.x/nativetypes/) will be helpful here – lwileczek Jan 24 '20 at 17:04
  • 1
    Use templating? Maybe jinja. Or https://stackoverflow.com/a/6385940/1011724 – Dan Jan 24 '20 at 17:04
  • You can use standard string formatting `"Hello {name}!".format(name="Boris")` but `Jinja2` could be nicer if you would need `for`-loops to add many list of elements in HTML. – furas Jan 24 '20 at 17:07

1 Answers1

2

There are a few ways to approach this depending on how dynamic this must be and how many elements you are going to need to insert. If it is one single value name then @furas is correct and you can simply put

html = open("test.html", "r")
text = html.read().format(name="skeletor")
print(text)

And get:

<html>
   <head>
   </head>

   <body>
    Hello World, skeletor!
   </body>
</html>

Alternatively you can use Jinja2 templates.

import jinja2
html = open("test.html", "r")
text = html.read()
t = jinja2.Template(text)
print(t.render(name="Skeletor"))

Helpful links: Jinja website

Real Python Primer on Jinja

Python Programming Jinja

lwileczek
  • 2,084
  • 18
  • 27