Outlook.ItemsEvents_ItemAddEventHandler(CallBack)可以用于多个邮件帐户吗?

时间:2018-12-21 06:04:58

标签: c# .net outlook outlook-addin

  

如何将监听器添加到全部多个邮件帐户?   或者在将所有传入邮件放入文件夹之前,先进行侦听   子文件夹?

     

我无法为多个帐户创建 outlook.ItemsEvents_ItemAddEventHandler(CallBack)回调函数。

        Outlook.Application outlookApp;
        Outlook.MAPIFolder deleterFolder = null;
        Outlook.Items mailItems = null;
        Outlook.MAPIFolder inboxFolder = null;
        Outlook.Items items;

        private void Phishing_Load(object sender, RibbonUIEventArgs e)
        {   
            outlookApp = new Outlook.Application();

            inboxFolder = outlookApp.ActiveExplorer().Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
            deleterFolder = outlookApp.ActiveExplorer().Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderJunk);
            mailItems = inboxFolder.Items;//.Restrict("[Unread]=true");
            mailItems.Sort("[ReceivedTime]", true);
            items = inboxFolder.Items;
            items.ItemAdd += new Outlook.ItemsEvents_ItemAddEventHandler(CallFunction);
        }
 private void CallFunction(object data)
         {
       Console.Write(" Call Function");
        }

1 个答案:

答案 0 :(得分:0)

创建一个包装器类,该包装器类包含一个指向Items对象的指针(以使其保持活动状态),并具有ItemAdd事件的处理程序。在您的代码中,您可以拥有这些包装对象的列表。创建该类的新实例,并将其添加到要监视的每个文件夹的列表中。

我的头顶上

public class ItemsWrapper
{
  private Items _items;
  private MAPIFolder _folder;
  public ItemsWrapper(MAPIFolder folder)
  {
    _folder = folder;
    _items = folder.Items;
    _items.ItemAdd += Item_Add;
  }
  private Items_Add(object item)
  {
    MessageBox.Show($"New item in folder '{folder.Name}' ");
  }
}

...
//global/class variable that will hold the wrappers
List<ItemsWrapper> allWrappers = new List<ItemsWrapper>();
foreach (MAPIFolder folder in FoldersThatYouWantToProcess)
{
  ItemsWrapper wrapper = new ItemsWrapper(folder);
  allWrappers.Add(wrapper);
}