首页 > 解决方案 > 使用 import smtplib 发送电子邮件时在 Python 中呈现 HTML

问题描述

我正在尝试使用 import smtplib 发送电子邮件。我希望它呈现 html 并通过电子邮件发送。不幸的是,它目前只是在电子邮件中发送 html 代码。任何建议将不胜感激。

我的代码如下:

import smtplib
import pandas as pd

DEFAULT_EMAIL_SERVER = "x"
TO = ["y@x.com"]
FROM = "z@x.com"
SUBJECT = "TEST"
table = pd.read_excel('abc.xlsm')

body = '<html><body>' + table.to_html() + '</body></html>'
        TEXT = body


message = """From: %s\r\nTo: %s\r\nSubject: %s\r\n\

            %s
            """ % (FROM, ", ".join(TO), SUBJECT, TEXT)


server = smtplib.SMTP(x)
server.sendmail(FROM, TO, message)
server.quit()

标签: pythonhtml

解决方案


您可以使用MIMETextfrom 对象email.mime.text创建一封电子邮件,将其内容指定为 HTML。

from email.mime.text import MIMEText

message = '<html><body> <b>hello world</b> </body></html>'

my_email = MIMEText(message, "html")
my_email["From"] = "me@email.com"
my_email["To"] = "you@other.org"
my_email["Subject"] = "Hello!"

server = smtplib.SMTP(my_server)
server.sendmail(from_email, to_email, my_email.as_string())

这将为您处理电子邮件标题的格式。.as_string()产生:

Content-Type: text/html; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
From: me@email.com
To: you@other.org
Subject: Hello!

<html><body> <b>hello world</b> </body></html>

推荐阅读