Download Outlook Email Attachments Using Microsoft Graph API In Python

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey how soon guys in this tutorial we'll learn how to download email attachments in outlook using microsoft graph api in python all right so in the past when i need to download outlook email attachments automatically i would have to rely on using vba and one of the limitations when using phoebe is vba only works with the outlook desktop application and since all the email messages are saved on the microsoft exchange server i need to retrieve the emails locally first then i can download the email attachments now the problem is completely itself with using graph api by using the graph api i can now connect to the email server directly now i want to dive into my python script from the input statement i'll hear me increase the font size from the input statement i'm going to import the o's module and to make the request code i'm going to import the requestes library and to authenticate our account i wrote a module called ms graph and here's the script and you can download the source code from the link in the description below so basically inside this module i have this generate access token function that allows me to quickly create the access token all right so from the ms graph module i'm going to import the generate access token function now to go into the documentations right so there are a couple of methods that i'll be using and to be honest downloading attachments from your email account is not as straightforward as people think right so i'll be using two main uh api endpoints the first one is going to be the message endpoint or the list message method right so if i scroll down to the permissions we can use one of these three permission sets and for the api request we'll need to make a get request and based on the account that you want to access if i'm going to connect to your own account then you can use me to reference your own account if you are connecting to someone else's account they will need to change the endpoint to users followed by the user's email address followed by messages and if you are downloading attachments from emails in a specific folder then you will need to use this method here to access those emails but honestly i usually use the query to return the emails based on the queries criteria which i'll show you in a second so basically we'll need to use the get me message method to retrieve the emails then we're going to download the attachments using the get attachments method and the permission set is going to be pretty much the same now this going to everything i'm going to cover in terms of the documentation and i'll post the links in the description below just in case if you need to reference the documentation all right so going back to the python script alright so for step one we need to get the access token and to do that we need to provide the app id and let me grab my app id then we need to uh specify the scopes all right so for the scopes i'm going to use let me take a look i'm going to use this one mail.read and right scope i'm going to insert the generate access token function and i'll assign the app id and the scopes and here i'll create my headers inside the headers we need to supply the authorization property and this will be bill space followed by the access token all right so let me go ahead and run this code block to generate the headers all right so if i print headers it's going to return the headers with the access token all right so on the top i want to create a function and i'll name this function download email attachments and this function takes three parameters message id headers and save folder location and i'll set the default location to my project folder basically this function is going to be used to save all the attachments giving the email's message id all right so inside the function i'm going to insert a try accept block and for the exception i'm going to print the air message down to its own files and for the try block i'm going to insert the gate request and name this as response all right so going back to step one i want to create one more variable i want to call this a graph api endpoint and it's going to be the base url to access to graph api import and the address is going to be dot graph.microsoft.com slash v 1.0 and we go ahead and create a variable right so going back to the function for the endpoint is going to be graph api endpoint followed by the list message component and here we're going to insert the email message id slash attachments data format and the variable is going to be coming from message id and here this is going to be coming from headers argument basically i'm making a get request and this response is going to return all the attachments or information giving the email id they want to grab the attachments records from the response option so i'm going to name this option attachment items so at this point while only retrieving the attachments made out data and to actually download the file we need to make a separate request all right so from response.json the rack is going to be sitting in the value key then i'm going to erase the attachment islands list so i'm going to say for attachment and attachment items i want to grab the file name first followed by the attachment id then we're going to download the byte string open attachment and i'll name this object attachment content now here we're going to make a separate request it's going to be a get request so i'm going to insert the graph api it's going to be me messages and it's going to be message id attachments and this one's going to be attachment id then we need to insert the dollar sign value and close the string so this is going to be the end point we're going to make to download the attachment content so i need to provide the variables okay so it's going to be message id and attach my id now here i want to use a message saving file and it's going to be the file name dat format then we're going to save the file locally so we open then we're going to insert the file path and this will be writer's binary and i'll name the context manager underscore f then i'll write the file and we can insert attachment content dot content to achieve the by string and then on to turn two once the task is finished right so let me go ahead and create this function oh so here i've got the comma now let's go back to step one so at this point we can go to step two retrieve emails so here i'm going to insert my parameter to limiting the number of messages that i'm going to retrieve if you have questions regarding the queries you can go to this page use query parameters to customize response and we can specify different conditions to retrieve the emails or other items given the conditions all right so here i'm going to create my criteria and i'll name the criteria params i only want to return the first three messages so i'm going to set the top value to 3 and the mix is 1000 messages per request down to specify the fields i want to return i only want to return the email subject in the field to indicate whether if an email has attachment or not and the field name is going to be has attachments down to insert my condition using the filter property and the crease is going to be has attachments this goes to 2 oh actually this needs to be double quotation i also want to return the record count so i'm going to set the count value to 2. now going back to my project folder i want to save all my email attachments in this attachments folder here i'm going to make a get request and the endpoint is going to be graph api endpoint me i want to create the emails only in the inbox folder so here i'm going to type me slash mail folders slash and it's going to be the folder name inbox followed by messages i'll name the outputs response all right so here i'm going to insert an if condition if response the status quo it's not equals to 200 don't raise an exception [Applause] don't return the reason why the exception is happening otherwise i can go ahead and resend the response in json format now let me go ahead and run step two so this disco block myself and he's saying that access tokens mto so i forgot to supply the hitters let's see oh this should be a comma right so if i print the response option by itself and it's going to return a status code 200 or i can run this if statement it's not going to play anything because there's no exception occurred but i'm going to pass the json output to this response json object all right so if i play response json it's going to return additional object with a big chunk of information now i'm going to print the keys and it's going to return these three keys so the emails records are going to be saved in this value key all right so i'm going to create object code emails in front response json i want to reference the valid key to pass the records to this emails option and i noticed that it's returning 10 emails not the tweet i specified it so i made a mistake i forgot to pass the parameters to the premise parameter so here we remake the request and i'll run this code block right so this time i have four keys and the data that counts key was what i was looking for and if we reference the oh you have a typo if i reference the oh data.counts key and it's going to return the email account as we send in certain emails i wonder why but let me go in the update the emails option if i use the link function to get the rack answer account tree but the old data that counts key is written in 13. so i guess there's a description see between um how the back end is performing but for now i know there are only two records that are returned given the value key now to erase each email in the emails object so i'm going to save for email in emails and basically uh based on the criteria diet i specified it every single email here let me print the email i want to print the email subject and has attachments uh property so if i run this loop i should expect that oh this should be lowercase i should expect that every single record should have has attachments value equals to true and to make the script a little bit more robust i'm going to insert if condition if email giving the has attachments key then i'll go ahead and download the attachments of an email message but first i need to grab the emails id now you can reference the id by giving the id key the only so the download email attachment is function and i'll provide the email id headers in the folder location all right so that's going to be the entire script what i want to do here is i'm going to terminate this session and because i already authenticated my account and it's going to create this api token.json file that store the session now here i'm going to press f5 to run the script right so here i have a typo oh this will be format let me try again and here i'm getting another ear loose indices must be an integers or slices oh okay so here uh this should not be there so this time getting the saving file followed by the file name message now if i go into my attachments folder and here are the attachments from my first three email messages so this is going to be some gum to share in this video and hopefully you guys found this video useful and as always see you guys watching i'll see you guys in the next video
Info
Channel: Jie Jenn
Views: 21,127
Rating: undefined out of 5
Keywords: Outlook API, Microsoft Graph API, Automate Outlook, Outlook Automation, MS Graph API
Id: UF-hc2nZV_A
Channel Id: undefined
Length: 20min 11sec (1211 seconds)
Published: Wed Apr 13 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.