I am sending out an html table in an email body using python. The html table consists of disk usage and I need to convert the text color in red when disk usage is above 80 percent . I have tried so far Give color to the text of HTML table body based on condition. However, this uses excel and does not add the borders which in my case i want to keep.
This is the code I'm using that works to get the email without colouring the text:
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()
This is the output I get in the email
Expected output
Any help is greatly appreciated.
loop through your data after reading it from the csv and change the value of disk usage to <p style='color:red'>Value</p>
if its greater than 80
Then in tabulate change the tablefmt
argument to "unsafehtml"
.
This should output html that incorporates your own styles.
The code below outputs "moon" in red color to give you a proof of concept:
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'))