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

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.