6
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 = 'me@email.com'
    you = 'you@email.com'
    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

user3613102
  • 63
  • 1
  • 1
  • 3
  • Do you want to send it as text in the body of the message, or as an attachment (text, csv, etc.)? – Evan Jan 10 '18 at 22:50
  • I would like to embed it in the body of the email message. – user3613102 Jan 11 '18 at 03:11
  • You can convert a df to an HTML table - https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_html.html. 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.) – Evan Jan 11 '18 at 03:31

2 Answers2

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.

Evan
  • 2,121
  • 14
  • 27
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.

scopchanov
  • 7,966
  • 10
  • 40
  • 68
Cho
  • 163
  • 3
  • 13
  • 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? – user3613102 Jan 11 '18 at 03:10
  • 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. – Cho Jan 11 '18 at 03:21
  • This should be commented and not posted as an answer! – tavalendo Oct 02 '18 at 14:40