Home > Mobile >  Passing variables to html from Python
Passing variables to html from Python

Time:09-26

I have a function which sends a mail to a user, like this:

import os
import smtplib
import imghdr
from email.message import EmailMessage

EMAIL_ADDRESS = email
EMAIL_PASSWORD = password


msg = EmailMessage()
msg['Subject'] = 'Email Title'
msg['From'] = EMAIL_ADDRESS
msg['To'] = ANOTHER_EMAIL_ADDRESS

msg.set_content('Email content')
html = open('email.html', 'r').read()
print(html)
msg.add_alternative(html, subtype='html')


with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
    smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
    smtp.send_message(msg)

And the html file is like the following:

<!DOCTYPE html>

<body>
    <h3 style="font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;font-size: large;font-weight: bold;">Hey there, {{userEmail}}!
        <h3>


</body>

</html>

I want to be able to pass the 'userEmail' variable to the HTML file. How may I do that?

CodePudding user response:

In email.html change {{userEmail}} to {userEmail}. Then you should be able to use Python string formatting to add the `userEmail variable.

userEmail = "MyFriend"
html = open('email.html', 'r').read().format(userEmail=userEmail)
print(html)
  • Related