gpt4 book ai didi

python - Python 中的 HTML 电子邮件

转载 作者:太空宇宙 更新时间:2023-11-04 10:48:15 24 4
gpt4 key购买 nike

我正在尝试使用 smtplib 发送 HTML 电子邮件。但我需要 HTML 内容有一个使用字典中的值填充的表格。我确实看过 Python 上的例子网站。但它没有解释如何在 HTML 中嵌入 Python 代码。有什么解决方案/建议吗?

我也看了this问题。我可以这样格式化吗?

.format(dict_name)

最佳答案

来自您的 link :

Here’s an example of how to create an HTML message with an alternativeplain text version: 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()

Edit 2022: 新手请指教python最新稳定版docs .

关于python - Python 中的 HTML 电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15802238/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com