将数据框作为表格发送到电子邮件正文python中?

时间:2018-02-25 13:13:38

标签: python pandas dataframe

我有一个csv文件,我需要在电子邮件正文中作为数据框发送。

但是在我的电子邮件输出中,我无法看到csv文件的列,而只是将csv文件的第一行作为列。

**这是我的代码:**

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

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

text = """
Hello, Friend.

Here is your data:

{table}

Regards,

Me"""

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

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

data = pd.read_csv("MySampleFile.csv")
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'] = "First Attempt"
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()

1 个答案:

答案 0 :(得分:2)

似乎我所要做的就是将我的csv文件中的各个列提取到一个单独的列表中,该列表可以传递到tabulate方法的headers参数中。

以下是完整的解决方案

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

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

text = """
Hello, Friend.

Here is your data:

{table}

Regards,

Me"""

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

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

df = pd.read_csv("MySampleFile.csv")
col_list = list(df.columns.values)
data = df
# above line took every col inside csv as list
text = text.format(table=tabulate(data, headers=col_list, tablefmt="grid"))
html = html.format(table=tabulate(data, headers=col_list, tablefmt="html"))

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

message['Subject'] = "First Attempt"
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()