Skip to main content

Tutorial: How to Create an Add-in for Microsoft Outlook

Visual Studio Tool for Office (VSTO) Add-in is a toolset available in .NET Framework that lets us extend and customize the Microsoft Office products in (versions 2003 and later).

In this tutorial, we are going use Outlook 2013 as a case study and Visual Studio 2015.

Version on CodeProject

Download source code

1. Outlook Object Model


This is the starting point when we want to create an Outlook Add-in and it's important to understand the meaning of these objects.

Outlook Object Model:
  • Application: It represents the Outlook application and is the highest-level object in the model. This object is the starting point to reach the other objects of the model.
  • Explorer: It represents a window to display the folder's contents, such as emails, message, tasks, appointments, etc.
  • Inspector: It represents a window to display an item, such as an email message, a task, an appointment, etc.
  • MAPIFolder: It represents a folder that contains emails, contacts, appointments, etc.
    Remark: This object is obsoleted and, in substitution, you should use Folder object instance of MAPIFolder.
  • MailItem: It represents an email message.
  • AppointmentItem: It represents a meeting, a one-time appointment, schedule appointment or a meeting in the Calendar folder.
  • TaskItem: It represents a task to be performed within a specified time frame.
  • ContactItem: It represents a contact in the Contact folder.

2. How to Start


In the following section, we are going to start in this type of applications.

2.1. How to Create the Project

  1. Start Visual Studio.
  2. File menu / New / Project.
  3. In the template panel of the project, open Visual C#, Office/SharePoint, Office Add-ins.
  4. Select Outlook 2013 and 2016 VSTO Add-in template.
  5. Complete the project name and click OK.

2.2. Project Layout


Actually, the project layout generated for Visual Studio is very intuitive and simple.

The main class is ThisAddIn and is like this:

public partial class ThisAddIn
{
    private void ThisAddIn_Startup(object sender, System.EventArgs e)
    {
    }

    private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
    {
        // Note: Outlook no longer raises this event. If you have code that
        //    must run when Outlook shuts down, see
        //    http://go.microsoft.com/fwlink/?LinkId=506785
    }

    #region VSTO generated code

    /// 
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// 

    private void InternalStartup()
    {
        this.Startup += new System.EventHandler(ThisAddIn_Startup);
        this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
    }

    #endregion
}

It's a very simple class. The ThisAddIn_Startup method is the application starting point. In this method, we can get the object Application and the other objects model. Also, we can perform our initialization processes such as configurations and access to a database.

The ThisAddIn_Shutdown method is executed when the user closes the Outlook. But it is important to say that in the current version, this method is not being called due to performance issues. However, if it's needed to perform some code when the Outlook is being closed, you can check this link for an alternative.

3.3. Application Object and the Others Model Objects


Next, we are going to see how to get others objects model. For this, we require to use the needed namespace:

using Outlook = Microsoft.Office.Interop.Outlook;

And it would be like this:

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

    // Get the Inspector object
    Outlook.Inspectors inspectors = application.Inspectors;

    // Get the active Inspector object
    Outlook.Inspector activeInspector = application.ActiveInspector();
    if (activeInspector != null)
    {
        // Get the title of the active item when the Outlook start.
        MessageBox.Show"Active inspector: " + activeInspector.Caption);
    }

    // Get the Explorer objects
    Outlook.Explorers explorers = application.Explorers;    

    // Get the active Explorer object
    Outlook.Explorer activeExplorer = application.ActiveExplorer();
    if (activeExplorer != null)
    {
        // Get the title of the active folder when the Outlook start.
        MessageBox.Show("Active explorer: " + activeExplorer.Caption);
    }
}
The other objects model can be obtained using the Inspector and Explorer objects. The how-to do it is generally event-based, for this reason, is necessary to subscribe to the events triggered by these two objects. It would be like this:

private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
    // …
    // Add a new Inspector to the application
    inspectors.NewInspector +=
        new Outlook.InspectorsEvents_NewInspectorEventHandler(
            Inspectors_AddTextToNewMail);
}

The Inspectors_AddTextToNewMail method is where would take place our functionality and it would be like this:

void Inspectors_AddTextToNewMail(Outlook.Inspector inspector)
{
}

The inspector param should be a reference to an email message or a contact, depending on the user action in the Outlook.


3.4. At the Project Ending


At the project ending, to remove the add-in from Outlook on the development computer, go to Build menu in Visual Studio and click on Clean Solution option.

3.5. How to Make An Installer


In Visual Studio, go to Build menu / "Publish...".

Remark: Sometimes, the installer generated by Visual Studio may fail when it is being installed in the user computer and you should get the following error message:

“The value of the property 'type' cannot be parsed. The error is: Could not load file or assembly …“.

To solve this error, check out this link and this link.

4. Basic Examples


In the following section, we are going to see some examples about creating a VSTO Add-in for Outlook 2013.

4.1. How to Handle a New Email Message


The following example takes place when the user creates a new email message and in this case, we'll put a custom text in the email subject and body. To accomplish it, in the ThisAddIn_Startup method, we need to register a new Inspector that when the user creates or open an email, this will call the Inspectors_AddTextToNewMail method.

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

    // Add a new Inspector
    inspectors.NewInspector +=
        new Outlook.InspectorsEvents_NewInspectorEventHandler(
            Inspectors_AddTextToNewMail);
}

void Inspectors_AddTextToNewMail(Outlook.Inspector inspector)
{
    // Get the current item for this Inspector object and check if is type
    // of MailItem
    Outlook.MailItem mailItem = inspector.CurrentItem as Outlook.MailItem;
    if (mailItem != null)
    {
        if (mailItem.EntryID == null)
        {
            mailItem.Subject = "My subject text";
            mailItem.Body = "My body text";
        }
    }
}

Remark: It's needed to check if the mailItem object is a type of MailItem class because when this event is triggered, by a user action in Outlook, we don't know which Inspector object will have been executed.

4.2. How to Handle an Email When It's Sent


The following example allows us to update an email message when it's sent, which is a very interesting and applicable functionality. There are Outlook add-ins that perform these type of operations, for example, the antivirus when they include a signature in the emails sent.

To accomplish it, we are going to subscribe our code to the ItemSend event, that it's triggered when an element is sent by the user or by a schedule operation.

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

    // Subscribe to the ItemSend event, that it's triggered when an email is sent
    application.ItemSend +=
        new Outlook.ApplicationEvents_11_ItemSendEventHandler(
            ItemSend_BeforeSend);
}

void ItemSend_BeforeSend(object item, ref bool cancel)
{
    Outlook.MailItem mailItem = (Outlook.MailItem) item;
    if (mailItem != null)
    {
        mailItem.Body += "Modified by GettingStartedOutlookAddIn";
    }
    cancel = false;
}

4.3. How to Add a Control to the Ribbon Toolbar


In the following example, we'll see how to add controls to the ribbon (the toolbar) in Outlook. Specifically, how to add a button to the ribbon when the user edits or reads an email message.

Do the following:
  1. Add a new item to the project. In my case, I named it RibbonDemo.
  2. In the ribbon designer, select the ribbon component and go to the Properties Window.
  3. Look for RibbonType property and select the values Microsoft.Outlook.Mail.Compose and Microsoft.Outlook.Mail.Read, which it refers to the ribbons of creating and reading email messages.
  4. Let's set an appropriate name to the group. To accomplish it, select it and look for the Label property in the Property Window and type a name for it.
  5. Next, we add the button from the ToolBox and ready.
  6. Optionally, using the ControlSize and ShowImage properties of the button, we can accomplish the Microsoft Office products' appearance.
What comes next is like any C# desktop application. Let's program the OnClick event of the button ButtonDemo and handle the email message.

private void buttonDemo_Click(object sender, RibbonControlEventArgs e)
{
    // Get the Application object
    Outlook.Application application = Globals.ThisAddIn.Application;

    // Get the active Inspector object and check if is type of MailItem
    Outlook.Inspector inspector = application.ActiveInspector();
    Outlook.MailItem mailItem = inspector.CurrentItem as Outlook.MailItem;
    if (mailItem != null)
    {
        MessageBox.Show("Subject: " + mailItem.Subject);
    }
}

5. Conclusion


As can be seen, we can extend the Outlook functionalities in many ways and easily, using the VSTO Add-in tools. In my opinion, there're many requirements to this type of application in the enterprise sectors that resolve some kind of problems in a quick way, and also, usually the office users feel comfortable with Microsoft Office products than others applications. With VSTO Add-in, we can query databases to get employee's contacts, product list to include on emails, synchronize appointments between an enterprise application and the Outlook, and so on.

6. References

Comments

Popular posts from this blog

How to use Font Awesome with IText

This post is about on how to use Font Awesome with IText library to generate awesome icons in our PDF documents. In this post, we are using  ITextSharp , a C# port for IText, but those are the same functionalities.

TinyMCE: anti-forgery token failed on file upload in an ASP.NET Boilerplate application

TinyMCE is an excellent full featured and well documented web editor that we can use in our web applications. But, integration with ASP.NET MVC 5 (as part of the ASP.NET Boilerplate technology stack) may be tricky to accomplish. When you set up the file upload plugin in TinyMCE, you have to consider the ASP.NET MVC 5 anti-forgery system. Otherwise, HTTP requests may fail loading resources to server due to an invalid or empty anti-forgery token error. This is a security and technology concern that can run out your time if you don't know about it. This article explains how this mechanism works and shows some solutions in an ASP.NET Boilerplate application.