python - 使用 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()
解决方案
您可以使用MIMEText
from 对象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>
推荐阅读
- sql - 将 "yyyy-MM-dd'T'HH:mm:ss.SSSXXX" 和 "yyyy-MM-dd'T'HH:mm:ss.SSSSSSSX" 转换为 SQL 表的一个常见时间戳
- python - Codechef:小菜一碟(问题代码:LCH15JAB)
- r - 基于 r 中的两列的 delim 分隔行
- rust - Serde 的反序列化方法是如何推断类型的?
- javascript - 尝试使用 chart.js 将三个不同的条形图合并为一个
- r - 在不使用 Hmisc 的情况下在 R 中外推
- android - 导航 popUpTo 未按预期工作
- javascript - 使用 HtmlUnit 执行 javascript (Ajax) 时出错
- pine-script - 将来如何在 pine 脚本中绘制线条?
- hive - 无法通过 SAS 连接到 Hive