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

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 MimeMessage via the Microsoft Graph using the Graph SDK, MimeKit and MSAL

One of the new features added to the Microsoft Graph recently was the ability to create and send Mime Messages (you have been able to get Message as Mime for a while). This is useful in a number of different scenarios especially when trying to create a Message with inline Images which has historically been hard to do with both the Graph and EWS (if you don't use MIME). It also opens up using SMIME for encryption and a more easy migration path for sending using SMTP in some apps. MimeKit is a great open source library for parsing and creating MIME messages so it offers a really easy solution for tackling this issue. The current documentation on Send message via MIME lacks any real sample so I've put together a quick console app that use MSAL, MIME kit and the Graph SDK to send a Message via MIME. As the current Graph SDK also doesn't support sending via MIME either there is a workaround for this in the future my guess is this will be supported.

Export calendar Items to a CSV file using Microsoft Graph and Powershell

For the last couple of years the most constantly popular post by number of views on this blog has been  Export calendar Items to a CSV file using EWS and Powershell closely followed by the contact exports scripts. It goes to show this is just a perennial issue that exists around Mail servers, I think the first VBS script I wrote to do this type of thing was late 90's against Exchange 5.5 using cdo 1.2. Now it's 2020 and if your running Office365 you should really be using the Microsoft Graph API to do this. So what I've done is create a PowerShell Module (and I made it a one file script for those that are more comfortable with that format) that's a port of the EWS script above that is so popular. This script uses the ADAL library for Modern Authentication (which if you grab the library from the PowerShell gallery will come down with the module). Most EWS properties map one to one with the Graph and the Graph actually provides better information on recurrences then...
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.