使用 Python 读取 CSV 文件并将 CSV 文件的内容作为电子邮件内容发送

Reading a CSV file & sending the contents of the CSV file as a e-mail message content using Python

我有一个 CSV 文件并使用 python ,我需要读取该文件并将 CSV 的内容通过电子邮件发送,而不是作为附件。使用下面的脚本,它的工作原理。

#!/usr/bin/python

import csv
from tabulate import tabulate
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib

me = 'me@gmail.com'
password = 'passWord'
server = 'smtp.gmail.com:587'
you = 'you@gmail.com'

text = """
Hello Team,

Import Status :

{table}

Regards,

Arun"""

html = """
<html><body><p>Hello Team,</p>
<p>Import Status :</p>
{table}
<p>Regards,</p>
<p>Arun</p>
</body></html>
"""

with open('/home/files/daily_import/import.csv') as input_file:
    reader = csv.reader(input_file)
    data = list(reader)
    print data
text = text.format(table=tabulate(data, headers="firstrow", tablefmt="grid"))
print text
html = html.format(table=tabulate(data, headers="firstrow", tablefmt="html"))
print html

message = MIMEMultipart( "alternative", None, [MIMEText(text), MIMEText(html,'html')])
message['Subject'] = "Test Mail - Import Status"
message['From'] = me
message['To'] = you
server = smtplib.SMTP(server)
server.ehlo()
server.starttls()
server.login(me, password)
server.sendmail(me, you, message.as_string())
server.quit()

但是使用上面的脚本发送邮件的方式并不令人印象深刻。 CSV 值的第一行突出显示。

关于如何在不突出显示 CSV 内容的第一行并且在电子邮件的交互式表格列中发送电子邮件的任何建议,如下所示?

CSV 文件:

第一行突出显示,因为您的调用包括 headers="firstrow"。如果你完全删除那个命名参数,它应该会更好。

要在 table 单元格周围设置边框,您可能需要定义自己的 TableFormat,而不是依赖模块预定义的 html 格式。例如,这是 html 给你的:

myformat = TableFormat(lineabove=Line("<table>", "", "", ""),
                       linebelowheader=None,
                       linebetweenrows=None,
                       linebelow=Line("</table>", "", "", ""),
                       headerrow=partial(tabulate._html_row_with_attrs, "th"),
                       datarow=partial(tabulate._html_row_with_attrs, "td"),
                       padding=0, with_header_hide=None)

尝试对其进行更改,并传递 myformat 而不是 "html" 作为 tablefmt 参数的值。