Easy scripted download Attachment utilizing the Graph or Outlook Relaxation API in Workplace365

Easy scripted download Attachment utilizing the Graph or Outlook Relaxation API in Workplace365 It is a rewrite of one of many extra well-liked EWS posts (authentic publish) on my weblog about making a scripted course of that may download attachments from an e-mail with a selected topic line within the Inbox after which mark that e-mail learn and transfer it to a different folder within the Mailbox. On this publish I am going to undergo a direct one to one rewrite of this script and speak in regards to the comparisons between the way you used the operations in EWS and now how you are able to do the identical factor utilizing the Graph or Outlook REST API. In one other publish I am going to present an enhanced model that permits you to use the Graph API to save lots of the attachment into one other Graph endpoint akin to OneDrive or SharePoint.

For this script I am utilizing the Exch-Relaxation Module I am at present constructing which is on the market on the powershellgallery and the supply from Github For this script I needed to overcome a difficulty with the ConvertFrom-Json Cmdlet which has a difficulty as soon as the JSON payload will get over 2 MB so an alternate technique within the REST code was wanted to permit for attachment downloads of over 2MB.

Step 1: Loading the Module, Establishing variables for the script and Getting the Entry Token

Import-Module Exch-Relaxation -Drive
$MailboxName = ""
$Topic = "Daily Export"
$ProcessedFolderPath = "InboxProcessed"
$downloadDirectory = "c:temp"
##Get the Entry Token
$AccessToken =  Get-AccessToken -MailboxName $MailboxName  -ClientId 5471030d-f311-4c5d-91ef-74ca885463a7 -redirectUrl "urn:ietf:wg:oauth:2.0:oob" -ResourceURL 

Step one within the scripted course of is to load the module then setup some variables to carry which mailbox to entry, the topic of the Message to seek for and the folder to maneuver the message to as soon as its has been processed. Then lastly now we have the code to get the oauth AccessToken,with getting the Entry Token there are few completely different choices described right here that you must select essentially the most acceptable one for you relying on how you will implement this in your surroundings. The EWS equal right here would have been loading the Managed API, authenticating and doing an Autodiscover

Step 2: Seek for the Objects within the Inbox which are Unread, Have Attachments and the Topic line “Daily Export”

$Filter = "IsRead eq false AND HasAttachments eq true AND Subject eq '" + $Topic + "'"
$Objects = Get-FolderItems -MailboxName $MailboxName -AccessToken $AccessToken -FolderPath Inbox -Filter $Filter

Within the REST API like EWS there are two other ways of trying to find gadgets

  • Filter

In EWS this was completed utilizing the SearchFilters Class (or a restriction in EWS proxy code) in REST that is completed utilizing the OData parameter $filter. The underlying mechanism the Change retailer makes use of for each EWS and REST to filter gadgets and returned outcomes is based mostly on Restrictions (I nonetheless like the reasons on this article as to how they work . Utilizing Filters offers you essentially the most flexibility with regards to discovering specific gadgets based mostly on specific properties however this does come at the price of efficiency. You must strive not to over complicate your filters an excessive amount of as like several database your efficiency and utility will undergo if the filters are written poorly with no regards to information construction or amount.

  • Content material Index Searches

In EWS a content material index search could possibly be completed utilizing AQS (Advance Question Syntax) and the QueryString Ingredient within the FindItem operation. In REST you employ the $Search OData parameter and the identical AQS syntax you employ in EWS. These searches ought to yield significantly better efficiency if you find yourself looking out folders with a lot increased Merchandise counts as a result of they make the most of the Content material indexes. There are limitations round utilizing Search nonetheless as a result of solely sure properties are listed and obtainable to be used (see and there generally is a delay in Indexes being up to date.

I’ve used the $filter parameter in my above instance which displays the SearchFilter utilized in EWS within the authentic publish however Search is also used on this instance.

Step 3: Processing the Attachments on the Objects

Get-Attachments -MailboxName $MailboxName -ItemURI $merchandise.ItemRESTURI -MetaData -AccessToken $AccessToken | ForEach-Object{
$connect = Invoke-DownloadAttachment -MailboxName $MailboxName -AttachmentURI $_.AttachmentRESTURI -AccessToken $AccessToken
$fiFile = new-object System.IO.FileStream(($downloadDirectory  + "" + $connect.Identify.ToString()), [System.IO.FileMode]::Create)
$attachBytes = [System.Convert]::FromBase64String($connect.ContentBytes)  
$fiFile.Write($attachBytes, 0, $attachBytes.Size)
write-host ("Downloaded Attachment : " + (($downloadDirectory + "" + $connect.Identify.ToString())))

 Like EWS once you enumerate the Objects in folder utilizing REST it will not return all of the details about the Merchandise for efficiency causes. So like EWS the place you’ll then use a GetItem request to get the Metadata details about attachments in REST that you must do a simular factor earlier than you possibly can proceed to downloading the attachment. Within the module I’ve the Get-Attachments operate for returning the MetaData about attachments (this writes a customized AttachmentRESTURI property into the outcomes). Then the Invoke-DownloadAttachment operate does the downloading of the attachments content material. If the message has extra then one attachment that is the place you’ll modify the code to do extra processing (eg restriction on FileName, FileType and so on).

Step4: Marking the Merchandise as Learn

$UpdateProps = @()
$UpdateProps += (Get-ItemProp -Identify IsRead -Worth true -NoQuotes)
Replace-Message -MailboxName $MailboxName -AccessToken $AccessToken -ItemURI $merchandise.ItemRESTURI -StandardPropList $UpdateProps

In EWS to mark an Merchandise as learn you’ll replace the IsRead Strongly typed property after which name UpdateItem operation. In REST it’s a lot the identical process besides now we have some code that defines the Property you wish to replace in JSON (on this case the isRead property) after which it makes use of a HTTP Patch request to ship the replace to the server together with the URI of the Merchandise you might be updating.

Step5: Shifting the Merchandise to a different folder

Transfer-Message -MailboxName $MailboxName -ItemURI $merchandise.ItemRESTURI -TargetFolderPath $ProcessedFolderPath -AccessToken $AccessToken     

 In EWS to maneuver an Merchandise to a different folder you employ the MoveItem operation, in REST its pretty simular you invoke a transfer by sending the URI of the Merchandise with /transfer appended to the tip with a JSON payload of vacation spot FolderId which is what Transfer-Message operate does within the Module.

that is just about it I’ve posted the complete code for this pattern on GitHub right here