Search code examples
c#outlook-addinoffice-interopoffice-2007

How to Program Outlook 2007 Add-In with Multiple Mailboxes


I'm trying to figure how to write a simple add-in for Excel 2007, but one that only interacts with one of my mailboxes. Currently I have two email addresses coming into my outlook, each in a specific 'mailbox'. I was wondering, how would I specify a NewMail event for a specific mailbox?

Or, perhaps not as clean, but how could I write an if function that specifies which mailbox / email any new item is addressed to...

Hopefully this makes sense. Thanks


Solution

  • To catch new mail event, add this code to addin startup method:

    this.Application.NewMailEx += 
        new Outlook.ApplicationEvents_11_NewMailExEventHandler(Application_NewMailEx);
    

    Then add method to handle NewMailEx event:

    void Application_NewMailEx(string EntryID)
    {
        // get MailItem for this new mail
        Outlook.Explorers explorers = this.Application.Explorers;
        Outlook.MailItem newMail =
            (Outlook.MailItem)explorers.Application.Session.GetItemFromID(EntryID, System.Reflection.Missing.Value);
    
        // check SendUsingAccount to see if it came in mailbox we are interested in
        if (newMail.SendUsingAccount.DisplayName == "[email protected]")
        {
            // do whatever You like
        }
    }  
    

    Add using statement also:

    using Outlook = Microsoft.Office.Interop.Outlook;