1
votes

I have an Outlook Add-in with two ribbons (for read mail and compose mail).

I created an event to get an email when it goes to the sent items after it has been send.

This is my ThisAddIn.cs

private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
    OutlookApplication = Application as Outlook.Application;
    OutlookInspectors = OutlookApplication.Inspectors;
    OutlookInspectors.NewInspector +=
        new Outlook.InspectorsEvents_NewInspectorEventHandler(OutlookInspectors_NewInspector);

    var sentBoxItems =
        this.Application.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderSentMail).Items;
    sentBoxItems.ItemAdd +=
        new Outlook.ItemsEvents_ItemAddEventHandler(Items_ItemsAdd);
}

private void Items_ItemsAdd(object Item)
{
    if (Item != null)
        Helpers.SaveMailSent((Outlook.MailItem)Item); // Here do stuff to save mail
}

I tried to get the event when the "Send" button is clicked, but the mailItem goes to null.

Now I am trying to get when a new mail is sent and it goes to the sent folder.

The problem is that the event is not firing every time a mail is sent (sometimes it executes, but sometimes no)

1

1 Answers

2
votes

First of all, you need to keep the source object alive, i.e. prevent it from destroying or releasing. To get that implemented you must declare the source object at the class level:

 private Outlook.Items sentBoxItems = null;

 private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
    OutlookApplication = Application as Outlook.Application;
    OutlookInspectors = OutlookApplication.Inspectors;

    sentBoxItems =
        this.Application.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderSentMail).Items;
    sentBoxItems.ItemAdd +=
        new Outlook.ItemsEvents_ItemAddEventHandler(Items_ItemsAdd);
}

private void Items_ItemsAdd(object Item)
{
    if (Item != null)
        Helpers.SaveMailSent((Outlook.MailItem)Item); // Here do stuff to save mail
}

Also pay attention to the following facts:

  1. The DeleteAfterSubmit property of the MailItem class allows to set a Boolean value that is True if a copy of the mail message is not saved upon being sent, and False if a copy is saved in Sent Items folder. So, the sent item will never be added to the Sent Items folder.
  2. The ItemAdd event is not fired if multiple items are added to the folder (usually more than sixteen). This is a well-known issue in OOM.