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

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