Python中HTML电子邮件中的Python变量

Python中HTML电子邮件中的Python变量,python,email,html-email,smtplib,Python,Email,Html Email,Smtplib,如何在使用python发送的html电子邮件中插入变量?我试图发送的变量是code。以下是我到目前为止的情况 text = "We Says Thanks!" html = """\ <html> <head></head> <body> <p>Thank you for being a loyal customer.<br> Here is your unique code to unlock

如何在使用python发送的html电子邮件中插入变量?我试图发送的变量是
code
。以下是我到目前为止的情况

text = "We Says Thanks!"
html = """\
<html>
  <head></head>
  <body>
    <p>Thank you for being a loyal customer.<br>
       Here is your unique code to unlock exclusive content:<br>
       <br><br><h1><% print code %></h1><br>
       <img src="http://domain.com/footer.jpg">
    </p>
  </body>
</html>
"""
text=“我们说谢谢!”
html=”“”\
感谢您成为忠实的客户。
以下是解锁独家内容的唯一代码:



"""
使用:

另一种方法是使用:

来自字符串导入模板的
>>
>>>html=“”\
感谢您成为忠实的客户。
以下是解锁独家内容的唯一代码:


$code

''' >>>s=模板(html).safe\u替换(code=“我们说谢谢!”) >>>印刷品 感谢您成为忠实的客户。
以下是解锁独家内容的唯一代码:


我们说谢谢


注意,我使用了
safe\u substitute
,而不是
substitute
,就好像有一个占位符不在提供的字典中一样,
substitute
将引发
值错误:字符串中的占位符无效。同样的问题也存在于。

使用pythons字符串操作:

通常,%运算符用于将变量放入字符串中,整数为%i,字符串为%s,浮点为%f, 注意:还有另一种格式类型(.format),也在上面的链接中描述过,它允许您传入一个dict或列表,比我在下面展示的稍微优雅一点,这可能是您应该长期使用的,因为如果您想将100个变量放入一个字符串中,那么%运算符会变得混乱,尽管使用dict(我的最后一个例子)有点否定这一点

code_str = "super duper heading"
html = "<h1>%s</h1>" % code_str
# <h1>super duper heading</h1>
code_nr = 42
html = "<h1>%i</h1>" % code_nr
# <h1>42</h1>

html = "<h1>%s %i</h1>" % (code_str, code_nr)
# <h1>super duper heading 42</h1>

html = "%(my_str)s %(my_nr)d" %  {"my_str": code_str, "my_nr": code_nr}
# <h1>super duper heading 42</h1>
code\u str=“超级复制头”
html=“%s”%code\u str
#超级二次头
代码=42
html=“%i”%code\u nr
# 42
html=“%s%i”%(代码\u str,代码\u nr)
#超级复制品目42
html=“%(my_str)s%(my_nr)d”%%{“my_str”:code_str,“my_nr”:code_nr}
#超级复制品目42
这是非常基本的,仅适用于基本类型,如果您希望能够存储dict、列表和可能的对象,我建议您使用cobvert将它们转换为json,这是很好的灵感来源


希望这有助于

对于更复杂的情况,您可能需要一个模板引擎,例如,如果需要在单个html中替换多个变量,我们如何提供?
.format(**locals())
>>> from string import Template
>>> html = '''\
<html>
  <head></head>
  <body>
    <p>Thank you for being a loyal customer.<br>
       Here is your unique code to unlock exclusive content:<br>
       <br><br><h1>$code</h1><br>
       <img src="http://domain.com/footer.jpg">
    </p>
  </body>
</html>
'''
>>> s = Template(html).safe_substitute(code="We Says Thanks!")
>>> print(s)
<html>
  <head></head>
  <body>
    <p>Thank you for being a loyal customer.<br>
       Here is your unique code to unlock exclusive content:<br>
       <br><br><h1>We Says Thanks!</h1><br>
       <img src="http://domain.com/footer.jpg">
    </p>
  </body>
</html>
code_str = "super duper heading"
html = "<h1>%s</h1>" % code_str
# <h1>super duper heading</h1>
code_nr = 42
html = "<h1>%i</h1>" % code_nr
# <h1>42</h1>

html = "<h1>%s %i</h1>" % (code_str, code_nr)
# <h1>super duper heading 42</h1>

html = "%(my_str)s %(my_nr)d" %  {"my_str": code_str, "my_nr": code_nr}
# <h1>super duper heading 42</h1>