How to Download Attachments From Outlook Using Python and MSAL

Automate your Outlook attachment downloads using Python


This article describes how to download email attachments from an Outlook mailbox using Python. We will be using the following libraries to accomplish this task.


Note: Please note that if you are using ADAL for authentication, Microsoft recommends migrating to MSAL.


To extract attachments from an email we need the following.

  • Mailbox credentials (username and password)
  • Sender email (Filter messages from a specific sender if required)
  • Message id (Unique message id for an email)
  • Attachment id for a Message id (Attachment id for an email that has an attachment).

The above data is required to authenticate, initialise the ClientApplication object, and construct the MS Graph API to download the attachments.

Install MSAL:

$pip install msal

The Microsoft authentication library for python allows you to sign in users or apps with Microsoft identities, obtain auth tokens to be used with Microsoft Graph APIs. They are built using OAuth2 and OpenID connect protocols.

Initialising the Client Application:

MSAL defines 3 types of applications and clearly provides a demarcation in initialising them.

  • Client Application
  • PublicClientApplication
  • ConfidentialClientApplication

To learn more about the OAuth client types please click here. In this article, we will be using ClientApplication to initialise the app object and reuse it throughout our application.

from msal import ClientApplication

class AttachmentDownloader:

def __init__(self, username: str, password: str):

self.client_id = '<your client id>'

self.authority = '<tenant-name>'

# Initialise MS ClientApplication object with your client_id and authority URL = ClientApplication(client_id=self.client_id,


self.username = username # your mailbox username

self.password = password # your mailbox password

if __name__ == "__main__":

downloader = AttachmentDownloader("", "password")

ClientApplication Initialisation

Acquire token:

Now that we have our app object initialised, we can acquire the token. This token can be used to extract to access_token for headers.

token =,





This gets the default, top 10 messages in the signed-in user’s mailbox.

If you wish to increase the number of results returned, you could set the page size using the top query parameter.$top=20

This sets the page size to 20.

The token output looks like this.



"scope":"email openid profile 00000003-0000-0000-c000-000000000000/EWS.AccessAsUser.All 00000003-0000-0000-c000-000000000000/IMAP.AccessAsUser.All 00000003-0000-0000-c000-000000000000/Mail.Read-0000-c000-000000000000/Mail.Read.Shared 00000003-0000-0000-c000-000000000000/Mail.ReadWrite.Shared 00000003-0000-0000-c000-000000000000/Mail.Send 00000003-0000-0000-c000-000000000000/Mail.Send.Shared 00000003-0000-0000-c000-000000000000/POP.AccessAsUser.All 00000003-0000-0000-c0/User.Read 00000003-0000-0000-c000-000000000000/.default",























token output

Extract emails for a username:

We will use the MS Graph API to extract all the messages. The API documentation is available here.


response = requests.get(url='',



except RequestException as re:


extract all messages from a sender in outlook using MSAL































"content":"<html><head>\r\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"></head><body><p></p><p>Thanks &amp; Regards,</p><p</p><br><hr></body></html>"



































all messages JSON output

Now that we have the messages, we need to extract the id of the messages that have the flag hasAttachments set to True. Something like below:

mails_with_attachments = list()

# all_msgs is the response of all messages API

for msg in all_msgs.get('value'):

if msg.get('sender').get('emailAddress').get('address') == sender and msg.get('hasAttachments'):


extract the message id

Alternatively, you could also use the filter options in the API, to filter messages from a specific sender like below.


Here, sender is the filter. You could also couple multiple filters like sender and subject as well.

Now, let’s assume we have all the ids of emails with attachments. We need to get all the attachment ids for an email.

Extract attachment id for a message:

We are assuming that this email has only one attachment. The API documentation is available here.

response = requests.get(url='"<msg-id>/attachments"', headers=headers)

jsonified_response = response.json()

attachment_id = jsonified_response.get('value')[0].get('id')

extract attachment id

Download attachment:

Now that we have both the attachment and msg ids, we can download the attachment. I have also added a progress bar to show the download progress. the API documentation for download is available here.

from tqdm import tqdm

def download_attachment(msg_id, att_id, name):


response = requests.get(

url="<msg id>/attachments/<attachment id>/$value",



file_size = len(response.content)

with open(f"{name}.zip", 'wb') as f, tqdm(unit='iB', unit_scale=True,

unit_divisor=1024, total=file_size,

desc=f"Downloading {name}.zip") as pbar:

for data in response.iter_content(chunk_size=1024):



return response

except ConnectionError as ce:

print(f" Connection error: {ce}")

except RequestException as re:

print(f" Request exception: {re}")

download attachment


  • Create a ClientApplication object and use it throughout the lifecycle of our application.
  • Use the app object to extract all attachments for a specific sender.
  • Filter the messages with attachments and add all the attachment ids and their corresponding message ids to a list/dict.
  • Use the message id and attachment id to download the attachment.

And there you have it. Thank you for reading.

Continue Learning