7
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

3
  • Do you want to send it as text in the body of the message, or as an attachment (text, csv, etc.)? Commented Jan 10, 2018 at 22:50
  • I would like to embed it in the body of the email message. Commented Jan 11, 2018 at 3:11
  • You can convert a df to an HTML table - pandas.pydata.org/pandas-docs/stable/generated/…. I've never used this feature; I'm not sure if you have to export and attach an html file, or if you can embed it inline. (And, of course, your email has to support HTML.) Commented Jan 11, 2018 at 3:31

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

3 Comments

Yes, that is the spirit of my question... is it possible to send a dataframe in an email or is my only option to send a .csv in html or as an attachment?
The way to send a dataframe from what I know is to send it to csv. I do not know how to send it to html.
This should be commented and not posted as an answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.