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

Asw*_* MA 4 html python email smtplib

我正在 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"
Run Code Online (Sandbox Code Playgroud)

除了上面的 html 之外,我还需要在 body 标记中包含一些动态内容

bab*_*ris 6

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

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