Tuấn Anh Phạm
Tuấn Anh Phạm

Reputation: 69

Outlook 2016 VSTO Folder Add item event fires only once

I have an add-in, I want to do something when the email sent successful, I write:

    private void ThisAddIn_Startup(object sender, System.EventArgs e)
    {
        Outlook.Application application = this.Application;

        var sentMail = Application.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderSentMail);
        sentMail.Items.ItemAdd += new Outlook.ItemsEvents_ItemAddEventHandler(Items_ItemAdd);
    }

    void Items_ItemAdd(object item)
    {
      // do something
    }

But my method runs only one when I sent first email success, the next emails not fires event.

Please help me!

Upvotes: 1

Views: 750

Answers (2)

smirne
smirne

Reputation: 220

I wanted to post my solution to this problem as well. I tried pretty much everything that was suggested on stackoverflow and nothing worked well, including adding 'Items' to a list so it doesn't get garbage collected, etc.

What worked perfectly for me was to tell the GC to not collect 'Items' explicitly and then it started picking up every new item in the Inbox.

Here's the code I ended up using:

public partial class ThisAddIn
{
    // Keep a static copy of the Inbox and Items
    private static MAPIFolder Inbox { get; set; }
    private static Items Items { get; set; }

    private void ThisAddIn_Startup(object sender, System.EventArgs e)
    {
        Inbox = Application.Session.GetDefaultFolder(OlDefaultFolders.olFolderInbox);
        Items = Inbox.Items;
        Items.ItemAdd += new ItemsEvents_ItemAddEventHandler(ProcessesEmail);

        // Tell the GC to *not* collect these objects
        GC.KeepAlive(Inbox);
        GC.KeepAlive(Items);
    }

    public static void ProcessesEmail(object Item)
    {
        // Rest of your code here
    }
}

Upvotes: 2

Dmitry Streblechenko
Dmitry Streblechenko

Reputation: 66286

You are setting an event handler on a implicit local variable. As soon as that variable is released by the Garbage Collector, no events will fire. You need to have a global (class) Items variable:

private Outlook.Items _items;
private void ThisAddIn_Startup(object sender, System.EventArgs e)
    {
        Outlook.Application application = this.Application;

        _items = Application.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderSentMail).Items;
        _items.ItemAdd += new Outlook.ItemsEvents_ItemAddEventHandler(Items_ItemAdd);
    }

Upvotes: 0

Related Questions