我需要读取CSV输入文件并在电子邮件正文中发送CSV内容html表格式。 CSV包含5列,所有5列的数据均为“成功”或“失败”。 需要突出显示绿色的“成功”列和红色的“失败”列。我能够发送html表格格式的电子邮件。但是无法基于CSV值进行颜色编码。 请执行Needfull。
import smtplib
from smtplib import SMTPException
import csv
from tabulate import tabulate
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
table = ''
with open('alert.csv') as csvFile:
reader = csv.DictReader(csvFile, delimiter=',')
table = '<tr>{}</tr>'.format(''.join(['<td class="cell">{}</td>'.format(header) for header in reader.fieldnames]))
for row in reader:
table_row = '<tr>'
# #print(table)
for fn in reader.fieldnames:
table_row += '<td class="cell">{}</td>'.format(row[fn])
table_row += '</tr>'
table += table_row
html = """
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>html title</title>
<style type="text/css" media="screen">
table{
background-color: #000000;
empty-cells:hide;
Border:5px solid red;
}
td.cell{
background-color: blue;
}
</style>
</head>
<html><body><p>Hi!</p>
<p>Here is your data.</p>
<table style="border: black 0.5px;">
%s
</table>
<p>Regards,</p>
<p>Python 3.5</p>
</body></html>""" % table
message = MIMEMultipart(
"alternative", None, [MIMEText(html,'html')])
message['Subject'] = "Some stats via mail"
message['From'] = 'donotreply@xxx.com'
message['To'] = 'pooja.kamat@xxx.com'
sender = "donotreply@xxx.com"
receivers = ['abc.def@xxx.com']
答案 0 :(得分:0)
最简单的方法是创建两个类,一个用于成功,一个用于失败,然后简单地将它们分配给单元格。由于已经填充了背景颜色,因此您不清楚“突出显示”的含义是什么,但是您应该能够轻松地进行调整。
在“样式”元素中
/* Place after td.cell */
td.success {
background-color: green; /* Highlight success as green */
}
td.failure {
background-color: red; /* Highlight failure as red */
}
施工中
for fn in reader.fieldnames:
## row[fn] is expected to equal "success" or "failure"
## These are style classes (success=green, failure=red)
## If row[fn] is neither, it will be highlighted blue
table_row += '<td class="{0} cell">{0}</td>'.format(row[fn])
## This should be de-indented (might have been copying error)
table_row += '</tr>'
table += table_row