Search code examples
pythonmime

if statement inside html email python


I am using MIME Multipart to compose an email in HTML and sending using smtplib and would like to include a sentence only if a condition evaluates to true. Basically something like

html = """\
    <html>
      <body>
        Hi {name}<br>
        Hope you are doing well.
           **<% if {empanelled}: %>**
                <br> We are already empanelled with your company<br>

      </body>
    </html>
    """.format(name=firstname, empanelled = empanelled)

If we are empanelled (value = 1) the sentence following this should be written else if value = 0, should not appear . Any pointers to how I can do this with python will be greatly appreciated.


Solution

  • As mentioned, you should using something like Jinja2. However, unless I am misunderstanding your question, you have the empanelled variable in python. why not jus evaluate the conditional in python like this:

    html = """\
        <html>
          <body>
            Hi {name}<br>
            Hope you are doing well.
                 {additional_message}
          </body>
        </html>
        """
    
    if empanelled:
        return html.format(name=firstname, additional_message="<br> We are already empanelled with your company<br>")
    else:
        return html.format(name=firstname,additional_message="")
    

    Although, some templating language approach would still be better.