Created
November 2, 2018 15:22
-
-
Save poiriersimon/3f8299caac9c35cb99e427e674820992 to your computer and use it in GitHub Desktop.
Connect EXO EWS With User Cred OAUTH
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#You need AzureAD Module (Save-Module AzureAD -Path C:\temp) | |
#You need EWS API 2.2 (www.microsoft.com/en-us/download/details.aspx?id=35371) | |
$UserPrincipalName = "user@TENANTNAME.onmicrosoft.com" | |
$resourceUri = "https://outlook.office365.com" | |
$AzureADDLLPath = "C:\Temp\AzureAD" | |
#EWSEditor ClientId used since it was already registered with the right permission | |
$clientid = "0e4bf2e2-aa7d-46e8-aa12-263adeb3a62b" | |
$redirectUri = "https://microsoft.com/EwsEditor" | |
$AuthAuthority = "https://login.windows.net/common" | |
# Load ADAL Assemblies | |
$adal = $AzureADDLLPath + "\Microsoft.IdentityModel.Clients.ActiveDirectory.dll" | |
[System.Reflection.Assembly]::LoadFrom($adal) | Out-Null | |
$authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $AuthAuthority | |
$PromptBehavior = [Microsoft.IdentityModel.Clients.ActiveDirectory.PromptBehavior]::Auto | |
$platformParam = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.PlatformParameters" -ArgumentList $PromptBehavior | |
$userId = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifier" -ArgumentList $UserPrincipalName, "OptionalDisplayableId" | |
$authResult = $authContext.AcquireTokenAsync($resourceUri, $clientId, $redirectUri, $platformParam, $userId) | |
#Load EWS DLL | |
Add-Type -Path "C:\Program Files\Microsoft\Exchange\Web Services\2.2\Microsoft.Exchange.WebServices.dll" -ErrorAction Stop | |
#Build EWS Service and Credential | |
$Service = new-object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2013_SP1); | |
$service.Credentials = new-object Microsoft.Exchange.WebServices.Data.OAuthCredentials($authResult.result.CreateAuthorizationHeader()) | |
#Build EWS URL | |
$URL = "$($resourceUri)/ews/exchange.asmx" | |
$service.Url = [system.URI] $URL | |
#Send EWS request to get the last 100 emails | |
$inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,[Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox) | |
[array]$Allmails = $inbox.FindItems(100) | |
$Allmails | select Subject |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment