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

Dav*_*ani 10 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 exclusive content:<br>
       <br><br><h1><% print code %></h1><br>
       <img src="http://domain.com/footer.jpg">
    </p>
  </body>
</html>
"""
Run Code Online (Sandbox Code Playgroud)

Eri*_*ric 29

用途"formatstring".format:

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)
Run Code Online (Sandbox Code Playgroud)

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

.format(**locals())
Run Code Online (Sandbox Code Playgroud)


ovg*_*vin 10

另一种方法是使用模板:

>>> 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>
Run Code Online (Sandbox Code Playgroud)

请注意,我用的safe_substitute,不是substitute,因为如果有一个占位符,这是不提供的字典,substitute将提高ValueError: Invalid placeholder in string.同样的问题是string formatting.