AWS Lambda - 在内存中生成 CSV 并将其作为电子邮件附件发送

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

我正在尝试使用 Python 2.7 编写一个 AWS Lambda 服务,它将生成一个内存中的 CSV 文件并将其作为附件通过电子邮件发送。根据我所学的知识,我觉得我已经接近这个脚本了,但我还不完全。

# 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'] = "daniel@mydomain.com"
msg['From'] = "noreply@mydomain.com"
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'], ["daniel@mydomain.com"],msg.as_string())
    server.quit()
except AttributeError as error:
    print(error)
else:
    print(response)

这给了我以下错误:

1,2,3
One,Two,Three

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

基本上归结为不确定如何使用 csv_buffer 对象。假设我只需要以某种方式将该属性添加到对象,但我不太确定如何添加。如果我尝试向 .attach() 行添加任何其他参数,它会抱怨我有太多参数。

谢谢!

多亏了几个 SO 帖子的拼接,我明白了。

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)