Skip to main content

EWS Basics Accessing and using Shared mailboxes

One of the most commonly asked and misunderstood things that people starting out using Exchange Web Services get wrong is accessing a Shared Mailbox or a Delegated Mailbox other then that of security principal (another way of saying credentials) you are authenticating with.

Autodiscover

One of the first confusion points is with Autodiscover, for people who aren't that familiar with Exchange its important to understand that all Autodisover does is gives you the endpoint to connect to for Exchange Web Services. Some people confuse using the following line

$service.AutodiscoverUrl("Mailbox@domain.com",{$true})

To mean all future EWS requests will go the mailbox you use here which isn't the case all this will do is return the most optimized endpoint for EWS request for that particular user.

Authentication

By default nobody has access to a Mailbox other then the owner of that mailbox, a common problem that people have is to believe they can use the admin account to access any users Mailbox content .  Access to a Mailbox needs to be granted via
  • Adding the user as a Delegate in Outlook or via the EWS Delegate operations
  • Giving the user full access using Add-MailboxPermission in the Exchange Management Shell
  • Grant EWS Impersonations rights on the Mailbox via the Application Impersonation RBAC role
  • Give Access to particular mailbox folder in Outlook or via Add-MailboxFolderPermssion
Accessing a Shared Mailboxes folder

To Access a Mailbox folder in EWS you need to know the EWSId of the folder, the one exception to this rule are the WellKnownFolders like the Inbox,Contacts,Calendar etc. With these WellKnowFolders you can tell EWS which folder you want in which mailbox without knowing the EWSId of that folder.

Eg to Access the Inbox in a Shared Mailbox you use the FolderId overload to define the folderId you want to access and then bind to that folder


$folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$MailboxName) 
$Inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)

If its a user created folder you want to access then this is where some complexity comes in, to access the folder you need to get the EWSId of that folder. The easiest way to do this would be to search for that folder within the target mailbox, however depending on what rights you have that this may or may not be a problem. But if you do have Full access or Impersonation rights to a Mailbox then to access a usercreated folder turn the folder you want to access into a path like \\Inbox\folder1\folder2 and you can then use a function like this


function Get-FolderFromPath{
 param (
   [Parameter(Position=0, Mandatory=$true)] [string]$FolderPath,
   [Parameter(Position=1, Mandatory=$true)] [string]$MailboxName,
   [Parameter(Position=2, Mandatory=$true)] [Microsoft.Exchange.WebServices.Data.ExchangeService]$service,
   [Parameter(Position=3, Mandatory=$false)] [Microsoft.Exchange.WebServices.Data.PropertySet]$PropertySet
    )
 process{
  ## Find and Bind to Folder based on Path  
  #Define the path to search should be seperated with \  
  #Bind to the MSGFolder Root  
  $folderid = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::MsgFolderRoot,$MailboxName)   
  $tfTargetFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)  
  #Split the Search path into an array  
  $fldArray = $FolderPath.Split("\") 
   #Loop through the Split Array and do a Search for each level of folder 
  for ($lint = 1; $lint -lt $fldArray.Length; $lint++) { 
         #Perform search based on the displayname of each folder level 
         $fvFolderView = new-object Microsoft.Exchange.WebServices.Data.FolderView(1) 
   if(![string]::IsNullOrEmpty($PropertySet)){
    $fvFolderView.PropertySet = $PropertySet
   }
         $SfSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.FolderSchema]::DisplayName,$fldArray[$lint]) 
         $findFolderResults = $service.FindFolders($tfTargetFolder.Id,$SfSearchFilter,$fvFolderView) 
         if ($findFolderResults.TotalCount -gt 0){ 
             foreach($folder in $findFolderResults.Folders){ 
                 $tfTargetFolder = $folder                
             } 
         } 
         else{ 
             Write-host ("Error Folder Not Found check path and try again")  
             $tfTargetFolder = $null  
             break  
         }     
     }  
  if($tfTargetFolder -ne $null){
   return [Microsoft.Exchange.WebServices.Data.Folder]$tfTargetFolder
  }
  else{
   throw ("Folder Not found")
  }
 }
}

Once you have the EWSId of the Folder you can use that in FindItems Operation or another other EWS operation that takes a FolderId to do what you want. For Example

Sending Email As a Shared Mailbox

To send a message as another user you need to first have either SendAS permissions to that Mailbox or Send on Behalf off (the latter will mean the message will be marked as Sent On Behalf)

The first thing in you code you want to do is bind to the SentItems folder of the Mailbox you want to send as eg

$folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::SentItems,$MailboxName)   
$SentItems = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)

Then when you create a message to Send set the From address to the Mailbox you want to SendAs and set the SentItems FolderId to the Target mailbox so a copy of what you will be sending will be saved to the SentItems folder of that mailbox eg


function Send-EWSMessage  {
     param( 
             [Parameter(Position=0, Mandatory=$true)] [string]$MailboxName,
  [Parameter(Mandatory=$true)] [System.Management.Automation.PSCredential]$Credentials,
  [Parameter(Position=2, Mandatory=$false)] [switch]$useImpersonation,
  [Parameter(Position=3, Mandatory=$false)] [string]$url,
  [Parameter(Position=6, Mandatory=$true)] [String]$To,
  [Parameter(Position=7, Mandatory=$true)] [String]$Subject,
  [Parameter(Position=8, Mandatory=$true)] [String]$Body,
  [Parameter(Position=9, Mandatory=$false)] [String]$Attachment
                )  
  Begin
 {
  if($url){
   $service = Connect-Exchange -MailboxName $MailboxName -Credentials $Credentials -url $url 
  }
  else{
   $service = Connect-Exchange -MailboxName $MailboxName -Credentials $Credentials
  }
  if($useImpersonation.IsPresent){
   $service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName) 
  }
  $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::SentItems,$MailboxName)   
  $SentItems = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)
  $EmailMessage = New-Object Microsoft.Exchange.WebServices.Data.EmailMessage -ArgumentList $service  
  $EmailMessage.Subject = $Subject
  #Add Recipients    
  $EmailMessage.ToRecipients.Add($To)  
  $EmailMessage.Body = New-Object Microsoft.Exchange.WebServices.Data.MessageBody  
  $EmailMessage.Body.BodyType = [Microsoft.Exchange.WebServices.Data.BodyType]::HTML  
  $EmailMessage.Body.Text = "Body"  
  $EmailMessage.From = $MailboxName
  if($Attachment)
  {   
   $EmailMessage.Attachments.AddFileAttachment($Attachment)
  }
  $EmailMessage.SendAndSaveCopy($SentItems.Id) 
  
 }
}




Popular posts from this blog

The MailboxConcurrency limit and using Batching in the Microsoft Graph API

If your getting an error such as Application is over its MailboxConcurrency limit while using the Microsoft Graph API this post may help you understand why. Background   The Mailbox  concurrency limit when your using the Graph API is 4 as per https://docs.microsoft.com/en-us/graph/throttling#outlook-service-limits . This is evaluated for each app ID and mailbox combination so this means you can have different apps running under the same credentials and the poor behavior of one won't cause the other to be throttled. If you compared that to EWS you could have up to 27 concurrent connections but they are shared across all apps on a first come first served basis. Batching Batching in the Graph API is a way of combining multiple requests into a single HTTP request. Batching in the Exchange Mail API's EWS and MAPI has been around for a long time and its common, for email Apps to process large numbers of smaller items for a variety of reasons.  Batching in the Graph is limited to a m

Sending a Message in Exchange Online via REST from an Arduino MKR1000

This is part 2 of my MKR1000 article, in this previous post  I looked at sending a Message via EWS using Basic Authentication.  In this Post I'll look at using the new Outlook REST API  which requires using OAuth authentication to get an Access Token. The prerequisites for this sketch are the same as in the other post with the addition of the ArduinoJson library  https://github.com/bblanchon/ArduinoJson  which is used to parse the Authentication Results to extract the Access Token. Also the SSL certificates for the login.windows.net  and outlook.office365.com need to be uploaded to the devices using the wifi101 Firmware updater. To use Token Authentication you need to register an Application in Azure https://msdn.microsoft.com/en-us/office/office365/howto/add-common-consent-manually  with the Mail.Send permission. The application should be a Native Client app that use the Out of Band Callback urn:ietf:wg:oauth:2.0:oob. You need to authorize it in you tenant (eg build a small ap

How to test SMTP using Opportunistic TLS with Powershell and grab the public certificate a SMTP server is using

Most email services these day employ Opportunistic TLS when trying to send Messages which means that wherever possible the Messages will be encrypted rather then the plain text legacy of SMTP.  This method was defined in RFC 3207 "SMTP Service Extension for Secure SMTP over Transport Layer Security" and  there's a quite a good explanation of Opportunistic TLS on Wikipedia  https://en.wikipedia.org/wiki/Opportunistic_TLS .  This is used for both Server to Server (eg MTA to MTA) and Client to server (Eg a Message client like Outlook which acts as a MSA) the later being generally Authenticated. Basically it allows you to have a normal plain text SMTP conversation that is then upgraded to TLS using the STARTTLS verb. Not all servers will support this verb so if its not supported then a message is just sent as Plain text. TLS relies on PKI certificates and the administrative issue s that come around certificate management like expired certificates which is why I wrote th
All sample scripts and source code is provided by for illustrative purposes only. All examples are untested in different environments and therefore, I cannot guarantee or imply reliability, serviceability, or function of these programs.

All code contained herein is provided to you "AS IS" without any warranties of any kind. The implied warranties of non-infringement, merchantability and fitness for a particular purpose are expressly disclaimed.