1

在 GAE Python 上,我正在从我的数据存储中编写一个 CSV,并希望通过电子邮件发送它而不将其存储在 blobstore 中。这旨在作为 CRON 作业每天运行一次。

导出工作正常,但我不知道如何将 CSV 添加到电子邮件的附件中。您的意见将不胜感激。

class ShopExport(webapp2.RequestHandler):
  def get(self):
    shops = Shop.all().filter('active =', True).order('name')
    self.response.headers[str('Content-Type')] = str('application/csv')
    self.response.headers[str('Content-Disposition')] = str('attachment; filename="shops.csv"')
    writer = unicodecsv.writer(self.response.out, encoding='utf-8')
    writer.writerow(["id", "name", "domain", "category", "deeplink", "region"])
    writer.writerow([shop.keyname, shop.name, shop.url, shop.category, shop.url_aff, region])

    message = mail.EmailMessage(sender="Me <me@gmail.com>",
            subject="Shop Export",
            attachments=[("shops.csv", self.response.out)])
    message.to="Someone <someone@gmail.com>",
    message.html= 'Please find attached the shop export'
    message.send()
4

2 回答 2

3

你可以这样做

import StringIO
...
data = StringIO.StringIO()
writer = unicodecsv.writer(data, encoding='utf-8')
...
message = mail.EmailMessage(sender="Me <me@gmail.com>",
            subject="Shop Export",
            attachments=[("shops.csv", bytes(data.getvalue()))])
于 2013-03-16T18:56:35.683 回答
1

尝试修改这一行。

message = mail.EmailMessage(sender="Me <me@gmail.com>",
        subject="Shop Export",
        attachments=[("shops.csv", self.response.body)])
于 2013-03-16T14:51:33.417 回答