2013-03-31 59 views
1

我们假设应用程序收到一条消息,其中has attachmentsmail_message.attachments)。现在,我想将该消息保存在数据存储中。我不想在那里存储附件,所以我只想保留blobstore密钥。我知道我可以write files to blobstore。我有的问题:如何将电子邮件附件存储到GAE Blobstore?

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

Upd。对于(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))) 

回答

0

这是我最后做的:

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_key s的存储到数据存储为ndb.BlobKeyProperty(repeated=True)

相关问题