如何在 html 中添加动态内容以在 Python 中发送邮件

How to add a dynamic content into html for sending mail in Python

我正在使用 python 中的 'smtplib' 发送包含 html 内容的邮件,我想向 html.

添加动态内容
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

message = MIMEMultipart("alternative")
message["Subject"] = "Error Notification"
message["From"] = sender
message["To"] = sender

# Create the plain-text and HTML version of your message
html = """\
    <html>
      <body>
        <p>Hi,<br>
           <span>Something went wrong !</span><br>
        </p>
      </body>
    </html>
    """
part1 = MIMEText(html, "html")

# Add HTML/plain-text parts to MIMEMultipart message
message.attach(part1)
try:
    smtpObj = smtplib.SMTP('localhost')
    smtpObj.sendmail(sender, receivers, message.as_string())
    print "Successfully sent email"
except smtplib.SMTPException:
    print "Error: unable to send email"

除上述内容外html我还需要在 body 标签中包含一些动态内容

要包含动态内容,只需从您的数据源获取数据并根据需要将它们连接到邮件正文中。

因为这是 Python 你可以用字符串做一些非常棒的事情。只需将 html 的某些区域命名为 特殊 名称,然后使用 replace 方法将它们替换为您想要的任何值。

html = """\
    <html>
      <body>
        <p>Hi, $(name)<br>
           <span> $(error) </span><br>
        </p>
      </body>
    </html>
"""

html = html.replace("$(name)", "John")
html = html.replace("$(error)", "Something went wrong!")

print(html)