【问题标题】:How to store e-mail attachment to GAE Blobstore?如何将电子邮件附件存储到 GAE Blobstore?
【发布时间】:2013-03-21 21:25:42
【问题描述】:

假设应用收到一条消息,has attachments (mail_message.attachments)。现在,我想将消息保存在数据存储中。我不想在那里存储附件,所以我想只保留 blobstore 密钥。我知道我可以write files to blobstore。我的问题:

  1. 如何从邮件附件中提取文件;
  2. 如何保留原始文件名;
  3. 如何在数据存储中存储 blob 密钥(考虑到一封邮件可以包含多个附件,BlobKeyProperty() 在这种情况下不起作用)。

更新。对于(1)the following code可以使用:

my_file = []
my_list = []
if hasattr(mail_message, 'attachments'):
    file_name = ""
    file_blob = ""
    for filename, filecontents in mail_message.attachments:
        file_name = filename
        file_blob = filecontents.decode()
        my_file.append(file_name)
        my_list.append(str(store_file(self, file_name, file_blob)))

【问题讨论】:

    标签: google-app-engine email blobstore app-engine-ndb


    【解决方案1】:

    您应该使用 NDB 而不是(旧)数据存储。在 NDB 中,您可以使用重复和结构化的重复属性来保存 BlobProperties 和文件名列表。

    见:https://developers.google.com/appengine/docs/python/ndb/properties

    【讨论】:

    • 谢谢,我使用 NDB(见标签)。
    【解决方案2】:

    这是我最终要做的:

    class EmailHandler(webapp2.RequestHandler):
        def post(self):
            '''
            Receive incoming e-mails
            Parse message manually
            '''
            msg = email.message_from_string(self.request.body) # http://docs.python.org/2/library/email.parser.html
            for part in msg.walk():
                ctype = part.get_content_type()
                if ctype in ['image/jpeg', 'image/png']:
                    image_file = part.get_payload(decode=True)
                    image_file_name = part.get_filename()
                    # save file to blobstore
                    bs_file = files.blobstore.create(mime_type=ctype, _blobinfo_uploaded_filename=image_file_name)
                    with files.open(bs_file, 'a') as f:
                        f.write(image_file)
                    files.finalize(bs_file)
                    blob_key = files.blobstore.get_blob_key(bs_file)
    

    blob_keys 在数据存储中存储为ndb.BlobKeyProperty(repeated=True)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-18
      • 2013-03-05
      • 1970-01-01
      • 1970-01-01
      • 2011-11-27
      • 2014-10-24
      相关资源
      最近更新 更多