Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EWS subscribe to streaming notifications in the inbox

I trying to write a Console Application which will establish a connection to a mailbox using EWS and then print a line every time a new email is received.

The end result once I have this working is to turn this into a service, and have a task created every time an email arrives in a certain mailbox, but for now I cant get the Console to write a line upon receipt.

Console Application Project

Program.cs

class Program
{
    static void Main(string[] args)
    {
         ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013);
         WebCredentials wbcred = new WebCredentials("myusername", "mypassw0rd");
         service.Credentials = wbcred;
         service.AutodiscoverUrl("[email protected]", RedirectionUrlValidationCallback);

         EWSConnection.SetStreamingNotifications(service);
    }

    internal static bool RedirectionUrlValidationCallback(string redirectionUrl)
    {
        //The default for the validation callback is to reject the URL
        bool result = false;

        Uri redirectionUri = new Uri(redirectionUrl);
        if (redirectionUri.Scheme == "https")
        {
            result = true;
        }
        return result;
    } 
}

Class Library Project

EWSConnection.cs

  public static void SetStreamingNotifications(ExchangeService service)
        {
            StreamingSubscription subscription;

            // Subscribe to streaming notifications in the Inbox. 
            subscription = service.SubscribeToStreamingNotifications(
                new FolderId[] { WellKnownFolderName.Inbox },
                EventType.NewMail);

            // Create a streaming connection to the service object, over which events are returned to the client.
            // Keep the streaming connection open for 30 minutes.
            StreamingSubscriptionConnection connection = new StreamingSubscriptionConnection(service, 30);
            connection.AddSubscription(subscription);
            connection.OnNotificationEvent += OnEvent;
            connection.OnDisconnect += OnDisconnect;
            connection.Open();

            bool status = connection.IsOpen;
            Console.WriteLine($"Connection Open:{status}");
        }

I can add the OnEvent and OnDisconnect methods if required. What's happening is the console prints

Connection Open:True Press any key to continue . . .

Then, when I send an email to that mailbox nothing happens, no break points are triggered and nothing is output to the console, which is what those two methods do.

Why is my OnEvent method not firing?

Edit - OnEvent & OnDisconnect methods

 public static void OnEvent(object sender, NotificationEventArgs args)
        {
            StreamingSubscription subscription = args.Subscription;

            // Loop through all item-related events. 
            foreach (NotificationEvent notification in args.Events)
            {

                switch (notification.EventType)
                {
                    case EventType.NewMail:
                        Console.WriteLine("\n————-Mail created:————-");
                        break;
                    case EventType.Created:
                        Console.WriteLine("\n————-Item or folder created:————-");
                        break;
                    case EventType.Deleted:
                        Console.WriteLine("\n————-Item or folder deleted:————-");
                        break;
                }
                // Display the notification identifier. 
                if (notification is ItemEvent)
                {
                    // The NotificationEvent for an e-mail message is an ItemEvent. 
                    ItemEvent itemEvent = (ItemEvent)notification;
                    Console.WriteLine("\nItemId: " + itemEvent.ItemId.UniqueId);
                }
                else
                {
                    // The NotificationEvent for a folder is an FolderEvent. 
                    FolderEvent folderEvent = (FolderEvent)notification;
                    Console.WriteLine("\nFolderId: " + folderEvent.FolderId.UniqueId);
                }
            }
        }

and

public static void OnDisconnect(object sender, SubscriptionErrorEventArgs args)
{
    // Cast the sender as a StreamingSubscriptionConnection object.           
    StreamingSubscriptionConnection connection = (StreamingSubscriptionConnection)sender;
    // Ask the user if they want to reconnect or close the subscription. 
    ConsoleKeyInfo cki;
    Console.WriteLine("The connection to the subscription is disconnected.");
    Console.WriteLine("Do you want to reconnect to the subscription? Y/N");
    while (true)
    {
        cki = Console.ReadKey(true);
        {
            if (cki.Key == ConsoleKey.Y)
            {
                connection.Open();
                Console.WriteLine("Connection open.");
                break;
            }
            else if (cki.Key == ConsoleKey.N)
            {
                // The ReadKey in the Main() consumes the E. 
                Console.WriteLine("\n\nPress E to exit");
                break;
            }
        }
    }
}
like image 421
JsonStatham Avatar asked Mar 11 '23 04:03

JsonStatham


2 Answers

Annoyingly, I was missing the Console.ReadKey() method. It worked as expected once I added this...

    static void Main(string[] args)
    {
        ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013);
        WebCredentials wbcred = new WebCredentials("myusername", "mypassw0rd","myDomain");
        service.Credentials = wbcred;
        service.AutodiscoverUrl("[email protected]", RedirectionUrlValidationCallback);

        EWSConnection.SetStreamingNotifications(service);

        Console.ReadKey(); //<-- this was missing
    }
like image 117
JsonStatham Avatar answered Mar 13 '23 19:03

JsonStatham


Bind the methods to the current subscription as this

connection.OnNotificationEvent +=
                new StreamingSubscriptionConnection.NotificationEventDelegate(OnEvent);
connection.OnDisconnect +=
        new StreamingSubscriptionConnection.SubscriptionErrorDelegate(OnDisconnect); 

Here's a example

like image 22
Marcus Höglund Avatar answered Mar 13 '23 17:03

Marcus Höglund