How to download all attachments of a mail using python IMAP

Viewed 5904

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.

2 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('test@mail.com', '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)

Here is an example of Downloading Attachments from Outlook Emails using Python. I used the library called: exchangelib.

https://medium.com/@theamazingexposure/accessing-shared-mailbox-using-exchangelib-python-f020e71a96ab

Here is the Code Snippet:

from exchangelib import Credentials, Account, FileAttachment
import os.path
from pathlib import Path

credentials = Credentials('Firstname.Lastname@someenterprise.com', 'Your_Password_Here')
account = Account('shared_mail_box_name@someenterprise.com', credentials=credentials, autodiscover=True)
filtered_items = account.inbox.filter(subject__contains='Data is ready for')
print("Getting latest email...")
for item in account.inbox.filter(subject__contains='Data is ready for').order_by('-datetime_received')[:1]:
    print(item.subject, item.sender, item.datetime_received)
    for attachment in item.attachments:
        if isinstance(attachment, FileAttachment):
            filepath = os.path.join('C:\\path\\to\\your\\directory', attachment.name)  #this part will download the attachment to local file system
            with open(filepath, 'wb') as f:
                f.write(attachment.content)
            print('Saved attachment to:', filepath)
Related