Monday, June 18, 2012

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  

2 comments:

Max said...

this helped a lot in setting ext properties of message (charset namely). thank you.

Jeff Girotto said...

I'm running the code snippet below to try to retrieve recurring appointments and receive the following error: "Exception calling "FindItems" with "3" argument(s): "Custom properties cannot be specified using property tags. The GUID and Id/Name combination must be used instead."

Can you tell me what I'm doing wrong? I've tried various values instead of 0x80C9 such as 33315 or 0x80C9000B. I'm thinking I'm just not doing it right.


$service.AutodiscoverUrl($PrimarySMTPAddress,{$true})
$ISRECURRING = New-Object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x80C9,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Boolean);

$SearchFilterIsRecurring = New-Object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo($ISRECURRING, $true)
$SearchFilterAppt = New-Object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.ItemSchema]::ItemClass, "IPM.Appointment")

# Create collection of filters
$sfCollection = New-Object Microsoft.Exchange.WebServices.Data.SearchFilter+SearchFilterCollection([Microsoft.Exchange.WebServices.Data.LogicalOperator]::And);
$sfCollection.add($SearchFilterIsRecurring)
$sfCollection.add($SearchFilterAppt)

# Create View - add firstclassproperties and custom IsRecurring property
$ItemView = New-Object Microsoft.Exchange.WebServices.Data.ItemView(10000)
$psPropertySet = new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)
$psPropertySet.Add($ISRECURRING);
$ItemView.PropertySet = $psPropertySet;

$fiFindItems = $service.findItems([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Calendar,$sfCollection,$ItemView)

foreach($Item in $fiFindItems.Items){
$Items.Subject + "`t" + $Item.DateTimeReceived
}