2017-12-06 3 views
0

私は着信電子メールの添付ファイルをDjangoのFileFieldに保存しようとしています。DjangoのFileFieldに入ってくるメールから添付ファイルを保存するには?

モデルは次のようになります。

class Email(models.Model): 
    ... 
    attachment = models.FileField(upload_to='files/%Y/%m/%d', null=True, blank=True) 
    ... 

    def __unicode__(self): 
    return self.contents[:20] 

私は添付ファイルを戻すには、この機能を書きました。

私は電子メールオブジェクトのインスタンスのリストを持っており、FileFieldにファイルとして保存する方法がわかりません。 attachment.get_content_type()image/jpegを返します。しかし、ここからファイルフィールドに保存できるようにするにはどうしたらいいですか?

ありがとうございました。ディレクトリへの電子メールの添付ファイルを保存して、モデル内のレコードを保存するには

答えて

0

、あなたが次のことを行う必要があり、

#firstly change your model design 
#an email can have 0 - n attachments 

class EmailAttachment(models.Model): 
    email = models.ForeignKey(Email) 
    document = models.FileField(upload_to='files/%Y/%m/%d') 

#if you want to save an attachment 
# assume message is multipart 
# 'msg' is email.message instance 
for part in msg.get_payload(): 
    if 'attachment' in part.get('Content-Disposition',''): 
     attachment = EmailAttachment() 
     #saving it in a <uuid>.msg file name 
     #use django ContentFile to manage files and BytesIO for stream 
     attachment.document.save(uuid.uuid4().hex + ".msg", 
      ContentFile(
       BytesIO(
        msg.get_payload(decode=True) 
       ).getvalue() 
      ) 
     ) 
関連する問題