Search code examples
pythonhtml-emailsmtplib

How to pass variable to html emails sent from Python


I have this python script:

import time
from email.message import EmailMessage

user_age = "12"
user_name="John"

msg = EmailMessage()
msg['Subject'] = "Test Subject"
msg['From'] = '[email protected]'
msg['To'] = '[email protected]'
msg.set_content("Test Mesage")

html_message = open('test.html').read()
msg.add_alternative(html_message, subtype='html')


while True:
    with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
        smtp.login("[email protected]", "pass")
        smtp.send_message(msg)

    time.sleep(500)

I want to pass a variable like first_name, age, links from this python script to html template (test.html), access and format them into html. Something like:

<html>
    <head>
     ....
    </head>
    <body>
        Hei user {{user_name}} we recieved your age confirmation! {{user_age}} is it right?
    </body>
</html>

Solution

  • Just replace your placeholders with the variables:

    html_message = html_message.replace('{{user_name}}',user_name).replace('{{user_age}}',user_age)