我在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标记中包含一些动态内容。
发布于 2019-05-22 12:14:13
因为这是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)发布于 2019-05-22 12:13:17
要包含动态内容,只需从数据源获取数据并根据需要将它们连接到邮件正文。
https://stackoverflow.com/questions/56256328
复制相似问题