Python - HTML - Send HTML Table with CSS Style

戏子无情 提交于 2019-12-11 15:56:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!