简体   繁体   English

如何在Django的FileField中保存来自传入电子邮件的附件?

[英]How to save the attachment from an incoming email in Django's FileField?

I'm trying to save any attachments of incoming emails to a FileField in Django. 我正在尝试将传入电子邮件的所有附件保存到Django中的FileField中。

The model looks like this: 该模型如下所示:

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

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

I wrote this function to return the attachments. 我编写了此函数以返回附件。

def get_attachments(email_object):
    attachments = []
    for part in email_object.walk():
        # content_type = part.get_content_type()
        content_disposition = part.get("Content-Disposition")
        if content_disposition and content_disposition.lower().startswith("attachment"):
            attachments.append(part)
    return attachments

Now I have a list of instances of the email object, and I'm not sure how to save them as a file in the FileField. 现在,我有了电子邮件对象的实例列表,而且不确定如何将它们另存为FileField中的文件。 attachment.get_content_type() returns image/jpeg . attachment.get_content_type()返回image/jpeg But how do I go from here to making it somehting that can be saved in the file field? 但是,如何从这里开始,使它可以保存在文件字段中呢?

Thanks for all help. 感谢您的所有帮助。

To save a email attachment to the directory and save the record in the model, you need to do the following, 要将电子邮件附件保存到目录并将记录保存在模型中,您需要执行以下操作,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM