Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to download all attachments of a mail using python IMAP

I need to download all the attachments from a particular mail in outlook. The below code is working fine if there is single attachment but when the mail has multiple attachment, it only download one. Can anyone help me regarding this? Thanks.

I'm running this on python 3.7.

import imaplib
import email
import os

server =imaplib.IMAP4_SSL('outlook.office365.com',993)
server.login('Email id','Password')
server.select()
typ, data = server.search(None, '(SUBJECT "Subject name")')
mail_ids = data[0]
id_list = mail_ids.split()

for num in data[0].split():
    typ, data = server.fetch(num, '(RFC822)' )
    raw_email = data[0][1]
    raw_email_string = raw_email.decode('utf-8')
    email_message = email.message_from_string(raw_email_string)

    for part in email_message.walk():
        if part.get_content_maintype() == 'multipart':
            continue
        if part.get('Content-Disposition') is None:
            continue
        fileName = part.get_filename()
        if bool(fileName):
            filePath = os.path.join('C:\\Users\\lokesing\\', fileName)
            if not os.path.isfile(filePath) :
                fp = open(filePath, 'wb')
                fp.write(part.get_payload(decode=True))
                fp.close()
server.logout
print("Attachment downloaded from mail")

The output should be all attachments downloaded to my system at defined path.

like image 538
Lokendra Singh Rathod Avatar asked Nov 21 '25 02:11

Lokendra Singh Rathod


1 Answers

You may use imap_tools package: https://pypi.org/project/imap-tools/

from imap_tools import MailBox, Q

# get all attachments for each email from INBOX folder
with MailBox('imap.mail.com').login('[email protected]', 'password') as mailbox:
    for msg in mailbox.fetch():
        for att in msg.attachments:
            print(att.filename, att.content_type)
            with open('C:/1/{}'.format(att.filename), 'wb') as f:
                f.write(att.payload)
like image 75
Vladimir Avatar answered Nov 22 '25 17:11

Vladimir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!