简体   繁体   中英

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.

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. attachment.get_content_type() returns 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()
            )
        )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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