使用 Python 发送 HTML 电子邮件

pythonserver side programmingprogramming更新于 2025/5/7 3:24:17

当您使用 Python 发送文本消息时,所有内容都被视为简单文本。即使您在文本消息中包含 HTML 标记,它也会显示为简单文本,并且 HTML 标记不会根据 HTML 语法进行格式化。但 Python 提供了将 HTML 消息作为实际 HTML 消息发送的选项。

发送电子邮件时,您可以指定 Mime 版本、内容类型和字符集来发送 HTML 电子邮件。

示例

以下是将 HTML 内容作为电子邮件发送的示例。试一次 −

#!/usr/bin/python
import smtplib
message = """From: From Person <from@fromdomain.com>
To: To Person <to@todomain.com>
MIME-Version: 1.0
Content-type: text/html
Subject: SMTP HTML e-mail test
This is an e-mail message to be sent in HTML format
<b>This is HTML message.</b>
<h1>This is headline.</h1>
"""
try:
   smtpObj = smtplib.SMTP('localhost')
   smtpObj.sendmail(sender, receivers, message)
   print "Successfully sent email"
except SMTPException:
   print "Error: unable to send email"

相关文章


有用资源