【问题标题】:Give color to the text of HTML table email body based on disk usage condition using Python使用 Python 根据磁盘使用情况为 HTML 表格电子邮件正文的文本着色
【发布时间】: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


    【解决方案1】:

    从 csv 读取数据后循环遍历数据,如果磁盘使用率大于 80,则将其更改为 &lt;p style='color:red'&gt;Value&lt;/p&gt;

    然后在表格中将tablefmt 参数更改为"unsafehtml"

    这应该会输出包含您自己的样式的 html。

    下面的代码以红色输出“月亮”来给你一个概念证明:

    from tabulate import tabulate
    table = [["Sun",696000,1989100000],["Earth",6371,5973.6],
             ["<p style='color:red'>Moon</p>",1737,73.5], 
             ["Mars",3390,641.85]]
    print(tabulate(table, tablefmt='unsafehtml'))
    

    【讨论】:

    • 嗨@machazthegamer,感谢您的回复。我按照你的建议做了,看起来它按预期工作。但是,我不再得到标题了。这是排除它。我会更新帖子。我不确定我做错了什么。再次感谢您的帮助。
    • 我通过添加循环更新了帖子。我得到的文字是红色的。被排除的部分是第一行(服务器、总大小 GB、总数据和使用百分比)。它改为将第二行(A 行)作为标题添加。
    • 值得一提的是,我还将 reader = csv.reader(input_file) 更改为 reader = DictReader(input_file),因为在使用 csv.reader(input_file) 时出现以下错误:row['Usage in %'] = int(row['Usage in %']) TypeError: list indices must be integers or slices, not str
    • 针对当前问题发布一个不同的问题,这越来越令人困惑。@chiko
    猜你喜欢
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-19
    相关资源
    最近更新 更多