问题
I'm trying to send a email with a table as a body with some CSS configurations. For that I have the following code:
import csv
from tabulate import tabulate
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
text = """Hello, Friend.Here is your data:{table}Regards,Me"""
html = """"\
<html>
<head>
<style type="text/css">
.tg {border-collapse:collapse;border-spacing:0;}
.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:black;}
.tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:black;}
.tg .tg-0lax{text-align:left;vertical-align:top}
</style>
</head>
<body>
<table class="tg">
<tr>
<th class="tg-0lax">Environment</th>
<th class="tg-0lax">Date</th>
<th class="tg-0lax">Error_Type</th>
<th class="tg-0lax">Error_Object</th>
<th class="tg-0lax">Description</th>
</tr>
<tr>
<td class="tg-0lax">PROD</td>
<td class="tg-0lax">15/03/2019</td>
<td class="tg-0lax">ERROR</td>
<td class="tg-0lax">F_ORDER_DETAIL</td>
<td class="tg-0lax">More columns than expected</td>
</tr>
</table>
</body>
</html>"""
with open('file.csv') as input_file:
reader = csv.reader(input_file)
data = list(reader)
However I'm facing with a problem when I add the CSS style:
html = html.format(table=tabulate(data, headers="firstrow", tablefmt="html"))
KeyError: 'border-collapse'
How can I add that CSS Style on my HTML Table?
Many thanks!!!
回答1:
You need to use double curly-braces in oder to avoid string format interpolation.
For instance:
<style type="text/css">
.tg {{border-collapse:collapse;border-spacing:0;}}
.tg td{{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:black;}}
.tg th{{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:black;}}
.tg .tg-0lax{{text-align:left;vertical-align:top}}
</style>
来源:https://stackoverflow.com/questions/55211547/python-html-send-html-table-with-css-style