Skip to main content

EWS Managed API and Powershell How-To Series Part 10 Message Classifications

In this part of the how-to series I'm going to look at message classifications and how you can make use of these in your EWS scripts. Message classification was introduced in Exchange 2007 to comply with Organization policies and regulations.

Technical stuff

The extended MAPI properties and X-headers that are used for classification are documented in the following protocol document http://msdn.microsoft.com/en-us/library/ee217686%28v=EXCHG.80%29.aspx .  

Lets go over then quickly


PidLidClassificationGuid is the extended property that contains the GUID of the classification that has been applied to a message. To work out these GUID's you need to use the Exchange Management Shell Get-MessageClassification cmdlet eg


So the ClassificationID = PidLidClassificationGuid

PidLidClassified : Is a Boolean property that tells if a message has been classified

PidLidClassificationDescription: The property either represents the Recipient Description on a message that is received or the Sender Description on a message that is sent.

PidLidClassification: = The displyName of the classification

Sending a Classified Message

To send a classified message with EWS you need to set these Extended Mapi properties the two Mandatory properties you need to set are the  PidLidClassified and PidLidClassificationGuid Exchange should handle the other properties for you. An example of sending a classified message would look like

  1. $message = New-Object Microsoft.Exchange.WebServices.Data.EmailMessage($service)  
  2. $message.Subject = "Test"  
  3. $message.Body = "Test 123"  
  4. $message.ToRecipients.Add("user@domain.com")  
  5. $PidLidClassificationGuid = New-Object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition([Microsoft.Exchange.WebServices.Data.DefaultExtendedPropertySet]::Common, 34232,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::String);  
  6. $message.SetExtendedProperty($PidLidClassificationGuid"e67e794b-f6d1-4c8f-9f63-1118d21dafa6");  
  7. $PidLidClassified = New-Object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition([Microsoft.Exchange.WebServices.Data.DefaultExtendedPropertySet]::Common,34229,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Boolean);  
  8. $message.SetExtendedProperty($PidLidClassified$true);  
  9. $message.Send.Invoke()  

Finding Classified Messages

To search for classified messages within a mailbox you need to create a searchfilter based around the parameters you want to search on eg. if you have multiple classifications and you just want to limit your search to all classified messages (not just one type of classification) then you can use an exists Search filter to search for only those messages where the classification properties have been set for example

  1. $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$MailboxName)     
  2. $Inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)  
  3.   
  4. $psPropertySet = new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)    
  5. $PidLidClassificationGuid = New-Object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition([Microsoft.Exchange.WebServices.Data.DefaultExtendedPropertySet]::Common, 34232,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::String);  
  6. $PidLidClassified = New-Object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition([Microsoft.Exchange.WebServices.Data.DefaultExtendedPropertySet]::Common,0x85B6,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::String);  
  7.   
  8. $psPropertySet.Add($PidLidClassificationGuid)  
  9. $psPropertySet.Add($PidLidClassified)  
  10.   
  11. $ItemSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+Exists($PidLidClassificationGuid)  
  12. $ivItemView = New-Object Microsoft.Exchange.WebServices.Data.ItemView(1000)    
  13. $ivItemView.PropertySet = $psPropertySet  
  14.   
  15. do{    
  16.     $fiResults = $Inbox.findItems($ItemSearchFilter,$ivItemView)    
  17.     foreach($Item in $fiResults.Items){  
  18.         $classificationGUID = $null  
  19.         [Void]$Item.TryGetProperty($PidLidClassificationGuid,[ref]$classificationGUID)  
  20.         $Classification = $null  
  21.         [Void]$Item.TryGetProperty($PidLidClassified,[ref]$Classification)  
  22.         "Subject : " + $Item.Subject  
  23.         "Received : " + $Item.DateTimeReceived  
  24.         "Classification : " + $Classification  
  25.         "ClassificationGUID : " + $classificationGUID  
  26.     }             
  27.     $ivItemView.Offset += $fiResults.Items.Count    
  28. }while($fiResults.MoreAvailable -eq $true)  

If you want to search all folders in a mailbox for message with a particular classification you can either create a searchfilter based on the ClassificationGUID eg
  1. $sfSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo($PidLidClassificationGuid"e67e794b-f6d1-4c8f-9f63-1118d21dafa6")  
Or use the above code and do some client side filtering. Depending on the size of the result sets involved you may find doing client side filtering gives better performance the doing a string match on an un-indexed property. Here is a sample for searching all folders in a mailbox for messages with a particular Message classification GUID and doing client side filter on that match and then producing a CSV report of the location of these messages.

  1. $RptObjColl = @()  
  2. $MailboxName = "user@domain.com"  
  3.   
  4. $guid = "e67e794b-f6d1-4c8f-9f63-1118d21dafa6"  
  5.   
  6. ## Load Managed API dll    
  7. Add-Type -Path "C:\Program Files\Microsoft\Exchange\Web Services\1.2\Microsoft.Exchange.WebServices.dll"    
  8.     
  9. ## Set Exchange Version    
  10. $ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP1    
  11.     
  12. ## Create Exchange Service Object    
  13. $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ExchangeVersion)    
  14.     
  15. ## Set Credentials to use two options are availible Option1 to use explict credentials or Option 2 use the Default (logged On) credentials    
  16.     
  17. #Credentials Option 1 using UPN for the windows Account    
  18. $creds = New-Object System.Net.NetworkCredential("glen@domain.com","passwd")     
  19. $service.Credentials = $creds        
  20.     
  21. #Credentials Option 2    
  22. #service.UseDefaultCredentials = $true    
  23.     
  24. ## Choose to ignore any SSL Warning issues caused by Self Signed Certificates    
  25.     
  26. [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}    
  27.     
  28. ## Set the URL of the CAS (Client Access Server) to use two options are availbe to use Autodiscover to find the CAS URL or Hardcode the CAS to use    
  29.     
  30. #CAS URL Option 1 Autodiscover    
  31. $service.AutodiscoverUrl($MailboxName,{$true})    
  32. "Using CAS Server : " + $Service.url     
  33.      
  34. #CAS URL Option 2 Hardcoded    
  35.     
  36. #$uri=[system.URI] "https://casservername/ews/exchange.asmx"    
  37. #$service.Url = $uri      
  38.     
  39. ## Optional section for Exchange Impersonation    
  40.     
  41. #$service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName)   
  42.   
  43. #Define Function to convert String to FolderPath      
  44. function ConvertToString($ipInputString){      
  45.     $Val1Text = ""      
  46.     for ($clInt=0;$clInt -lt $ipInputString.length;$clInt++){      
  47.             $Val1Text = $Val1Text + [Convert]::ToString([Convert]::ToChar([Convert]::ToInt32($ipInputString.Substring($clInt,2),16)))      
  48.             $clInt++      
  49.     }      
  50.     return $Val1Text      
  51. }     
  52.   
  53. $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::MsgFolderRoot,$MailboxName)     
  54. $MsgRoot = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)  
  55.   
  56. $fvFolderView =  New-Object Microsoft.Exchange.WebServices.Data.FolderView(1000)    
  57. #Deep Transval will ensure all folders in the search path are returned   
  58.    
  59. $fvFolderView.Traversal = [Microsoft.Exchange.WebServices.Data.FolderTraversal]::Deep;    
  60. $ivItemView = New-Object Microsoft.Exchange.WebServices.Data.ItemView(1000)    
  61.   
  62.   
  63. $psPropertySet = new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)    
  64. $PidLidClassificationGuid = New-Object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition([Microsoft.Exchange.WebServices.Data.DefaultExtendedPropertySet]::Common, 34232,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::String);  
  65. $PidLidClassified = New-Object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition([Microsoft.Exchange.WebServices.Data.DefaultExtendedPropertySet]::Common,34229,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Boolean);  
  66.   
  67. $psPropertySet.Add($PidLidClassificationGuid)  
  68. $psPropertySet.Add($PidLidClassified)  
  69.   
  70. $FPropertySet = new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)    
  71.   
  72. $PR_Folder_Path = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(26293, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::String);  
  73. $FPropertySet.add($PR_Folder_Path)  
  74.   
  75. $fvFolderView.PropertySet = $FPropertySet  
  76. $fiResult = $null    
  77. #The Do loop will handle any paging that is required if there are more the 1000 folders in a mailbox   
  78. $rptHash = @{}  
  79. $ItemSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+Exists($PidLidClassificationGuid)  
  80. do {   
  81.     $ivItemView = New-Object Microsoft.Exchange.WebServices.Data.ItemView(1000)    
  82.     $ivItemView.PropertySet = $psPropertySet  
  83.     $fiResult = $Service.FindFolders($folderid,$sfSearchFilter,$fvFolderView)    
  84.     foreach($ffFolder in $fiResult.Folders){    
  85.     "Processing Folder : " + $ffFolder.displayName  
  86.         $foldpathval = $null      
  87.         #Try to get the FolderPath Value and then covert it to a usable String       
  88.         if ($ffFolder.TryGetProperty($PR_Folder_Path,[ref] $foldpathval))      
  89.         {      
  90.             $binarry = [Text.Encoding]::UTF8.GetBytes($foldpathval)      
  91.             $hexArr = $binarry | ForEach-Object { $_.ToString("X2") }      
  92.             $hexString = $hexArr -join ''      
  93.             $hexString = $hexString.Replace("FEFF""5C00")      
  94.             $fpath = ConvertToString($hexString)      
  95.         }      
  96.         if($ffFolder.TotalCount -gt 0){  
  97.             $fiResults = $null  
  98.             $updateColl = @()  
  99.             do{    
  100.                 $fiResults = $ffFolder.findItems($ItemSearchFilter,$ivItemView)  
  101.                 $rptobj = "" | select FolderPath,DateTimeRecieved,Subject,Size,MessageGUID   
  102.                 foreach($Item in $fiResults.Items){    
  103.                     $messageGuid = $null  
  104.                     if($Item.TryGetProperty($PidLidClassificationGuid,[ref]$messageGuid)){  
  105.                         if($messageGuid -eq $guid){  
  106.                             $rptobj.MessageGUID = $messageGuid  
  107.                             $rptobj.FolderPath = $fpath  
  108.                             $rptobj.DateTimeRecieved = $Item.DateTimeReceived  
  109.                             $rptobj.Subject = $Item.Subject  
  110.                             $rptobj.Size = $Item.Size   
  111.                             $RptObjColl += $rptobj  
  112.                         }  
  113.                     }  
  114.                 }    
  115.                 $ivItemView.Offset += $fiResults.Items.Count    
  116.             }while($fiResults.MoreAvailable -eq $true)  
  117.         }           
  118.     }   
  119.     $fvFolderView.Offset += $fiResult.Folders.Count  
  120. }while($fiResult.MoreAvailable -eq $true)   
  121.   
  122. $RptObjColl | Export-Csv -NoTypeInformation c:\Temp\classificationReport.csv  

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 Gr...

Sending a MimeMessage via the Microsoft Graph using the Graph SDK, MimeKit and MSAL

One of the new features added to the Microsoft Graph recently was the ability to create and send Mime Messages (you have been able to get Message as Mime for a while). This is useful in a number of different scenarios especially when trying to create a Message with inline Images which has historically been hard to do with both the Graph and EWS (if you don't use MIME). It also opens up using SMIME for encryption and a more easy migration path for sending using SMTP in some apps. MimeKit is a great open source library for parsing and creating MIME messages so it offers a really easy solution for tackling this issue. The current documentation on Send message via MIME lacks any real sample so I've put together a quick console app that use MSAL, MIME kit and the Graph SDK to send a Message via MIME. As the current Graph SDK also doesn't support sending via MIME either there is a workaround for this in the future my guess is this will be supported.

Export calendar Items to a CSV file using Microsoft Graph and Powershell

For the last couple of years the most constantly popular post by number of views on this blog has been  Export calendar Items to a CSV file using EWS and Powershell closely followed by the contact exports scripts. It goes to show this is just a perennial issue that exists around Mail servers, I think the first VBS script I wrote to do this type of thing was late 90's against Exchange 5.5 using cdo 1.2. Now it's 2020 and if your running Office365 you should really be using the Microsoft Graph API to do this. So what I've done is create a PowerShell Module (and I made it a one file script for those that are more comfortable with that format) that's a port of the EWS script above that is so popular. This script uses the ADAL library for Modern Authentication (which if you grab the library from the PowerShell gallery will come down with the module). Most EWS properties map one to one with the Graph and the Graph actually provides better information on recurrences then...
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.