将数据帧转换为HTML,然后在emai中显示

2024-05-19 17:08:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个脚本,它在数据帧中给我一个表。然后我把它转换成HTML并通过电子邮件发送

import pandas as pd
import datetime as dt
import smtplib
from IPython.display import HTML

def sendEmail():
    sender = 'DanielScript@domain.com'
    receivers = ['daniel@domain.com']
    message = """From: Daniel's Script <DanielScript@domain.com>
    To: Anyone who forgot
    Subject: New Employees Reminder

    Hi, here is a list of the people who will start working here soon: \n**{}** \n\nYou're welcome\nDaniel Beiin
    """.format(df)
    try:
        smtpObj = smtplib.SMTP('smtpserver')
        smtpObj.sendmail(sender , receivers, message)         
        print("Successfully sent email")
    except SMTPException:
        print ("Error: unable to send email")

df = pd.read_csv(r'testcsv.csv')
df = HTML(df.to_html())

sendEmail()

问题是,我在电子邮件中得到了**<IPython.core.display.HTML object>**。 我不知道该怎么表达。我不想将文件附加到电子邮件中,我希望当有人打开电子邮件时,该表显示为HTML格式

我不知道怎么做

谢谢:)


Tags: importcommessagedfdomainhtmlasipython
1条回答
网友
1楼 · 发布于 2024-05-19 17:08:21

嗨,丹尼尔,
只需在代码中尝试这种修改

    import pandas as pd
    import datetime as dt
    import smtplib
    import codecs
    from IPython.display import HTML

    def sendEmail():
    sender = 'DanielScript@domain.com'
    receivers = ['daniel@domain.com']
    message = """From: Daniel's Script <DanielScript@domain.com>
    To: Anyone who forgot
    Subject: New Employees Reminder

    Hi, here is a list of the people who will start working here soon: \n**{}** 
    \n\nYou're welcome\nDaniel Beiin
    """.format(df)
    try:
         smtpObj = smtplib.SMTP('smtpserver')
         smtpObj.sendmail(sender , receivers, message)         
         print("Successfully sent email")
    except SMTPException:
         print ("Error: unable to send email")

    df = pd.read_csv(r'testcsv.csv')
    df.to_html('filename.html')
    f = codecs.open("filename.html",'r')
    df = HTML(f.read()) 

    sendEmail()

相关问题 更多 >