【问题标题】:GAE Python - How to attach the results of csv.writer to an email?GAE Python - 如何将 csv.writer 的结果附加到电子邮件中?
【发布时间】:2013-03-05 04:03:20
【问题描述】:

在 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()

【问题讨论】:

    标签: python google-app-engine email csv


    【解决方案1】:

    你可以这样做

    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()))])
    

    【讨论】:

    • +1。与接受的答案相比,这样做的好处是它适用于延迟任务等。
    【解决方案2】:

    尝试修改这一行。

    message = mail.EmailMessage(sender="Me <me@gmail.com>",
            subject="Shop Export",
            attachments=[("shops.csv", self.response.body)])
    

    【讨论】:

    • 谢谢,正是我想要的! :)
    猜你喜欢
    • 2013-03-21
    • 1970-01-01
    • 2021-07-22
    • 1970-01-01
    • 1970-01-01
    • 2017-11-07
    • 1970-01-01
    • 2020-12-28
    • 1970-01-01
    相关资源
    最近更新 更多