我正在 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)
关于python - 如何在html中添加动态内容以在Python中发送邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56256328/