2

I am attempting to write an AddIn that can modify an Outlook MailItem when it is loaded (either through a preview pane or through it being opened). Here is the code that I have so far, but I can't seem to actually access the MailItem

public partial class ThisAddIn
{
    private void ThisAddIn_Startup(object sender, EventArgs e)
    {
        Application.ItemLoad += ApplicationOnItemLoad;
    }

    private void ApplicationOnItemLoad(object item)
    {
        var mail = item as MailItem;

        if (mail != null)
        {
            Console.WriteLine(mail.HTMLBody);
        }
    }

    // Etc...
}

The code reaches the Console.WriteLine(mail.HTMLBody); statement just fine, meaning that casting the item as an Outlook MailItem is fine (it doesn't end up being null). However, I can't access any of the MailItem members... it just throws exceptions:

A first chance exception of type 'System.Runtime.InteropServices.COMException' occurred in MyOutlookProject.DLL
A first chance exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.dll

JimmyPena
  • 8,694
  • 6
  • 43
  • 64
myermian
  • 31,823
  • 24
  • 123
  • 215

1 Answers1

2

Application.ItemLoad occurs prior to the item being fully loaded. You cannot read any properties on the Item other than Class and MessageClass.

From MSDN...

This event occurs when the Outlook item begins to load into memory. Data for the item is not yet available, other than the values for the Class and MessageClass properties of the Outlook item, so an error occurs when calling any property other than Class or MessageClass for the Outlook item returned in Item.

To access the MailItem in the Preview Pane, you should look at Explorer.Selection. To access the MailItem that has been opened (via inspector) - leverage Inspectors.NewInspector.

Community
  • 1
  • 1
SliverNinja - MSFT
  • 31,051
  • 11
  • 110
  • 173