如何在用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>
"""
另一种方法是使用Templates:
注意,我使用的是} 。
safe_substitute
,而不是substitute
,就像字典中没有提供占位符一样,substitute
将引发ValueError: Invalid placeholder in string
。同样的问题是^{使用^{} :
如果发现自己替换了大量变量,可以使用
使用pythons字符串操作: http://docs.python.org/2/library/stdtypes.html#string-formatting
通常,%运算符用于将变量放入字符串,%i表示整数,%s表示字符串,%f表示浮点数, 注意:还有另一种格式化类型(.format),在上面的链接中也有描述,它允许您传入一个dict或list,稍微比我在下面显示的要优雅一些,这可能是您在长期中应该追求的,因为如果您有100个变量要放入一个字符串中,%运算符会变得混乱,尽管使用dicts(我的最后一个例子)有点否定了这一点。
这是非常基本的,而且只适用于原始类型,如果您想存储dict、list和可能的对象,我建议您使用cobvert将它们转换为jsonhttp://docs.python.org/2/library/json.html和https://stackoverflow.com/questions/4759634/python-json-tutorial是很好的灵感来源
希望这有帮助
相关问题 更多 >
编程相关推荐