如何以表格格式将pandas DataFrame发送到Python中



我正在尝试通过邮件发送pandas dataframe。我尝试过,但我无法获得它。我的代码是

代码

import pandas as pd 
import json
import requests
from requests.auth import HTTPBasicAuth
import datetime
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import pdb
ticket_details=pd.DataFrame(list_values,
columns['incident',"short_description","priority","assignment_group"])

#converting a datframe into html table
df=ticket_details.to_html()
send ="xxx@xxx.com"
reciever="xxx@xxx.com"   
subject="incident details "
msg = MIMEMultipart('alternative')
msg['From'] = send
msg['To'] = reciever 
msg['Subject'] =subject      

html_body = str(df)
messagePlain = 'Look at the incident details'
msg.attach(MIMEText(messagePlain, 'plain'))
msg.attach(MIMEText(html_body, 'html')                           
server = smtplib.SMTP("xxx.com")
server.sendmail(send, reciever, msg.as_string())
server.quit()

首先,请不要在您的问题中共享个人信息作为邮件地址。那么主要问题是您将df转换为str而不是html对象。

# declare mixed MIME
msg = MIMEMultipart('mixed')
# convert df to html
table = df.to_html()
# attach to your mail
msg.attach(MIMEText(table, 'html')

您的HTML仅包含一个表,并且不格式为完整的HTML页面。但是它用雷鸟读得正确。无论如何,我会在表格前后添加最低限度,以使其看起来像一个可接受的HTML页面:

...
prolog='''<html>
<head><title>Incident details</title></head>
<body>
'''
epilog = '</body></html>'
html_body = prolog + df + epilog
...

这不是一个很好的HTML,但至少它具有html Bloc,一个包含标题和身体的标题。这样,即使在宽容的邮件读取器上也应该可以读取。

最新更新