EWS 邮件提醒

摘要

之前做的邮件提醒的项目,最近需要优化,由于使用了队列,但即时性不是特别好,有队列,就会出现先后的问题,最近调研了exchange 流通知的模式,所以想使用流通知模式和原先的拉取邮件的方法结合,在收到新邮件的时候,通过SyncFolderItems方法拉取当前状态下的所有邮件。

遇到的问题

在使用流通知模式的时候,发现经常会出现下面的错误:

Microsoft.Exchange.WebServices You must add at least one subscription to this connection before it can be opened. 

经常会出现丢订阅对象的问题,虽然可以通过重新初始化订阅对象,解决该问题,但在初始化过程中,如果有新邮件,那么就会出现丢邮件现象。那么就想到了将流式通知和SyncFolderItems方法结合的方式,SyncFolderItems放需要传递邮件同步的状态(即邮件读取到具体位置的一个指针),那么每次有新邮件的时候,触发NewMail事件,可以在这时通过SyncFolderItems拉取上次保存的state之后的所有邮件。核心代码块如下:

 private void OnNotificationEvent(object sender, NotificationEventArgs args)
        {
            if (args != null)
            {
                foreach (NotificationEvent notificationEvent in args.Events)
                {
                    if (notificationEvent is ItemEvent)
                    {
                        try
                        {
                            ItemEvent itemEvent = (ItemEvent)notificationEvent;
                            Console.WriteLine(notificationEvent.EventType.ToString());
                            Item item = Item.Bind(this._service, itemEvent.ItemId);
                            switch (notificationEvent.EventType)
                            {
                                case EventType.Moved:
                                    Console.WriteLine(item.Subject);
                                    string emialId = MD5Helper.GetMD5FromString(item.Id.UniqueId);
                                    TriggerLogHandler(new LogModel { Op = "delete_email", 
Content = JsonConvert.SerializeObject(new { id = emialId, subject = item.Subject }) }, LogType.Info); _exchangeMailBusiness.UpdateIsDeletedAsync(emialId, true); break; case EventType.NewMail: //如果有新邮件,触发同步,拉取该状态下所有邮件 ChangeCollection<ItemChange> iccEmail =
this._service.SyncFolderItems(new FolderId(WellKnownFolderName.Inbox), PropertySet.FirstClassProperties, null,
512, SyncFolderItemsScope.NormalItems, mailSyncState.SyncState); .... .....这里处理该状态下所有的邮件 ... break; default: break; } } catch (Exception ex) { TriggerErrorAndUnautorizedHandler(ex, "load_email_field"); } } } } }

这样可以解决丢邮件的问题,比通过SyncFolderItems方法不停轮询exchange服务器,性能上应该好很多。

总结

有关其它详情,可以查看我写的几篇关于EWS的相关文章。

原文地址:https://www.cnblogs.com/wolf-sun/p/7610719.html