pythonvariables

How to substitute variable value within another string variable in Python


I have HTML template in database column that is shared with another platform. The HTML template has placeholder variables. This value is pulled from DB in my Python script but for some reason, it is not replacing the placeholder variables with it's value.

Here is what the HTML string that is in DB.

    <html> Dear {FullName}, <p>We are excited to notify you that your account has been activated. Please login to your account at  
<a href="https://portal.example.com">My Account Portal</a>. </p> </html>

I get the name from DB table in the variable FullName. When the email is sent out, it doesn't replaces the name in the html template.

If I create a local python variable with the same html template and not pull from database, it works just fine.

So what I would like to know is how can I pull the html template from DB and make it work in my Python script?

The DB template can't be updated to use %s in html template as it is a vendor provided system and changing that will break that application.

Below is the Python script that I am using.

cur.execute("select FirstName,LastName, Email, AlternateEmail,CustCode from Customer Where CustCode = ?", f"{CustCode}")
    for data in cur.fetchall():
        FullName += data.FirstName+" "+data.LastName
        CustEmail += data.Email
        CustPIN += str(data.CustCode)
        ToEmail += data.AlternateEmail
    
    cur.execute("select Value from [dbo].[Configs] where [Name] = ?",'Email - Subject')
    for data in cur.fetchall():
        mail_subject += data.Value
    
    cur.execute("select Value from [dbo].[Configs] where [Name] = ?",'Email - Message Body')
    for data in cur.fetchall():
         mail_body = f'''
         {data.Value}
         '''

    send_mail(from_mail='noreply@example.com', to_mail=f'{cust_email}',subject=f'{mail_subject}',mailbody=mail_body,mime_type='html')

if I change the script to hardcode the html template within the script, it works and I want to avoid that so I wouldn't have to change the script every time when the template changes.

What are my option in this situation?


Solution

  • I think you just need to call the .format() string method on mail_body, and pass in the value of FullName.

    You can either do it at the end when you call send_mail():

    mailbody=mail_body.format(FullName=FullName)
    

    Or you can do it when you first read mail_body from the database:

    mail_body = f'''
    {data.Value}
    '''.format(FullName=FullName)