Skip to main content

Searching Mailbox folders using the REST API In Powershell on Office365 and Exchange 2016

Preface

Searching Mailboxes is something I've written a fair bit about in the past but in this article I'm going to cover how searching has been surfaced in the new REST API on Office365 and Exchange 2016.  The first place to go when considering searching in Office365 is the Security and Compliance center https://support.office.com/en-us/article/run-a-content-search-in-the-office-365-security-compliance-center-61852fd9-fe8a-4880-a339-cb19ed3bff4a it offers the most feature rich and realistic search experience that is difficult to replicate with client facing Mailbox API's (eg things like RBAC's delegated access rights, litigation holds etc). Given the amount of data that can be stored in Mailboxes now its important to have a realistic expectation of the time it will take and difficulty of searching 100,000's items in multiple folders or millions of items in an Archive is important (at the time of writing Archives aren't accessible using the REST API).

Searching Mailboxes

Within an Office365 Mailbox there are number of different methods for performing a Search using the REST API for particular items within a particular Mailbox folder or across all folders in a mailbox. Depending on the properties you want to search on and the amount of data you expect to return in your search you should select the most appropriate method to use.

Using filters (or Restrictions)

Restrictions are the standard way in which searches are normally carried out in Outlook and Exchange, restrictions are property based searches on one or more properties and may involve a number of operators such as equals, greatorthan, lessthan, contains (for substrings) or startswith. In the REST API restriction are implemented via the $filter Query Parameter. Because the raw content is queried this type of search can take longer to perform if the underlying folder has a larger number of items or the restriction being used is very complicated. A common issue that can occur using filters is the Query will timeout or will be throttled because of the overall load it produces on the server. Some more background on restrictions can be found https://technet.microsoft.com/en-us/library/bb267022(v=exchg.80).aspx

Using KQL (or Exchange Search)

Exchange Search is the full text indexing feature of Exchange which indexes contents automatically (asynchronously) as email arrives in a Mailbox.This type of Search utilizes the KQL (Keyword Query Logic) that is also used with in Share-point for query processing. This is the faster and more efficient method of searching a Mailbox because it utilizes Full Text Indexes rather then needing to query the raw content and should be the preferred starting point for search. However there are some limitations on the properties that can be searched using this method and also on the amount of results that will be returned by a query. In the REST API KQL queries are performed using the $search Query Parameter.
Property restrictions : As Exchange only indexes certain properties for performance reason only certain properties can be searched using KQL a full list of the indexed properties the can be used can be found https://support.office.com/en-us/article/keyword-queries-and-search-conditions-for-content-search-c4639c2e-7223-4302-8e0d-b6e10f1c3be3#emailproperties
Maximum Result Sets: Exchange limits the maximum result set of Exchange Search queries to 250 Items in REST and EWS. with OnPrem Servers this value is adjustable via the MaxHitsForFullTextIndexSearches property https://support.microsoft.com/en-us/help/3093866/the-number-of-search-results-can-t-be-more-than-250-when-you-search-em however in Exchange OnLine (Office365) you can't adjust that value and need to work under the 250 item ceiling.

Using SearchFolders

Search Folders are Special Mailbox folders that contain no items but return linked Items based on a predefined search criteria (usually the same as you would use in Filters). Because these are constantly updated asynchronously by the Exchange Server they offer better performance when retrieving items based on a search criteria then doing a normal search using a filter. Search Folders are a good choice if you have static queries that don't require any dynamic input or you need to have a search that spans multiple folders. You do need to be aware that overuse of Search Folders can cause poor performance and they are updated by a background process so new items may not be instantly available as apposed to querying the Mailbox folder directly. Some more background information on Search Folders can be found
Currently there is no way of creating a SearchFolder programmaticly using the REST API but this can be done using EWS.

Search Examples using the Search-EXRMessage cmdlet from the Exch-Rest Module

Several of the cmdlets in the Exch-REST Module https://www.powershellgallery.com/packages/Exch-Rest allows the entering of both the Filter and Search criteria however the cmdlet specifically designed for search is the Search-EXRMessage cmdlet
Using Raw KQL
The -KQL Parameter allows you enter raw KQL to be used as a Mailbox Search if you do use this approach you should take care that some characters need to be escaped correct. Eg when search for an exact phrase in KQL the phrase should be encolesd in double quotes. When doing this in REST these double quotes need to be escape. Eg so if you where search for email with the subject has the following keywords you could use -KQL "subject:'termone termtwo'" where if you want to search for a phrase you should use -KQL 'subject:"this is a phrase""
Specifying the folders to Search
By default the Search-EXRMessage cmdlet will search all the Mail folders in a Mailbox using the AllItems Search Folder if no folder is specified in the cmdline. To limit the Search to a particular folder you can specify the folder using the -FolderPath eg
Search-EXRMessage -FolderPath \Inbox -KQL 'subject:"Happy Days"'
or use the -Wellknown parameter to specify one of the default folder such as Inbox or SentItems eg
Search-EXRMessage -Wellknow SentItems -KQL 'subject:"Happy Days"'
Returning Attachments details within Search Results
Returning attachment details when search for objects requires extra requests be made to the server which will affect the performance of search greatly so this isn't done by default. However if its import for you to get this information because of the type of search that you are trying to do then you can use the -ReturnAttachments swich. Not when using the -AttachmentKQL switch this is submitted by default.
Finding a Message from a Particular Sender
Find a Message from a Particular Sender by Name or Email Address using a Filter
by Email
Search-EXRMessage -MailboxName user@domain -from 'James@domain.com'  | select Subject,SenderEmailAddress,SenderName,FolderPath
Find a messages from a Particular Sender by Name or Email Address using KQL
by Name
Search-EXRMessage -MailboxName user@domain -kql 'From:James'  | select Subject,SenderEmailAddress,SenderName,FolderPath
by Email Address
Search-EXRMessage -MailboxName user@domain -kql 'From:James@domain.com'  | select Subject,SenderEmailAddress,SenderName,FolderPath
Find a Message from a Particular Sender on a Particular Date
using a Filter
Search-EXRMessage -MailboxName user@domain -ReceivedtimeFrom ([DateTime]::Parse('2018-01-01')) -ReceivedtimeTo ([DateTime]::Parse('2018-01-02')) -from 'james@domain.com' | select Subject,SenderEmailAddress,SenderName,FolderPath
using KQL
Search-EXRMessage -MailboxName user@domain -ReceivedtimeFromKQL ([DateTime]::Parse('2018-01-01')) -ReceivedtimeToKQL ([DateTime]::Parse('2018-01-02')) -KQL 'from:james@domain.com' | select Subject,SenderEmailAddress,SenderName,FolderPath
Find a Message with a Particular Subject (Exact Match)
using a Filter
Search-EXRMessage -MailboxName user@domain -subject 'And the Subject is' | select Subject,SenderEmailAddress,SenderName,FolderPath
using KQL
Search-EXRMessage -MailboxName user@domain -SubjectKQL 'And the Subject is' | select Subject,SenderEmailAddress,SenderName,FolderPath
Find a Message where the Subject contains a phrase
using a Filter
Search-EXRMessage -MailboxName user@domain -SubjectContains 'And the Subject' | select Subject,SenderEmailAddress,SenderName,FolderPath
using KQL
Search-EXRMessage -MailboxName user@domain -KQL "Subject:'And the Subject'" | select Subject,SenderEmailAddress,SenderName,FolderPath
Find a Message where the Subject starts with a phrase using a Filter
Search-EXRMessage -MailboxName user@domain -SubjectStartsWith 'And the Subject' | select Subject,SenderEmailAddress,SenderName,FolderPath
Find a Message where the Body contains a phrase
using a Filter
Search-EXRMessage -MailboxName user@domain -BodyContains 'Summer Sales' | select Subject,SenderEmailAddress,SenderName,FolderPath
using KQL
Search-EXRMessage -MailboxName user@domain -BodyKQL "Sumber Sale" | select Subject,SenderEmailAddress,SenderName,FolderPath
Find Attachments
You can search for attachments using the full attachment name or a partial name like the extension if you want to find all email with word documents for example.
Using KQL
Search-EXRMessage -MailboxName user@domain -AttachmentKQL ".doc" -ReturnAttachments 

Using SearchFolders

To use a Search folder you first need to know the FolderId value of the SearchFolder you wish to use, SearchFolder should be available under the NON_IPM_Subtree Finder folder. To get the available search folders in a Mailbox you can use the Get-EXRSearchFolders Cmldet eg
Get-EXRSearchFolders -MailboxName user@domain.com
To Restrict the results to a particular name SearchFolder you can use
Get-EXRSearchFolders -MailboxName user@domain.com -FolderName 'Voice Mail'
To enumerate the linked Items (Search Criteria items) from the Voice Mail SearchFolder use
$VoiceMail = Get-EXRSearchFolders -MailboxName user@domain.com -FolderName 'Voice Mail'
Get-EXRFolderItems  -MailboxName user@domain.com -Folder $voicemail

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 Graph is limited to a m

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 need to authorize it in you tenant (eg build a small ap

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 I wrote th
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.