user3613102
user3613102

Reputation: 73

Python3 How do I send Pandas Dataframe in an email

def call_panda():
    filename = 'C:\\file.csv'
    cols_to_use = ['col1', 'col2', 'col3', 'col4']
    df = pd.read_csv(filename, nrows= 5,usecols=cols_to_use,index_col='col1')               
    # Send email
    me = '[email protected]'
    you = '[email protected]'
    textfile = df
    with open(textfile, 'rb') as fp:
        msg = MIMEText(fp.read())
        msg['Subject'] = 'Contents of file'
        msg['From'] = me
        msg['To'] = you
        s = smtplib.SMTP('mailhost.acme.net')
        s.sendmail(me, [you], msg.as_string())
        s.quit()

Error Message is with open(textfile, 'rb') as fp: TypeError: expected str, bytes or os.PathLike object, not DataFrame

Upvotes: 7

Views: 18048

Answers (2)

Cho
Cho

Reputation: 163

In the above code, df defined as textfile is data that exists in current memory. Therefore, the with open command can not be executed. with open is a function that loads any file stored on the hard disk into memory.

Upvotes: 0

Evan
Evan

Reputation: 2151

Pandas has a df.to_html feature.

https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_html.html

Copying Chris Albon: https://chrisalbon.com/python/data_wrangling/pandas_join_merge_dataframe/

import pandas as pd

raw_data = {
        'subject_id': ['1', '2', '3', '4', '5'],
        'first_name': ['Alex', 'Amy', 'Allen', 'Alice', 'Ayoung'], 
        'last_name': ['Anderson', 'Ackerman', 'Ali', 'Aoni', 'Atiches']}
df_a = pd.DataFrame(raw_data, columns = ['subject_id', 'first_name', 'last_name'])
df_a.to_html('df.html')

From here, check this thread for email tips: Sending HTML email using Python

It looks like you'll need to attach the HTML file; I'm not sure if it'll display online, and I don't have a mail server with which I can check.

Upvotes: 5

Related Questions