Skip to main content

EWS Managed API and Powershell How-To Series Part 9 EWS Notifications

In this installment of the how-to series I'm going to cover EWS notifications which are a mechanism you can use to find out when changes occur in an Exchange Folder. One critical point when thinking about notifications is you need to think of them as notifications and not the programmatic equivalent of events which event sinks where (kind of). Exchange is a mail system that caters to many clients and applications and from a client sense (not a throttling sense) all of these clients are even. So when your building a notification application that is going to affect a message in some way(eg say your just moving it to another folder) you need to understand that by the time your application has received the notification another application may have taken an action on that message. The other issue you may have is because there can be so many clients involved and different synchronization methods in use is you may get multiple notifications for one item which is an issue you just need to make sure you cater for in your code. A good idea can be to look at combining notification operations with synchronization operations which I'll cover in a another post.

Event Notification Types

Before looking at the Types of notifications its a good idea to look at what type of events you can get notifications for.
  • NewMail - This notification fires when a new email is delivered to the Inbox
  • Modified - This notification fires when in Item is modified
  • Copy - This notification fires when an Item is copied
  • Created - This notification fires when a new Item is created in a folder (useful for monitoring the creation of Contacts,Task or Appointments)
  • Deleted - This notification fires when an Item is deleted (accessing the deleted Item is not trivial through)
  • Moved - This notification fires when an Item is moved.
  • FreeBusyChanged - This notification fires when FreeBusy status changes

Types of Notification's

Pull Notifications 

Pull notifications are client initiated notifications eg the way this would generally work is your client would first register for notifications at 10:00 AM on the Inbox, In the next hour 5 new emails arrive, your client then sends a request to the Exchange Server for new notifications on the Inbox at 11:00 AM and you receive back 5 notifications for the newly received messages. Pull notifications are good if your application isn't time critical and you just want to track changes at a regular interval. Here's an example of creating a pull notification on the Inbox folder for NewMail events and a simple update loop that will check for updates and bind to any updated items from the notification event when you press a key.

  1. $InboxId = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$MailboxName)  
  2. $fldArray = new-object Microsoft.Exchange.WebServices.Data.FolderId[] 1  
  3. $fldArray[0] = $InboxId  
  4. $pullSubscription = $service.SubscribeToPullNotifications($fldArray,60,$null,[Microsoft.Exchange.WebServices.Data.EventType]::NewMail)  
  5. $events = $pullSubscription.GetEvents();  
  6. foreach ($notificationEvent in $events.AllEvents)  
  7. {    
  8.     switch ($notificationEvent.EventType)  
  9.       {  
  10.         "NewMail" {"New Mail"  
  11.                     $item = [Microsoft.Exchange.WebServices.Data.Item]::Bind($service,$notificationEvent.ItemId)  
  12.                     "Subject : " + $item.Subject  
  13.         }  
  14.       }  
  15. }  
  16. do{  
  17.     $response = read-host "Press key to check next events or Q to exits"  
  18.     $events = $pullSubscription.GetEvents();  
  19.     foreach ($notificationEvent in $events.AllEvents)  
  20.     {  
  21.         switch ($notificationEvent.EventType)  
  22.           {  
  23.             "NewMail" {"New Mail" 
  24.                     $item = [Microsoft.Exchange.WebServices.Data.Item]::Bind($service,$notificationEvent.ItemId)  
  25.                     "Subject : " + $item.Subject  
  26.                      }  
  27.                               
  28.           }  
  29.     }  
  30. }while($response -ne "Q")  
Subscribing to Notification events on all folders

In Exchange 2010 you can also subscribe to notifications on all folders in the EWS Managed API for pull notifications this is exposed as SubscribeToPullNotificationsOnAllFolders. The following is a sample of creating pull notifications on all folders in a mailbox this looks at the Modification events on Items.

  1. $pullSubscription = $service.SubscribeToPullNotificationsOnAllFolders(60,$null,[Microsoft.Exchange.WebServices.Data.EventType]::Modified)  
  2. $events = $pullSubscription.GetEvents();  
  3. foreach ($notificationEvent in $events.AllEvents)  
  4. {    
  5.     switch ($notificationEvent.EventType)  
  6.       {  
  7.             "Modified" {"Modified"  
  8.                     if($notificationEvent.ItemId -ne $null){  
  9.                         $item = [Microsoft.Exchange.WebServices.Data.Item]::Bind($service,$notificationEvent.ItemId)  
  10.                         "Subject : " + $item.Subject  
  11.                          }                     
  12.                         }  
  13.       }  
  14. }  
  15. do{  
  16.     $response = read-host "Press key to check next events or Q to exits"  
  17.     $events = $pullSubscription.GetEvents();  
  18.     foreach ($notificationEvent in $events.AllEvents)  
  19.     { 
  20.           {  
  21.             "Modified" {  
  22.                     if($notificationEvent.ItemId -ne $null){  
  23.                         $item = [Microsoft.Exchange.WebServices.Data.Item]::Bind($service,$notificationEvent.ItemId)  
  24.                         "Subject : " + $item.Subject  
  25.                          }  
  26.                      }  
  27.                               
  28.           }  
  29.     }  
  30. }while($response -ne "Q")  
Push Notifications

Push notifications are server initiated Notifications eg the way these work is at 10:00 AM you register for Push notifications on the Inbox for your client application with IP address 10.0.1.22. The next time an email arrives in the Inbox the Exchange server will then send a notification to your application. Push notifications are complex beasts in that you need to have a fairly complex application that listens for notifications and maintains the subscription. You also need to make sure you have a dedicated port and clear communication channels through firewalls etc. For this reason Push notifications aren't really practical to use with simple scripted type applications however the third type of notification Streaming Notification allow you to get all the benefits of Push notifications without the communication complexities.

Streaming Notifications

Streaming notifications work similar to push email in ActiveSync eg Your steaming notification application would register for streaming notifications at 10:00AM on the Inbox. The TCP connection used for the registration will then stay open and the Exchange Server will push notifications back to your application via this connection as new emails arrive in the Inbox. Which means you get push notifications without needing a dedicated listener application or the need to worry about firewalls etc. The only catch with streaming notification is that they have a maximum duration of 30 minutes so in the example I've been talking about at 10:30AM you would need to recreate the streaming notification subscription. The good thing is that there are events that are triggered by the Managed API's StreamingSubscriptionConnection class they we can hook in Powershell so we can have a self renewing subscription process. In Powershell the Register-ObjectEvent cmdlet allows you to subscribe to the events that are generated by the Microsoft .NET Framework. To use Streaming notifications in Powershell you need to register for events that are generated by the StreamingSubscriptionConnection class. An example of a Streaming Notification script that will listen for the NewMail Event on the Inbox looks like

  1. $fldArray = new-object Microsoft.Exchange.WebServices.Data.FolderId[] 1  
  2. $Inboxid = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$MailboxName)  
  3. $fldArray[0] = $Inboxid  
  4. $stmsubscription = $service.SubscribeToStreamingNotifications($fldArray, [Microsoft.Exchange.WebServices.Data.EventType]::NewMail)  
  5. $stmConnection = new-object Microsoft.Exchange.WebServices.Data.StreamingSubscriptionConnection($service, 30);  
  6. $stmConnection.AddSubscription($stmsubscription)  
  7. Register-ObjectEvent -inputObject $stmConnection -eventName "OnNotificationEvent" -Action {  
  8.     foreach($notEvent in $event.SourceEventArgs.Events){      
  9.         [String]$itmId = $notEvent.ItemId.UniqueId.ToString()  
  10.         $message = [Microsoft.Exchange.WebServices.Data.EmailMessage]::Bind($event.MessageData,$itmId)  
  11.         "Subject : " + $message.Subject + " " + (Get-Date) | Out-File c:\temp\log2.txt -Append   
  12.     }   
  13. } -MessageData $service  
  14. Register-ObjectEvent -inputObject $stmConnection -eventName "OnDisconnect" -Action {$event.MessageData.Open()} -MessageData $stmConnection  
  15. $stmConnection.Open()  
To register for Streaming notifications on all folders you can use SubscribeToStreamingNotificationsOnAllFolders

Popular posts from this blog

Testing and Sending email via SMTP using Opportunistic TLS and oAuth in Office365 with PowerShell

As well as EWS and Remote PowerShell (RPS) other mail protocols POP3, IMAP and SMTP have had OAuth authentication enabled in Exchange Online (Official announcement here ). A while ago I created  this script that used Opportunistic TLS to perform a Telnet style test against a SMTP server using SMTP AUTH. Now that oAuth authentication has been enabled in office365 I've updated this script to be able to use oAuth instead of SMTP Auth to test against Office365. I've also included a function to actually send a Message. Token Acquisition  To Send a Mail using oAuth you first need to get an Access token from Azure AD there are plenty of ways of doing this in PowerShell. You could use a library like MSAL or ADAL (just google your favoured method) or use a library less approach which I've included with this script . Whatever way you do this you need to make sure that your application registration  https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-

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

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