html 电子邮件 python 中的 if 语句

if statement inside html email python

我正在使用 MIME Multipart 在 HTML 中撰写电子邮件并使用 smtplib 发送,并且希望仅在条件计算结果为真时包含一个句子。基本上像

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 empaneled (value = 1) the sentence following this should be which else if value = 0, should not appear .任何关于如何使用 python 执行此操作的指示将不胜感激。

如前所述,您应该使用 Jinja2 之类的东西。但是,除非我误解了你的问题,否则你在 python 中有 empanelled 变量。为什么不像这样评估 python 中的条件:

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="")

尽管如此,一些模板语言方法仍然会更好。

像这样:

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