如何在 Pandas 中将 Pandas DataFrame 作为附件发送

How to send Pandas DataFrame as an attachment in Pandas

我在 SO 和 Google 周围搜索了很多但没有得到我的答案因此最终想在这里问。

我有一个 csv 文件,我正在将其转换为 html 框架,它工作正常,我可以通过 Outlook 作为电子邮件将其作为 html 帧发送。

正在寻找我们是否可以直接将 df.to_html 作为电子邮件的附件发送?

代码如下:

这可以很好地通过 Outlook 作为带有 html 框架的电子邮件发送。

import pandas as pd
import numpy as np
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText


df = pd.read_csv('graph.csv', names=['Volume_Path', 'Last Acced', 'Year', 'Month', 'Days', '1-24 hrs', '1 hour', '15 mins', 'future'])
df['Volume_Path'] = df['Volume_Path'].str.replace('\t', '')
df = df.replace(np.nan, '')

# Create message container - the correct MIME type is multipart/alternative.
##############################################################################
msg =  "<u><b> Checklist</b></u><br />"
msg = msg + "<br />"
msg += df.to_html(escape=False)
def mail(msg,recipients,key):
        try:
            s = smtplib.SMTP('mailserver.xyz.com')
            msg1 = MIMEText(msg, 'html')
            sender = 'tina@xyz.com'
            msg1['From'] = sender
            msg1['To'] = ", ".join(recipients)
            msg1['Cc'] =  'mauj@xyz.com'
            msg1['Subject'] = "Mauj Test"
            s.sendmail(sender, recipients, msg1.as_string())
            print(f"Mail Sent to {sender}")
        except Exception as error:
            print(f"Mail Failed - {error}")
recipients = ['joe@xyz.com']
key=""
mail(msg,recipients,key)

如果您不想将 pandas.DataFrame 保存为驱动器上的 html 文件,而是直接附加它,我会使用 MIMEBase 并将其附加到您的消息中

这里 html_objectdf.to_html() 对象。

import smtplib
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase

def mail(body,recipients,key, html_object):
    s = smtplib.SMTP('server.com')
    msg = MIMEMultipart()
    msg.attach(MIMEText(body))
    part = MIMEBase('text', "html")
    part.set_payload(html_object)
    part.add_header('Content-Disposition', 'attachment; filename="tbl.html"')
    msg.attach(part)
    sender = 'me@place.com'
    msg['From'] = sender
    msg['To'] = ", ".join(recipients)
    msg['Subject'] = "Html Test"
    s.sendmail(sender, recipients, msg.as_string())
    print(f"Mail Sent to {sender}")

例如

mail('See attached for html file.',["me@place.com"],key="", html_object=df.to_html())