Getting mail attachment to python file object

后端 未结 3 701
小鲜肉
小鲜肉 2020-12-02 10:10

I have got an email multipart message object, and I want to convert the attachment in that email message into python file object. Is this possible? If it is possible, what m

3条回答
  •  执笔经年
    2020-12-02 10:41

    Here is working solution, messages are form IMAP server

    self.imap.select()
    typ, data = self.imap.uid('SEARCH', 'ALL')
    msgs = data[0].split()
    print "Found {0} msgs".format(len(msgs))
    
    for uid in msgs:
        typ, s = self.imap.uid('FETCH', uid, '(RFC822)')
        mail = email.message_from_string(s[0][1])
    
        print "From: {0}, Subject: {1}, Date: {2}\n".format(mail["From"], mail["Subject"], mail["Date"])
    
        if mail.is_multipart():
            print 'multipart'
            for part in mail.walk():
                ctype = part.get_content_type()
                if ctype in ['image/jpeg', 'image/png']:
                    open(part.get_filename(), 'wb').write(part.get_payload(decode=True))
    

提交回复
热议问题