3

我正在尝试发送一封带有表格作为正文的电子邮件,其中包含一些 CSS 配置。为此,我有以下代码:

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">DEV</td>
      <td class="tg-0lax">15/03/2019</td>
      <td class="tg-0lax">ERROR</td>
      <td class="tg-0lax">Table</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)

但是,当我添加 CSS 样式时,我遇到了一个问题:

html = html.format(table=tabulate(data, headers="firstrow", tablefmt="html"))
KeyError: 'border-collapse'

如何在我的 HTML 表格中添加该 CSS 样式?

非常感谢!!!

4

1 回答 1

9

您需要在 oder 中使用双花括号以避免字符串格式插值。

例如:

  <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>
于 2019-03-17T20:36:13.417 回答