daniel9x
daniel9x

Reputation: 805

AWS Lambda - Generate CSV In Memory and send it as an attachment to an Email

I'm trying to write an AWS Lambda service using Python 2.7 that will generate an In-Memory CSV file and email it as an attachment. I feel like I'm close with this script based on what I've learned but I'm not quite there.

# Import smtplib for the actual sending function
import smtplib
import sys
import csv 
import cStringIO
from os.path import basename
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
# Import the email modules we'll need
server = smtplib.SMTP('smtp.postmarkapp.com', 587)

server.starttls()

server.login('.....','.....')

list = []

row1 = ["One","Two","Three"]

list.append(row1)

msg = MIMEMultipart()
msg['To'] = "[email protected]"
msg['From'] = "[email protected]"
msg['Subject'] = "DG Test subject"
msg.attach(MIMEText("Test Message"))


csv_buffer = cStringIO.StringIO() 
writer = csv.writer(csv_buffer, lineterminator='\n')
writer.writerow(["1","2","3"])
for row in list:
    writer.writerow(row)
print(csv_buffer.getvalue())
msg.attach(csv_buffer)

try:
    response = server.sendmail(msg['From'], ["[email protected]"],msg.as_string())
    server.quit()
except AttributeError as error:
    print(error)
else:
    print(response)

This gives me the following error:

1,2,3
One,Two,Three

'cStringIO.StringO' object has no attribute 'get_content_maintype'

Basically it comes down to not being sure how to use the csv_buffer object. Assuming I just need to add that attribute to the object somehow but I'm not quite sure how. If I try to add any additional arguments to the .attach() line, it complains that I have too many arguments.

Thanks!

Upvotes: 3

Views: 5460

Answers (1)

daniel9x
daniel9x

Reputation: 805

I figured it out, thanks to stitching together a few SO posts.

import  cStringIO
import csv

csv_buffer = cStringIO.StringIO() 
writer = csv.writer(csv_buffer, delimiter=',', quoting=csv.QUOTE_ALL)
writer.writerow(["1","2","3"])
  for row in list:
    writer.writerow(row)
    print(csv_buffer.getvalue())

# new lines
csv_file = MIMEText(csv_buffer.getvalue())
attachment = csv_file.add_header('Content-Disposition', 'attachment', filename="csv_file.csv")
msg.attach(csv_file)

Upvotes: 3

Related Questions