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

2024-09-27 23:23:03 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在用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>
"""

Tags: textbryoufor电子邮件htmlcodebody
3条回答

另一种方法是使用Templates

>>> 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>

注意,我使用的是safe_substitute,而不是substitute,就像字典中没有提供占位符一样,substitute将引发ValueError: Invalid placeholder in string。同样的问题是^{}

使用^{}

code = "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>{code}</h1><br>
       <img src="http://domain.com/footer.jpg">
    </p>
  </body>
</html>
""".format(code=code)

如果发现自己替换了大量变量,可以使用

.format(**locals())

使用pythons字符串操作: http://docs.python.org/2/library/stdtypes.html#string-formatting

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

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>

这是非常基本的,而且只适用于原始类型,如果您想存储dict、list和可能的对象,我建议您使用cobvert将它们转换为jsonhttp://docs.python.org/2/library/json.htmlhttps://stackoverflow.com/questions/4759634/python-json-tutorial是很好的灵感来源

希望这有帮助

相关问题 更多 >

    热门问题