0
votes

I have a data, let's say

data = [
    ['header_1', 'header_2'],
    ['row_1_!', 'row_1_2'],
    ['row_2_1', 'row_2_2'],
]

I need to send that data as .csv file attachment to email message. I can not save it as .csv and then attach existing csv - application is working in Googpe App Engine sandbox environment. so no files can be saved.

As I understand, email attachment consists of file name and file encoded as base64.

I tried to make attachment body in the following way:

import csv
if sys.version_info >= (3, 0):
    from io import StringIO
else:
    from StringIO import StringIO
in_memory_data = StringIO()
csv.writer(inmemory_data).writerows(data)
encoded = base64.b64encode(inmemory_data.getvalue())

But in result I have received by email not valid file 2 columns and 3 rows, but just one string in file (see the picture). csv_screen

What I'm doing wrong?

1

1 Answers

0
votes

I've found out the mistake. I should have been convert it to bytearray instead of encoding to base64:

encoded = bytearray(inmemory_data.getvalue(), "utf-8")

Worked fine that way.