Download messages from a particular sender in Outlook

44 Views Asked by At

I need help in writing a Python script to download attachments from Outlook from a particular sender. I was able to download all attachments in 'Inbox', but should download from a particular sender.

from exchangelib import Account, DELEGATE 
from exchangelib.util import Credentials


def download_attachments(username, password, sender_email, save_path):
    
    credentials = Credentials(username, password)
    
    account = Account(username, credentials=credentials, autodiscover=True, access_type=DELEGATE)
    
    for item in account.inbox.filter(sender__icontains=sender_email).order_by('-datetime_received')[:5]:
        
        print(f"Subject: {item.subject}")
        print(f"From: {item.sender.email_address}")
        print(f"Received: {item.datetime_received}")

        if item.attachments:
            for attachment in item.attachments:
                with open(f"{save_path}/{attachment.name}", "wb") as f:
                    f.write(attachment.content)

                print(f"Attachment '{attachment.name}' downloaded.")`

if __name__ == "__main__":
    username = "*****@outlook.com"
    password = "your_password"
    sender_email = "******@outlook.com"
    
    save_path = input("Enter the path to save attachments (default is current directory): ") or "."

    download_attachments(username, password, sender_email, save_path)

The above code is perfect but giving me errors in Credentials library

from exchangelib import Credentials, DELEGATE
ImportError: cannot import name 'Credentials' from partially initialized module 'exchangelib' (most likely due to a circular import)
0

There are 0 best solutions below