【问题标题】:Add borders of table sent by email via Python通过 Python 添加通过电子邮件发送的表格边框
【发布时间】:2018-04-19 13:40:43
【问题描述】:

目前我使用这个解决方案 Send table as an email body (not attachment ) in Python 通过 Python 在电子邮件中发送表格:

import smtplib
from smtplib import SMTPException
import csv
from tabulate import tabulate

text = """
Hello, Friend.

Here is your data:

{table}

Regards,

Me"""

html = """
<html><body><p>Hello, Friend.</p>
<p>Here is your data:</p>
{table}
<p>Regards,</p>
<p>Me</p>
</body></html>
"""

with open('result.csv') as input_file:
    reader = csv.reader(input_file)
    data = list(reader)

text = text.format(table=tabulate(data, headers="firstrow", tablefmt="grid"))
html = html.format(table=tabulate(data, headers="firstrow", tablefmt="html"))

message = MIMEMultipart(
    "alternative", None, [MIMEText(text), MIMEText(html,'html')])

message['Subject'] = "Your data"
message['From'] = 'a@abc.com'
message['To'] = 'b@abc.com'

sender = "a@abc.com"
receivers = ['b@abc.com']

try:
    smtp_obj = smtplib.SMTP('mail.abc.com')
    smtp_obj.sendmail(sender, receivers, message.as_string())         
    print ("Successfully sent email")
except SMTPException:
    print ("Error: unable to send email")

数据从 csv 文件加载。但我需要在表格中添加边框,使其看起来像 pandas DataFrame。

【问题讨论】:

    标签: python html email smtplib


    【解决方案1】:

    将样式添加到原始 html 脚本将起作用。

    html = """
    <html>
    <head>
    <style> 
      table, th, td {{ border: 1px solid black; border-collapse: collapse; }}
      th, td {{ padding: 5px; }}
    </style>
    </head>
    <body><p>Hello, Friend.</p>
    <p>Here is your data:</p>
    {table}
    <p>Regards,</p>
    <p>Me</p>
    </body></html>
    """
    

    【讨论】:

      【解决方案2】:

      这里是创建带边框的表格的完整解决方案。

      table = '' 
      with open('result.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>' 
              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: white;
       }
      
      </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'] = 'a@abc.com'
      message['To'] = 'b@abc.com'
      
      sender = "a@abc.com"
      receivers = ['b@abc.com']
      
      try:
          smtp_obj = smtplib.SMTP('mail.abc.com')
          smtp_obj.sendmail(sender, receivers, message.as_string())         
          print ("Successfully sent email")
      except SMTPException:
          print ("Error: unable to send email")
      

      【讨论】:

        【解决方案3】:

        试试这个

        email_content = """
        <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: #AAD373;
            empty-cells:hide;
          Border:5px solid red;
         }
         td.cell{
            background-color: white;
        }
        </style>
        </head>
        <body>
        <table style="border: blue 1px solid;">
        <tr><td class="cell">Cell 1.1</td><td class="cell">Cell 1.2</td></tr>
        <tr><td class="cell">Cell 2.1</td><td class="cell"></td></tr>
         </table>
        

        【讨论】:

        • 谢谢!但是猫我以某种方式从 csv 加载表格,而不是明确地写入每个单元格的内容?
        • 没有得到!!你想从 CSV 添加内容值?表格单元格中的平均值??如果可以的话,
        • 从 CSV 读取数据使用 my_data = genfromtxt('my_file.csv', delimiter=',')
        • 如果你认为numpy.genfromtxt,它是行不通的。虽然,我不知道您到底想用该代码替换哪个部分。
        • import csv table = '' with open(csv_path, encoding="utf8") as csvFile: reader = csv.DictReader(csvFile, delimiter=',') table = '{} '.format(''.join(['{}'.format(header) for header in reader.fieldnames])) for row in reader: table_row = ' ' for fn in reader.fieldnames: table_row += '{}'.format(row[fn]) table_row += '' table += table_row
        猜你喜欢
        • 2012-02-07
        • 2013-01-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-18
        • 2011-09-14
        • 2015-10-26
        相关资源
        最近更新 更多