【问题标题】:Pass value to html inside string in python将值传递给python中字符串内的html
【发布时间】:2020-09-26 00:31:08
【问题描述】:

我有以下代码:

def smtp_mailer(name,email):
    html = """\
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
 <style type="text/css">
.h1, .p, .bodycopy {color: #153643; font-family: sans-serif;}
  .h1 {font-size: 33px; line-height: 38px; font-weight: bold;}
</style>
</head>
<body>

<h1>This is a {name}</h1>
<p>This is a {email).</p>

</body>
</html> 
"""
    part2 = MIMEText(html, 'html')
    msg.attach(part2) 

当我发送 SMTP 邮件时,我无法在名称的 h1 标记和电子邮件的 p 标记处传递 HTML 内的值。请帮帮我。 谢谢。

【问题讨论】:

  • 尝试使用html.format(name=...., email=....)替换值
  • 你可能忘记了开头的 f 来做插值 f”””text {name} “””
  • 但是我的 HTML 中有这些内联 CSS,它也要求格式 ''' .header { width: 100%;背景颜色:#3B5998;高度:35px;边距顶部:0; } .style1 { 边距右:38px; } .style2 { 宽度:100%;背景颜色:#3B5998;高度:35px; } ''' @alaniwi
  • @anuragkumaranu 好的,我现在明白问题所在了。请看我的回答。

标签: python html python-3.x string smtp


【解决方案1】:

在最初的 cmets 之后,似乎被问到的主要问题是字符串包含一些大括号(即 {} 字符),这些大括号旨在作为 @ 的一部分作为文字保留在字符串中987654322@ 元素,还有那些打算作为格式说明符的一部分被替换的元素。

鉴于此字符串是您自己的代码,您可以将其修改为预期的内容,而不是外部提供的值,您必须为这种不一致找到不可避免的混乱解决方法,因此适当的解决方案是更改{} 旨在成为 {{}} 的文字,因此在调用 format 方法后,它们将作为单括号输出。

完成此操作后(还纠正了{email)末尾的错误字符),可以应用format方法:

例如,

html = """\
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
 <style type="text/css">
.h1, .p, .bodycopy {{color: #153643; font-family: sans-serif;}}
  .h1 {{font-size: 33px; line-height: 38px; font-weight: bold;}}
</style>
</head>
<body>

<h1>This is a {name}</h1>
<p>This is a {email}.</p>

</body>
</html> 
""".format(name="John", email="test@example.com")

print(html)

给予:

...
.h1, .p, .bodycopy {color: #153643; font-family: sans-serif;}
  .h1 {font-size: 33px; line-height: 38px; font-weight: bold;}
...
<h1>This is a John</h1>
<p>This is a test@example.com.</p>
...

正如其他人提到的(在 Python 3 中),您也可以使用 f 字符串表示法,而不是显式调用 format 方法,前提是您已经在名为 name 和 @ 的变量中替换了值987654335@。在任何情况下,您仍然需要在格式化之前将文字大括号加倍。

【讨论】:

    【解决方案2】:

    你可以像这样使用string interpolation

    def smtp_mailer(name,email):
        html = f"""\
    <!DOCTYPE html>
    <html>
    <head>
    <title>Page Title</title>
    </head>
    <body>
    
    <h1>This is a {name}</h1>
    <p>This is a {email}.</p>
    
    </body>
    </html> 
    """
        print(html)
    
    smtp_mailer("test", "test@test.test")
    

    返回

    <!DOCTYPE html>
    <html>
    <head>
    <title>Page Title</title>
    </head>
    <body>
    
    <h1>This is a test</h1>
    <p>This is a test@test.test.</p>
    
    </body>
    </html>
    

    【讨论】:

    • 但是我的 HTML 中有这些内联 CSS,它也要求格式 ''' .header { width: 100%;背景颜色:#3B5998;高度:35px;边距顶部:0; } .style1 { 边距右:38px; } .style2 { 宽度:100%;背景颜色:#3B5998;高度:35px; } '''
    猜你喜欢
    • 2014-01-21
    • 1970-01-01
    • 2020-05-13
    • 1970-01-01
    • 1970-01-01
    • 2017-09-28
    • 2013-10-21
    • 1970-01-01
    • 2021-04-27
    相关资源
    最近更新 更多