Utilizing the Workplace365/Trade 2016 REST API for working with Mailbox and OneDrive recordsdata/attachments

Utilizing the Workplace365/Trade 2016 REST API for working with Mailbox and OneDrive recordsdata/attachments In my final publish I demonstrated learn how to rewrite a easy download course of script from utilizing EWS to utilizing the brand new REST API in Workplace365. This was an instance of an Automation course of that I first used within the early 2000’s as again then e-mail supplied a ubiquity for a easy knowledge switch that even right now is difficult to do in some enterprises which is why that publish has been so in style over time.

On this publish I’ll present you how one can make use of different Workplace365 endpoints obtainable within the Graph API to mainly take this outdated course of and begin bettering on it. The actual Endpoint I will be specializing in on this publish is OneDrive https://dev.onedrive.com/ (or One Drive for enterprise). I am going to even be utilizing my Exch-Relaxation Module and profiting from all of the present code I’ve written for the interacting with  Trade On-line to work together with the OneDrive endpoint. And that actually is the one beauty of the brand new Graph Endpoint is that each one I’ve wanted to do so as to add OneDrive functionally to my module is to create some new capabilities to cope with the particular addressing variations between Mail and One Drive whereas the underlying Auth, Get and Publish perform are the identical (so velocity and agility in advertising and marketing fluff and fewer hours recoding in actual converse).

Fundamentals of Interacting with One Drive

Authentication : To make use of One Drive from the Exch-Relaxation Module the applying registration you may have been utilizing for your Mail scripts must be granted the OneDrive Permission Grants within the Azure portal https://dev.onedrive.com/auth/graph_oauth.htm. As soon as the grants have been added they are going to be then returned when AccessToken is requested, so mainly you should use the identical AccessToken for accessing Electronic mail and OneDrive with out the necessity to authenticate once more.

Paths and Drives:
 Every person has a default OneDrive drive which you’ll entry utilizing the /drive/root path . If you understand the Id of the file you wish to entry then you should use the next Path drive/gadgets/{item-id} to entry it in any other case if you understand the relative path (eg folder path/filename) then this can be utilized like /drive/root:/path/to/file to entry the file. (this can be a fairly primary rationalization however the documentation cowl this in additional depth https://dev.onedrive.com/ )

 It will make extra sense while you have a look at an instance so lets begin

Fashionable Attachments aka Reference Attachments

Fashionable Attachments is a brand new function launched into Trade,Workplace365 and Outlook 2016 that was a sort of inbuilt OneDrive and Trade integration function. In EWS and REST these sort of attachments are referred to as reference attachments . Inside the REST API at the moment Reference attachments are supported within the v2.zero Outlook endpoint and the Beta endpoint within the present Graph API. I’ve added help for sending reference attachments in Exch-Relaxation (v1.9) so an instance of sending a reference attachment (eg a one drive file) utilizing the Graph Beta Endpoint utilizing the module would seem like

Import-Module Exch-Relaxation -Pressure
$MailboxName = "gscales@datarumble.com"
$OneDriveFile = "/test/test2/fileName.zip"
$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 graph.microsoft.com -Beta
##Get OneDrive DownloadURI
$OneDriveAttachmentToSend = Get-OneDriveItemFromPath -MailboxName $MailboxName -AccessToken $AccessToken -OneDriveFilePath $OneDriveFile
$rtArray = @()
$rtArray += (New-referanceAttachment -Identify $OneDriveAttachmentToSend.Identify -SourceUrl $OneDriveAttachmentToSend.webUrl -Permission Edit)
Ship-MessageREST -MailboxName $MailboxName  -AccessToken $AccessToken -ToRecipients @(New-EmailAddress -Handle glenscales@yahoo.com) -Topic "Daily Send" -Physique "See Attached" -ReferanceAttachments $rtArray

 Full Supply Obtainable right here

On this instance the Get-OneDriveItemFromPath perform within the module is getting used to get the required Reference Attachment properties (Identify and WebURL) from the OneDrive file utilizing the relative onedrive path. The New-referanceAttachment perform creates a customized object that then Ship-MessageREST perform will be capable of assemble the required REST message to ship.

Downloading a File from One Drive and Sending it as a traditional Attachment

Fashionable Attachments are nice however loads of the time you’ll simply have to ship a specific one drive file as a daily attachment. On this case we want some extra code to download the file you wish to ship from One Drive so it could possibly then be Despatched usually eg right here is an instance of doing this

Import-Module Exch-Relaxation -Pressure
$MailboxName = "gscales@datarumble.com"
$OneDriveFile = "/test/test2/fileName.zip"
$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 graph.microsoft.com
##Get OneDrive DownloadURI
$OneDriveAttachmentToSend = Get-OneDriveItemFromPath -MailboxName $MailboxName -AccessToken $AccessToken -OneDriveFilePath $OneDriveFile
$DownloadFileName = $DownloadDirectory + "" + $OneDriveAttachmentToSend.Identify
Invoke-WebRequest -Uri $OneDriveAttachmentToSend.'@microsoft.graph.downloadUrl' -OutFile $DownloadFileName
Ship-MessageREST -MailboxName $MailboxName  -AccessToken $AccessToken -ToRecipients @(New-EmailAddress -Handle person@area.com) -Topic "Daily Send" -Physique "See Attached" -Attachments @($DownloadFileName)

Full Supply Obtainable right here

On this instance the Get-OneDriveItemFromPath perform is used once more to get the main points of the One Drive file utilizing its pleasant relative path. The property that’s used this time is the @microsoft.graph.downloadUrl’ which is a preautheticated quick time period download URL that’s then utilized in Invoke-WebRequest to download the file from OneDrive to the native file system so it could possibly simply then be despatched as a daily file attachment in Ship-MessageREST.

Saving an Attachment from a Message to One Drive (Easy scripted download Attachment script modification)

Within the final instance I am taking a look at modifying my earlier script from this publish so as an alternative of saving the attachment to disk it as an alternative saves them to One Drive. I’ve used the easy add technique so this is able to imply the attachment measurement is restricted to four MB most (you would wish to make use of one other technique when you’ve got recordsdata which are bigger then this that want importing).

Import-Module Exch-Relaxation -Pressure

#Import-Module Exch-Relaxation -Pressure
$MailboxName = "gscales@datarumble.com"
$Topic = "Daily Export"
$ProcessedFolderPath = "InboxProcessed"
$OneDriveUploadFilePath = "/test"


##Get the Entry Token
$AccessToken =  Get-AccessToken -MailboxName $MailboxName  -ClientId 5471030d-f311-4c5d-91ef-74ca885463a7 -redirectUrl "urn:ietf:wg:oauth:2.0:oob" -ResourceURL graph.microsoft.com 
##Search the Inbox
$Filter = "IsRead eq false AND HasAttachments eq true AND Subject eq '" + $Topic + "'"
$Objects = Get-FolderItems -MailboxName $MailboxName -AccessToken $AccessToken -FolderPath Inbox -Filter $Filter
if($Objects -ne $null){
   if($Objects -is [system.array]){
         Write-Host ($Objects.Rely.ToString() + " Items Found ")
   }
   else{
        Write-Host "Found 1 item"
   }
   foreach ($merchandise in $Objects) {
        Write-Host ("Processing Item received " + $Merchandise.receivedDateTime)
        $merchandise
        Get-Attachments -MailboxName $MailboxName -ItemURI $merchandise.ItemRESTURI -MetaData -AccessToken $AccessToken | ForEach-Object{
            $connect = Invoke-DownloadAttachment -MailboxName $MailboxName -AttachmentURI $_.AttachmentRESTURI -AccessToken $AccessToken
            $attachBytes = [System.Convert]::FromBase64String($connect.ContentBytes)  
            $OneDriveFilePath = $OneDriveUploadFilePath + "/" + $connect.Identify.ToString()
      Invoke-UploadOneDriveItemToPath -AccessToken $AccessToken -MailboxName $MailboxName -OneDriveUploadFilePath $OneDriveFilePath -FileBytes $attachBytes
            write-host ("uploaded " + $OneDriveFilePath + " to one drive")
        }
        $UpdateProps = @()
        $UpdateProps += (Get-ItemProp -Identify IsRead -Worth true -NoQuotes)
        Replace-Message -MailboxName $MailboxName -AccessToken $AccessToken -ItemURI $merchandise.ItemRESTURI -StandardPropList $UpdateProps
        Transfer-Message -MailboxName $MailboxName -ItemURI $merchandise.ItemRESTURI -TargetFolderPath $ProcessedFolderPath -AccessToken $AccessToken               
   }
 
}
else{
    Write-Host "No Item found"
}

Full Supply Obtainable right here

The primary change on this script is within the attachment processing code the place the Invoke-UploadOneDriveItemToPath is used. This perform does a easy add of the file to OneDrive https://dev.onedrive.com/gadgets/upload_put.htm so the entire measurement of the file cannot exceed 4MB.

All of the scripts on this weblog require model 1.9 of the Exch-Relaxation module from the PowerShell gallery https://www.powershellgallery.com/packages/Exch-Relaxation/1.9

The OneDrive API provides much more performance that I am going to share with extra in future posts.

Leave a Reply