2013-03-31 107 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)

相關問題