Pieter van der Westhuizen

Outlook NewMail event and Extended MAPI: C# example

In part 1 of the Outlook NewMail unleashed series, we’ve looked at the problems facing us as Outlook developers when it comes to effectively handling a new e-mail in Outlook. We’ve also seen that the NewMailEx and Folder Items Add events aren’t entirely reliable. In part 2 of the series we looked at two approaches that are alternatives to NewMailEx and the Folder Items Add events for catching new mails in Outlook.

In part 3, we will be moving the theory aside and rather focus on the code. Let us write an add-in using Extended MAPI and Add-in Express for Office .net.

Before we get started you need to head over to the Free stuff page on the Add-in Express website and download the MAPI Accessor for .Net 2.3. This .Net component will allow us to access any low-level MAPI features.

Once you’ve downloaded and installed the MAPI Accessor component, create a new ADX COM Add-in in Visual Studio.

Creating a new COM Add-in in Visual Studio

When prompted, select Visual C# Project and Microsoft Office 2000.

Selecting Visual C# Project and Office 2000 as the minimum supported version

And of course, we need to select Microsoft Outlook as the Supported Application.

Selecting Microsoft Outlook as the supported application

To keep things relatively simple our add-in will process new e-mails on arrival and save some of the details in a Microsoft Access database.

With the AddinModule designer open, open your Toolbox in Visual Studio. If you’ve installed the MAPI Accessor component you should see it the Visual Studio Toolbox.

MAPI Accessor component

Drag an instance of the ADXMAPIStoreAccessor component from the toolbox onto the AddinModule designer surface. Change its AsyncInterval property to 1000, the AsycnNotifications property to True and set SupportedStoreEvents to NewMail. What these properties mean is that the component will check the MAPI store for any NewMail notifications every 1000 milliseconds or every second.

Next, we need to add an event handler for the MAPI Store Accessor’s OnNewMail event. Generate a new event handler for it by double clicking next to the OnNewMail event in the property grid.

Adding an event handler for the MAPI Store Accessor's OnNewMail even

Add the following code to the event handler.

C# code example

private void adxmapiStoreAccessor1_OnNewMail(object sender,
    AddinExpress.MAPI.ADXMAPINewMailNotificationEventArgs e)
{
 
    AddinExpress.MAPI.MapiItem item = null;
    try
    {
        item = adxmapiStoreAccessor1.GetMapiItem(e.EntryId);
 
        Email newMail = new Email();
        newMail.EntryId = e.EntryId.ToString();
        newMail.StoreId = e.StoreId.ToString();
        newMail.ParentId = e.ParentId.ToString();
        newMail.Subject = item.GetProperty(
			AddinExpress.MAPI.ADXMAPIPropertyTag._PR_SUBJECT).ToString();
        newMail.SenderEmail = item.GetProperty(
			AddinExpress.MAPI.ADXMAPIPropertyTag._PR_SENDER_EMAIL_ADDRESS).
			ToString();
        newMail.DateReceived = DateTime.Now;
        newMail.Save();
    } 
    finally
    {
        item.Dispose();
    }            
}

You’ll notice I use a custom Email class to save the values to the database. The code for the class looks like this:

public class Email
{
    public string EntryId { get; set; }
    public string StoreId { get; set; }
    public string ParentId { get; set; }
    public string Subject { get; set; }
    public string SenderEmail { get; set; }
    public DateTime DateReceived { get; set; }
 
    public Email()
    {
    }
 
    public void Save()
    {
        using (OleDbConnection conn = new OleDbConnection(
			@"Provider=Microsoft.ACE.OLEDB.12.0;" +
			@"Data Source=C:\Development\ADX\NewMailUnleashedPart3\" +
			@"NewMailUnleashedPart3\NewMails.accdb;Persist Security Info=False;"))
        {
            conn.Open();
            using (OleDbCommand cmdSave = new OleDbCommand(
				"Insert Into NewEmails(EntryId,StoreId,ParentId,Subject," +
				"SenderEmail,DateReceived) " +
                "Values (@EntryId,@StoreId,@ParentId,@Subject," +
				"@SenderEmail,@DateReceived)", conn))
            {
                cmdSave.Parameters.AddWithValue("@EntryId", this.EntryId);
                cmdSave.Parameters.AddWithValue("@StoreId", this.StoreId);
                cmdSave.Parameters.AddWithValue("@ParentId", this.ParentId);
                cmdSave.Parameters.AddWithValue("@Subject", this.Subject);
                cmdSave.Parameters.AddWithValue("@SenderEmail", this.SenderEmail);
                cmdSave.Parameters.AddWithValue("@DateReceived",
					this.DateReceived.ToShortDateString());
                cmdSave.ExecuteNonQuery();
            }                
        }
    }        
}

A very important piece of code you need to add to the AddinStartupComplete event is to initialize the MAPI Store Accessor component:

private void AddinModule_AddinStartupComplete(object sender, EventArgs e)
{
    adxmapiStoreAccessor1.Initialize(true);
}

If all goes well, you should see the new e-mail information in your database soon after it arrives. Unfortunately this method for catching new e-mails in Outlook is not fool proof, for example the MAPI Accessor does not work for Outlook 2010 64-bit and when working with an Outlook account that is connected to an Exchange server (in cached mode), you may experience delays up to 30 minutes. There might also be certain scenarios, when using Exchange in cached mode, where notifications are missing when you close and re-open Outlook.

Thank you for reading. Until next time, keep coding!

Available downloads:

This sample add-on was developed using Add-in Express for Office .net:
Sample add-on in C#

Outlook NewMail unleashed:

5 Comments

  • https://secure.gravatar.com/avatar/2b7bac198b8d719b486d570bb8d5173b?s=32&d=https%3A%2F%2Fsecure.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D32&r=G Fabske says:

    I was waiting the next post of this series, but I feel a bit disappointed now. In fact, there is no real solution to this problem ? or you’ll publish a part 4 ?
    Because Outlook 64bit is now more often installed by company, and “sometime it will fail” is not acceptable for our customers… at least we’ve to detail in which limited cases it’ll fail.
    Thanks anyway for the post, even if it doesn’t give the promised solution

  • https://secure.gravatar.com/avatar/e1a4c2b21a5186e0b27c1c601f418b76?s=32&d=https%3A%2F%2Fsecure.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D32&r=G Pieter van der Westhuizen says:

    Hi Fabske,

    In next week’s post I’ll show you how to write your own solution to this problem that will work in all versions of Outlook, including Outlook 64bit.
    So please, stay tuned :)

    Thanks for your comment!

  • https://secure.gravatar.com/avatar/2b7bac198b8d719b486d570bb8d5173b?s=32&d=https%3A%2F%2Fsecure.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D32&r=G Fabske says:

    AAh
    Be sure I’m already waiting for the next post :)

  • https://secure.gravatar.com/avatar/f2fe1d932523ffd3f0273f66a66627de?s=32&d=https%3A%2F%2Fsecure.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D32&r=G tharindu says:

    how to install Microsoft COM add in plugin to my visual studio 2013 ?????

  • https://secure.gravatar.com/avatar/e1a4c2b21a5186e0b27c1c601f418b76?s=32&d=https%3A%2F%2Fsecure.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D32&r=G Pieter van der Westhuizen says:

    Hi Tharindu,

    If you want to use Add-in Express in your Visual Studio, you would need to purchase a license. The project templates would then be under Other Project Types > Extensibility.

    Hope this answers your question.

Post a comment

Have any questions? Ask us right now!