【发布时间】:2022-01-12 05:44:14
【问题描述】:
我正在使用 python 在电子邮件正文中发送一个 html 表格。 html 表包含磁盘使用情况,当磁盘使用率高于 80% 时,我需要将文本颜色转换为红色。到目前为止我已经尝试过Give color to the text of HTML table body based on condition。但是,这使用 excel 并且不添加在我的情况下我想要保留的边框。
这是我正在使用的代码,用于在不着色文本的情况下获取电子邮件:
me = 'noreply@automationtest.com'
server = 'some smtp server'
you = ‘email@someautomation.com'
text = """
{table}
"""
html = """
<html>
<head>
<style>
table, th, td {{ border: 1px solid black; border-collapse: collapse; }}
th, td {{ padding: 5px; }}
</style>
</head>
<body><p style="font-family:verdana">Hi,</p>
<p style="font-family:verdana">sometext</p>
{table}
<p style="font-family:verdana">sometext</p>
<p style="font-family:verdana">Regards</p>
<p style="font-family:verdana">someme</p>
</body></html>
"""
with open('files/file.csv') as input_file:
reader = DictReader(input_file)
data = list(reader)
for row in data:
row['Usage in %'] = pd.to_numeric(row['Usage in %'])
if row['Usage in %'] >= 80:
row['Usage in %'] = "<p style='color:red'>%s</p>"%row['Usage in %']
text = text.format(table=tabulate(data, headers="firstrow", tablefmt="grid"))
html = html.format(table=tabulate(data, headers="firstrow", tablefmt="unsafehtml"))
message = MIMEMultipart("alternative", None, [MIMEText(text), MIMEText(html,'html')])
print(html)
message['From'] = me
message['To'] = you
server = smtplib.SMTP(server)
server.ehlo()
server.starttls()
server.login(me, password)
server.sendmail(me, you, message.as_string())
server.quit()
非常感谢任何帮助。
【问题讨论】:
标签: html python-3.x pandas email tabulate