使用导入smtplib发送电子邮件时在Python中呈现HTML
我正在尝试使用导入smtplib发送电子邮件。我想让它呈现html并通过电子邮件发送。不幸的是,它目前只在电子邮件中发送html代码。任何建议都将不胜感激 我的代码如下:使用导入smtplib发送电子邮件时在Python中呈现HTML,python,html,Python,Html,我正在尝试使用导入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 = '<htm
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()
导入smtplib
作为pd进口熊猫
默认电子邮件服务器=“x”
TO=[”y@x.com"]
FROM=”z@x.com"
主题=“测试”
table=pd.read\u excel('abc.xlsm')
body=''+table.to_html()+''
文本=正文
message=“”发件人:%s\r\n收件人:%s\r\n对象:%s\r\n\
%
“%”(FROM,“,”。连接(TO)、主题、文本)
服务器=smtplib.SMTP(x)
server.sendmail(发件人、收件人、邮件)
server.quit()
您可以使用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())
我现在可以使用它来获得html格式的表格,但是我无法获得from-to和subject-to工作。你确定应该是server.sendmail(从_email,到_email,我的_email.as _string())?@Imccann,我在发布答案后做了一些编辑。你看到那些了吗?啊,是的,现在它开始工作了。为什么我需要添加内容类型:text/html;charset=“us ascii”到您的消息字符串:
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>