Skip to main content

Using the ExcludesBitmask SearchFilter\ Restriction in EWS

Complex properties are one of the more challenging elements when it comes to developing with Exchange and bitwise properties are one of the more challenging property types you may need to deal with. The most common bitwise property in Exchange you may access/use is the PR_MessageFlags property https://msdn.microsoft.com/en-us/library/ee160304(v=exchg.80).aspx . If you look at this property on a Message that you received you might see something like


What the  ExcludesBitmask SearchFilter/Restriction in EWS allows you to do is create a search where you can specifically exclude messages because they have one of these bitmask values set. Eg you might want to exclude Draft messages from your search or maybe you want to exclude any messages that where SentBy you in the Inbox. You can also use this Search Filter with the Not filter which Negates the restriction so if I created a Searchfilter to excluded all messages with the MSGFlag_HasAttached then negated that with the Not filter I would then only get the message where the MSGFlag_HasAttached bit-wise is set.

Using this the EWS Managed API is pretty simple you first define the property you want to search on and then create a SearchFilter using this property and the Bitwise Value as the variable eg

ExtendedPropertyDefinition PR_MESSAGE_FLAGS = new ExtendedPropertyDefinition(0x0E07,MapiPropertyType.Integer);
SearchFilter ExcludeDraft = new SearchFilter.ExcludesBitmask(PR_MESSAGE_FLAGS, 8);

This creates a SearchFilter that excludes draft messages, If you want to Negate that you can use

SearchFilter JustDrafts = new SearchFilter.Not(ExcludeDraft);

Which would then create a filter that just retrieved draft messages.

In PowerShell you can write a function like the following

function Query-MessageFlag  {
     param( 
             [Parameter(Position=0, Mandatory=$true)] [string]$MailboxName,
  [Parameter(Position=1, Mandatory=$true)] [System.Management.Automation.PSCredential]$Credentials,
  [Parameter(Position=2, Mandatory=$false)] [switch]$useImpersonation,
  [Parameter(Position=3, Mandatory=$false)] [string]$url,
                [Parameter(Position=4, Mandatory=$true)] [Int32]$Flag,
  [Parameter(Position=5, Mandatory=$true)] [string]$FolderPath,
  [Parameter(Position=6, Mandatory=$false)] [switch]$Negate,
  [Parameter(Position=7, Mandatory=$false)] [switch]$SummaryOnly
    )  
  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 = FolderIdFromPath -FolderPath $FolderPath -SmtpAddress $MailboxName
  if($folderId -ne $null){
   $Folder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderId) 
   Write-Host ("Folder Name : " + $Folder.DisplayName)
   $PR_MESSAGE_FLAGS = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x0E07,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Integer); 
   $sfItemSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+ExcludesBitmask($PR_MESSAGE_FLAGS, $Flag) 
                        if($Negate.IsPresent){
    $sfItemSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+Not($sfItemSearchFilter)
   }   
   if(!$SummaryOnly.IsPresent){
    $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-Host($Item.DateTimeReceived.ToString() + " : " + $Item.Subject)       
     }    
     $ivItemView.Offset += $fiItems.Items.Count    
    }while($fiItems.MoreAvailable -eq $true) 
   }
   else
   {
     $ivItemView =  New-Object Microsoft.Exchange.WebServices.Data.ItemView(1)
     $fiItems = $service.FindItems($Folder.Id,$sfItemSearchFilter,$ivItemView)  
     Write-Host ("Total Items : " + $fiItems.TotalCount)
   }
  }
 }
}

The above function comes from the following script on Github https://github.com/gscales/Powershell-Scripts/blob/master/ExcludeQuery.ps1 demonstrates how to either get Items or a Summary count of those Items based on a bitwise flag exclusion or a negation of that exclusion. Again some examples may be in order

Example 1 Search for messages in the Inbox not sent from you using the mfFromMe bitwise flag

Query-MessageFlag -MailboxName user@domain.com -FolderPath '\Inbox' -Flag 32 -SummaryOnly

Example 2 Search for messages in the Inbox  sent from you using the mfFromMe bitwise flag (this is using a Negate filter)

Query-MessageFlag -MailboxName user@domain.com -FolderPath '\Inbox' -Flag 32 -SummaryOnly -Negate

Example 3 Search for messages with the Attach Flag set in the Inbox mfHasAttach

Query-MessageFlag -MailboxName user@domain.com -FolderPath '\Inbox' -Flag 16 -SummaryOnly -Negate

Example 4 Search for message with Read Recipient flag mfNotifyRead and Negate that

Query-MessageFlag -MailboxName user@domain.com -FolderPath '\Inbox' -Flag 256  -SummaryOnly -Negate

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

Exporting and Uploading Mailbox Items using Exchange Web Services using the new ExportItems and UploadItems operations in Exchange 2010 SP1

Two new EWS Operations ExportItems and UploadItems where introduced in Exchange 2010 SP1 that allowed you to do a number of useful things that where previously not possible using Exchange Web Services. Any object that Exchange stores is basically a collection of properties for example a message object is a collection of Message properties, Recipient properties and Attachment properties with a few meta properties that describe the underlying storage thrown in. Normally when using EWS you can access these properties in a number of a ways eg one example is using the strongly type objects such as emailmessage that presents the underlying properties in an intuitive way that's easy to use. Another way is using Extended Properties to access the underlying properties directly. However previously in EWS there was no method to access every property of a message hence there is no way to export or import an item and maintain full fidelity of every property on that item (you could export the...

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