3

I am trying to create a popup mail alert for a shared mailbox in Outlook 2007. The following code doesn't work. why?

private Microsoft.Office.Interop.Outlook._Explorers Explorers;
private Microsoft.Office.Interop.Outlook.NameSpace outlookNamespace;
private Microsoft.Office.Interop.Outlook.MAPIFolder mFolder;
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
  Explorers = this.Application.Explorers;         
  outlookNamespace = this.Application.GetNamespace("MAPI");         
  mFolder = outlookNamespace.Folders["Mailbox -AdditionalMailBox"].Folders["Inbox"];  
  mFolder.Application.NewMailEx += new  ApplicationEvents_11_NewMailExEventHandler(Application_NewMailEx );
}
private void Application_NewMailEx(string EntryID)
{
  MessageBox.Show("New MailReceived!");
}
SliverNinja - MSFT
  • 31,051
  • 11
  • 110
  • 173
Shnerka Zoid
  • 107
  • 1
  • 1
  • 6

1 Answers1

1

In order for your event handlers to survive garbage collection - you need to ensure that the objects that contain your events are kept alive by adding them as a private member variable. Try adding an Application private class variable and your event subscription should work just fine. See related SO post for more details.

private Microsoft.Office.Interop.Outlook.Application application;
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
    application = this.Application;
    Explorers = application.Explorers;         
    // ...         
    application.NewMailEx += new  ApplicationEvents_11_NewMailExEventHandler(Application_NewMailEx );
}

The other issue you discovered is that NewMailEx only fires for your primary mailbox - not secondary mailboxes as confirmed in this forum post. You will need to rely on the Folder.Items event ItemAdd.

private Outlook.Items mFolderItems;
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
    // ...
    mFolderItems = mFolder.Items; // avoid GC for ItemAdd event
    mFolderItems.ItemAdd += new ItemsEvents_ItemAddEventHandler(mFolder_ItemAdd);
    // ...
}        
private void mFolder_ItemAdd(object addedItem)
{
  Outlook.MailItem newItem = addedItem as Outlook.MailItem;
}
Community
  • 1
  • 1
SliverNinja - MSFT
  • 31,051
  • 11
  • 110
  • 173