Python Variable in an HTML email in Python

David Vasandani picture David Vasandani · Nov 3, 2012 · Viewed 30.9k times · Source

How do I insert a variable into an html email I'm sending with python? The variable I'm trying to send is code. Below is what I have so far.

text = "We Says Thanks!"
html = """\
<html>
  <head></head>
  <body>
    <p>Thank you for being a loyal customer.<br>
       Here is your unique code to unlock exclusive content:<br>
       <br><br><h1><% print code %></h1><br>
       <img src="http://domain.com/footer.jpg">
    </p>
  </body>
</html>
"""

Answer

Eric picture Eric · Nov 3, 2012

Use "formatstring".format:

code = "We Says Thanks!"
html = """\
<html>
  <head></head>
  <body>
    <p>Thank you for being a loyal customer.<br>
       Here is your unique code to unlock exclusive content:<br>
       <br><br><h1>{code}</h1><br>
       <img src="http://domain.com/footer.jpg">
    </p>
  </body>
</html>
""".format(code=code)

If you find yourself substituting a large number of variables, you can use

.format(**locals())