我正在尝试使用 smtplib 发送 HTML 电子邮件。但我需要 HTML 内容有一个使用字典中的值填充的表。我确实看过Python网站上的示例。但它没有解释如何在 HTML 中嵌入 Python 代码。任何解决方案/建议?
我也看了这个问题。我可以这样格式化吗?
.format(dict_name)
从您的链接:
以下是如何使用替代纯文本版本创建 HTML 消息的示例:2
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# me == my email address
# you == recipient's email address
me = "my@email.com"
you = "your@email.com"
# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = "Link"
msg['From'] = me
msg['To'] = you
# Create the body of the message (a plain-text and an HTML version).
text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org"
html = """\
<html>
<head></head>
<body>
<p>Hi!<br>
How are you?<br>
Here is the <a href="http://www.python.org">link</a> you wanted.
</p>
</body>
</html>
"""
以及它的发送部分:
# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
msg.attach(part2)
# Send the message via local SMTP server.
s = smtplib.SMTP('localhost')
# sendmail function takes 3 arguments: sender's address, recipient's address
# and message to send - here it is sent as one string.
s.sendmail(me, you, msg.as_string())
s.quit()
2022 年编辑:对于新人,请参考 python 最新的稳定版本文档。
您需要的是模板引擎。也就是说,您需要一个python 库来读取用HTML 和代码编写的文件,解释编写在HTML 文件中的代码(例如,从字典中检索值的代码),然后为您生成一个HTML 文件。