Search code examples
c#outlookvstooutlook-addin

How to add ItemAddEventHandler for multiple folders in outlook using C#?


We have added some rules in outlook to move item to some folder depends on some condition.

example: if email sender is [email protected] and subject contains particular keyword lets say "news" then move that email to folder "NewsFolder", if email sender is [email protected] then move that email to "InterestFolder" folder. etc.

I want to perform some action when item is added to particular folder, I have added configuration in app.config for checking folder name. I tried with itemAdd event handler but I failed.

below is my code.

Outlook.NameSpace outlookNameSpace;
Outlook.MAPIFolder inbox;
Outlook.Items items;

Private void ThisAddIn_Startup(object sender, system.EventArgs e)
{
           //configuration will come from app.config file
        
            string configuration="news,NewsFolder|interest,InterestFolder"; //comma separated by keyword, folder name
            string[] conf = configuration.split('|');
            foreach(string singleConfiguartion in conf)
           {
                  string[] config = singleConfiguraiton.Split(','); 
                  string configFolderName= config[1].ToString(); //get folder name from configuration
                  Application.ActiveExplorer().CurrentFolder = inbox.Folders[configFolderName];
                  Outlook.MAPIFolder currentFolder = inbox.Folders[configFolderName];
                  items= currentFolder.Items;
                  items.ItemAdd+= new Outlook.ItemEvents_ItemAddEventHandler(ItemAddedEventHandler);
           }
    
}    

void ItemAddedEventHandler(Object item)
{

}

This way is worked if I want to add event handler for "Inbox" folder only. But I want to add Event handler for "NewsFolder" and "InterestFolder".


Solution

  • Create a wrapper class that holds the Items collection and implements the ItemAdd event handler. You can then keep these wrappers in a list. Off the top of my head:

    private List<FolderWrapper> _folders = new List<FolderWrapper>();
    ...
    foreach(string singleConfiguartion in conf)
    {
        ...
        _folders.Add(new FolderWrapper(currentFolder));
    }
    
    public class FolderWrapper
    {
        private MAPIFolder _folder;
        private Items _items;
        public FolderWrapper(MAPIFolder folder)
        {
            _folder = folder;
            _items = _folder.Items;
            _items.ItemAdd += ItemAddedEventHandler;
        }
        private ItemAddedEventHandler(object Item)
        {
            MessageBox.Show($"new item is created in {folder.Name}");
        } 
    }