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))
Getting mail attachment to python file object