0

I'm trying to send a pandas dataframe as a CSV attachment in an email.

My code is not throwing an error. However, the resulting email contains an empty attachment.

Am I missing something?

I am using mailgun api for email and have tried the following code:

from io import StringIO
import pandas as pd

def send_simple_message(a):
    mgurl = 'https://api.mailgun.net/v3/{}/messages'.format('sandboxf04fcce3c4dc46c987c92f3a967e7f9c.mailgun.org')
    auth = ('api', '3701ba6d2b1ad202e76a4322a80c7600-87cdd773-683e02b1')
    files=[("attachment", ("test.csv", a))]
    data = {
        'from': 'Mailgun User <mailgun@{}>'.format('sandboxf04fcce3c4dc46c654c92f3a765e7f9c.mailgun.org'),
        'to': 'user@gmail.com',
        'subject': 'Simple Mailgun Example',
        'text': 'Find attached your CSV'
    }

    response = requests.post(mgurl, auth=auth, data=data, files=files)
    response.raise_for_status()


a = StringI0()

df=pd.DataFrame({'a':[1,2,3],'b':[3,2,1]})

df.to_csv(a)

send_simple_message(a)

pablowilks2
  • 299
  • 5
  • 15
  • Why don't you directly send a string? Something `send_simple_message(df.to_csv())` should work. – IanS Jun 14 '19 at 11:30

1 Answers1

3

Method 1: to_string()

a = StringIO(df.to_string(index=False))

send_simple_message(a)

Method 2:

Export it to csv, then read it with the open function so you get it back as str:

df.to_csv('df.csv', index=False)

with open('df.csv') as f:
    lines = [line for line in f]

a = StringIO(' '.join(lines))

send_simple_message(a)

To check if our a variable is filled:

pd.read_csv(a)

   a  b
0  1  3
1  2  2
2  3  1
Erfan
  • 40,971
  • 8
  • 66
  • 78