Using EWS impersonation and PowerShell to log into an Exchange Online Mailbox

 Below is very basic PowerShell sample that will log into a mailbox in Exchange Online with another account which has the right to impersonate other mailboxes in your tennant. This can be very useful when there is a need to connect to multiple mailboxes in Exchange Online to perform various tasks. Using this method will help (but not totally) mitigate being throttled by Exchange Online in the event you are preforming tasks against a large number of mailboxes

 

As stated the sample below is very basic and will Impersonate the desired mailbox and list some very basic information on the inbox It is a great start or foundation for any script you need to write where impersonation is necessary.

 

## Define UPN of the Account that has impersonation rights

$AccountWithImpersonationRights = "AccountWithImpersonationRights@contoso.onmicrosoft.com"

##Define the SMTP Address of the mailbox to impersonate

$MailboxToImpersonate = "MailboxToImpersonate@contoso.onmicrosoft.com"

## Load Exchange web services DLL

## Download here if not present: https://go.microsoft.com/fwlink/?LinkId=255472

$dllpath = "C:\Program Files\Microsoft\Exchange\Web Services\2.2\Microsoft.Exchange.WebServices.dll"

Import-Module $dllpath

## Set Exchange Version

$ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2013

## Create Exchange Service Object

$service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ExchangeVersion)

#Get valid Credentials using UPN for the ID that is used to impersonate mailbox

$psCred = Get-Credential

$creds = New-Object System.Net.NetworkCredential($psCred.UserName.ToString(),$psCred.GetNetworkCredential().password.ToString())

$service.Credentials = $creds

## Set the URL of the CAS (Client Access Server)

$service.AutodiscoverUrl($AccountWithImpersonationRights ,{$true})

##Login to Mailbox with Impersonation

Write-Host 'Using ' $AccountWithImpersonationRights ' to Impersonate ' $MailboxToImpersonate

$service.ImpersonatedUserId = New-Object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress,$MailboxToImpersonate );

#Connect to the Inbox and display basic statistics

$InboxFolder= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$ImpersonatedMailboxName)

$Inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$InboxFolder)

Write-Host 'Total Item count for Inbox:' $Inbox.TotalCount

Write-Host 'Total Items Unread:' $Inbox.UnreadCount