Skip to main content

Finding RMS Items in a Mailbox using EWS

If you want to search for emails that have been protected using AD Rights Managed Service using EWS there are a few challenges. How RMS works with Email it is documented in the following Exchange Protocol document https://msdn.microsoft.com/en-us/library/cc463909(v=exchg.80).aspx. The important part when it comes to searching is PidNameContentClass property https://msdn.microsoft.com/en-us/library/office/cc839681.aspx which on RMS messages gets set to rpmsg.message. So to search for this Internet Header you can use a SearchFilter like the following to define the ExtendProperty to search folder

$contentclassIh = New-Object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition([Microsoft.Exchange.WebServices.Data.DefaultExtendedPropertySet]::InternetHeaders,"content-class",[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::String);  
$sfItemSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo($contentclassIh,"rpmsg.message") 

Putting it together in a script that searches a Folder in a Mailbox based on a MailboxName and FolderPath This script is on GitHub https://github.com/gscales/Powershell-Scripts/blob/master/GetRMSItems.ps1  (An important point to note while you can find email that has been protected using RMS with EWS you won't be able to read the encrypted contents using EWS).

function Get-RMSItems{
    param
 ( 
     [Parameter(Position=0, Mandatory=$true)] [string]$MailboxName,
  [Parameter(Position=1, Mandatory=$true)] [System.Management.Automation.PSCredential]$Credentials,
  [Parameter(Position=2, Mandatory=$true)] [String]$FolderPath

 )
 begin
 {
  $service = connect-exchange -Mailbox $MailboxName -Credentials $Credentials
  $Folder = Get-FolderFromPath -FolderPath $FolderPath -MailboxName $MailboxName -service $service 
  $contentclassIh = New-Object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition([Microsoft.Exchange.WebServices.Data.DefaultExtendedPropertySet]::InternetHeaders,"content-class",[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::String);  
  $sfItemSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo($contentclassIh,"rpmsg.message") 
  #Define ItemView to retrive just 1000 Items    
  $ivItemView =  New-Object Microsoft.Exchange.WebServices.Data.ItemView(1000)    
  $fiItems = $null    
  do{    
      $fiItems = $service.FindItems($Folder.Id,$sfItemSearchFilter,$ivItemView)    
      #[Void]$service.LoadPropertiesForItems($fiItems,$psPropset)  
      foreach($Item in $fiItems.Items){      
    Write-Output $Item
      }    
      $ivItemView.Offset += $fiItems.Items.Count    
  }while($fiItems.MoreAvailable -eq $true)  
 
 }
}

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")
  }
 }
}

function ConvertToString($ipInputString){  
    $Val1Text = ""  
    for ($clInt=0;$clInt -lt $ipInputString.length;$clInt++){  
            $Val1Text = $Val1Text + [Convert]::ToString([Convert]::ToChar([Convert]::ToInt32($ipInputString.Substring($clInt,2),16)))  
            $clInt++  
    }  
    return $Val1Text  
}

One last sample that does a statistics report of all RMS items in a Mailbox using a SearchFilter on the AllItems Search Folder (which is created by the Outlook Desktop client) this outputs a report of the RMS Items and the size of those item in each folder that looks like


This script is on GitHub at https://github.com/gscales/Powershell-Scripts/blob/master/GetRMSItems.ps1

function ConvertToString($ipInputString){  
    $Val1Text = ""  
    for ($clInt=0;$clInt -lt $ipInputString.length;$clInt++){  
            $Val1Text = $Val1Text + [Convert]::ToString([Convert]::ToChar([Convert]::ToInt32($ipInputString.Substring($clInt,2),16)))  
            $clInt++  
    }  
    return $Val1Text  
} 

function Get-RMSItems-AllItemSearch{
    param
 ( 
     [Parameter(Position=0, Mandatory=$true)] [string]$MailboxName,
  [Parameter(Position=1, Mandatory=$true)] [System.Management.Automation.PSCredential]$Credentials

 )
 begin
 {
  $FolderCache = @{}
  $service = connect-exchange -Mailbox $MailboxName -Credentials $Credentials
  $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::MsgFolderRoot,$MailboxName)  
  $MsgRoot = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)
  GetFolderPaths -FolderCache $FolderCache -service $service -rootFolderId $MsgRoot.Id
  $PR_FOLDER_TYPE = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(13825,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Integer);
  $folderidcnt = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Root,$MailboxName)
  $fvFolderView =  New-Object Microsoft.Exchange.WebServices.Data.FolderView(1000)
  $fvFolderView.Traversal = [Microsoft.Exchange.WebServices.Data.FolderTraversal]::Shallow;
  $sf1 = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo($PR_FOLDER_TYPE,"2")
  $sf2 = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.FolderSchema]::DisplayName,"allitems")
  $sfSearchFilterCol = new-object  Microsoft.Exchange.WebServices.Data.SearchFilter+SearchFilterCollection([Microsoft.Exchange.WebServices.Data.LogicalOperator]::And)
  $sfSearchFilterCol.Add($sf1)
  $sfSearchFilterCol.Add($sf2)
  $fiResult = $Service.FindFolders($folderidcnt,$sfSearchFilterCol,$fvFolderView)
  $fiItems = $null
  $RptCollection = @{}
  $ItemView = New-Object Microsoft.Exchange.WebServices.Data.ItemView(1000)
  if($fiResult.Folders.Count -eq 1)
  {
   $Folder = $fiResult.Folders[0]
      $contentclassIh = New-Object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition([Microsoft.Exchange.WebServices.Data.DefaultExtendedPropertySet]::InternetHeaders,"content-class",[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::String);  
   $sfItemSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo($contentclassIh,"rpmsg.message") 
   #Define ItemView to retrive just 1000 Items    
   $ivItemView =  New-Object Microsoft.Exchange.WebServices.Data.ItemView(1000)    
   $fiItems = $null    
   do{    
       $fiItems = $service.FindItems($Folder.Id,$sfItemSearchFilter,$ivItemView)    
        #[Void]$service.LoadPropertiesForItems($fiItems,$psPropset)  
       foreach($Item in $fiItems.Items){     
     if($FolderCache.ContainsKey($Item.ParentFolderId.UniqueId))
     {
      if($RptCollection.ContainsKey($FolderCache[$Item.ParentFolderId.UniqueId]))
      {
       $RptCollection[$FolderCache[$Item.ParentFolderId.UniqueId]].TotalItems++
       $RptCollection[$FolderCache[$Item.ParentFolderId.UniqueId]].TotalSize+= $Item.Size
      }
      else
      {
       $fldRptobj = "" | Select FolderName,TotalItems,TotalSize
       $fldRptobj.FolderName = $FolderCache[$Item.ParentFolderId.UniqueId]
       $fldRptobj.TotalItems = 1
       $fldRptobj.TotalSize = $Item.Size 
       $RptCollection.Add($fldRptobj.FolderName,$fldRptobj)
      }     
     }
       }    
       $ivItemView.Offset += $fiItems.Items.Count    
   }while($fiItems.MoreAvailable -eq $true)    
   
  }
  write-output $RptCollection.Values
 }
 

}

function GetFolderPaths
{
 param (
      [Parameter(Position=0, Mandatory=$true)] [Microsoft.Exchange.WebServices.Data.FolderId]$rootFolderId,
   [Parameter(Position=1, Mandatory=$true)] [Microsoft.Exchange.WebServices.Data.ExchangeService]$service,
   [Parameter(Position=2, Mandatory=$true)] [PSObject]$FolderCache,
   [Parameter(Position=3, Mandatory=$false)] [String]$FolderPrefix
    )
 process{
 #Define Extended properties  
 $PR_FOLDER_TYPE = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(13825,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Integer);  
 $PR_MESSAGE_SIZE_EXTENDED = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(3592, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Long);
 #Define the FolderView used for Export should not be any larger then 1000 folders due to throttling  
 $fvFolderView =  New-Object Microsoft.Exchange.WebServices.Data.FolderView(1000)  
 #Deep Transval will ensure all folders in the search path are returned  
 $fvFolderView.Traversal = [Microsoft.Exchange.WebServices.Data.FolderTraversal]::Deep;  
 $psPropertySet = new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)  
 $PR_Folder_Path = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(26293, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::String);  
 #Add Properties to the  Property Set  
 $psPropertySet.Add($PR_Folder_Path);  
 $psPropertySet.Add($PR_MESSAGE_SIZE_EXTENDED)
 $fvFolderView.PropertySet = $psPropertySet;  
 #The Search filter will exclude any Search Folders  
 $sfSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo($PR_FOLDER_TYPE,"1")  
 $fiResult = $null  
 #The Do loop will handle any paging that is required if there are more the 1000 folders in a mailbox  
 do 
 {  
     $fiResult = $service.FindFolders($rootFolderId,$sfSearchFilter,$fvFolderView)  
     foreach($ffFolder in $fiResult.Folders){
         #Try to get the FolderPath Value and then covert it to a usable String 
   $foldpathval = $null
         if ($ffFolder.TryGetProperty($PR_Folder_Path,[ref] $foldpathval))  
         {  
             $binarry = [Text.Encoding]::UTF8.GetBytes($foldpathval)  
             $hexArr = $binarry | ForEach-Object { $_.ToString("X2") }  
             $hexString = $hexArr -join ''  
             $hexString = $hexString.Replace("FEFF", "5C00")  
             $fpath = ConvertToString($hexString)  
         }
   if($FolderCache.ContainsKey($ffFolder.Id.UniqueId) -eq $false)
   {
    if ([string]::IsNullOrEmpty($FolderPrefix)){
     $FolderCache.Add($ffFolder.Id.UniqueId,($fpath)) 
    }
    else
    {
     $FolderCache.Add($ffFolder.Id.UniqueId,("\" + $FolderPrefix + $fpath)) 
    }
   }
     } 
     $fvFolderView.Offset += $fiResult.Folders.Count
 }while($fiResult.MoreAvailable -eq $true)  
 }
}


Popular posts from this blog

Testing and Sending email via SMTP using Opportunistic TLS and oAuth in Office365 with PowerShell

As well as EWS and Remote PowerShell (RPS) other mail protocols POP3, IMAP and SMTP have had OAuth authentication enabled in Exchange Online (Official announcement here ). A while ago I created  this script that used Opportunistic TLS to perform a Telnet style test against a SMTP server using SMTP AUTH. Now that oAuth authentication has been enabled in office365 I've updated this script to be able to use oAuth instead of SMTP Auth to test against Office365. I've also included a function to actually send a Message. Token Acquisition  To Send a Mail using oAuth you first need to get an Access token from Azure AD there are plenty of ways of doing this in PowerShell. You could use a library like MSAL or ADAL (just google your favoured method) or use a library less approach which I've included with this script . Whatever way you do this you need to make sure that your application registration  https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-

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

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.