我正在尝试使用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()行添加任何其他参数,它会抱怨我有太多参数。
谢谢!
答案 0 :(得分:1)
我想通了,这要归功于将几个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)