[Switch] Create a Microsoft Outlook extension

This article is reprinted from: https://coyee.com/article/10625-how-to-create-an-add-in-for-microsoft-outlook

1 Introduction

The Visual Studio Tool for Office (VSTO) add-in is a set of tools available in the .NET Framework that allow us to extend and customize Microsoft Office products in (version 2003 and later).

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

2. Outlook Object Model

This is the starting point when you want to create an Outlook add-in, it's important to understand what these objects mean.

Outlook Object Model:

  • Application: It represents the Outlook application and is the highest level object in the model. This object is the starting point for other objects reaching the model.
  • Explorer: It represents a window to display the contents of a folder such as emails, messages, tasks, appointments, etc.
  • Inspector: It represents a window that displays items such as email messages, tasks, appointments, etc.
  • MAPIFolder: It represents a folder containing emails, contacts, appointments, etc. Remark: This object is obsolete, instead you should use the Folder  object instance of MAPIFolder.
  • MailItem: It represents an email.
  • AppointmentItem: It represents a meeting, a one-time appointment, an agenda appointment, or a meeting in a calendar  folder.
  • TaskItem: It represents a task to be executed within a specified time frame.
  • ContactItem: It represents a contact in the Contact folder.
 

3. How to get started

In the next section, we'll start with this type of application.

3.1. How to create a project

  1. Start Visual Studio.
  2. File menu / New / Project.
  3. In the project's Model panel, open Visual C#, Office/SharePoint, Office Add-ins.
  4. Select Outlook 2013 and 2016 VSTO add-ins to join the model.
  5. Fill in the project name and click OK.

3.2. Project Layout

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

The main class is  ThisAddIn , the code looks 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 /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InternalStartup() { this.Startup += new System.EventHandler(ThisAddIn_Startup); this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown); } #endregion }
 

This is a very simple class. The ThisAddIn_Startup method is the starting point of the application. In this method, we can get the object Application and other objects of the model. Additionally, we can perform our initialization procedures such as configuring and accessing the database.

The ThisAddIn_Shutdown method is executed when the user closes Outlook. But importantly, in the current version of Outlook, this method is not called due to performance issues. However, if some code needs to be executed when Outlook is closed, you can check this link for other options.

 

3.3. Application Objects and Other Model Objects

Next, we'll see how to get some object models. Therefore, we need to use the necessary namespace:

using Outlook = Microsoft.Office.Interop.Outlook;

The code looks 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); } }
 

Other object models can be obtained by using  Inspector and  Explorer objects. The action is usually event-based, so you need to register for events created by these two objects. The code is probably 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); }

Inspectors_AddTextToNewMail is the method that implements our function as follows:

 
void Inspectors_AddTextToNewMail(Outlook.Inspector inspector) { }

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

3.4. At the end of the project

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

3.5. How to make an installer

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

Note: Sometimes the installer generated by Visual Studio may fail to install on the user's computer and you should receive the following error message:

 

Quote:

"Cannot resolve value for property 'type'. Error: Could not load file or assembly...".

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

4. Basic example

In the next section, we'll show some examples on how to create a VSTO add-in for Outlook 2013.

4.1. How to handle new emails

The example below is that when a user creates a new email, we insert custom text in the subject and body of the email. To accomplish this task, we need ThisAddIn_Startupto register a new method in  the method Inspector , which will be invoked when the user creates or opens an email Inspectors_AddTextToNewMail.

 
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 Inspecto 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"; } } }
 

Note: The class needs to be checked  because we don't know which object will be executed  mailItem 对象是否是一种 MailItem when this event is fired, through Outlook's user action .Inspector

4.2. How to handle a sending email

The example below is to allow us to update the message in the email when the email is sent. This is a very interesting and applicable feature. There are Outlook add-ins that do this type of thing, for example, antivirus software that needs to include a signature when a message is sent.

To accomplish these functions, we will ItemSend 事件中插入我们的代码。当一个邮件通过用户或者计划任务被发送时,这个事件就会被触发。

 
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 Controls to the Ribbon Toolbar

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

Do the following:

  • Add a new item to the project. In this example, I named it RibbonDemo.

  • In the Ribbon Designer, select the Ribbon component and go to the Properties window.
  • Find the RibbonType property and select the values ​​for Microsoft.Outlook.Mail.Compose and Microsoft.Outlook.Mail.Read, which refers to the ribbon for creating and reading emails.
  • We set an appropriate name for the group. To finish it, select it and look for the Label property in the properties window and type a name for it.

  • Next, we add the button from the ToolBox and get it ready.
  • Alternatively, using the button's ControlSize and ShowImage properties, we can complete the look of the Microsoft Office product. ​​​​​​​

 

Next just like developing a C# desktop application, let's write ButtonDemo按钮的OnClick事件来处理邮件消息。

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. Examples of other object models

In the following sections we will see examples where we need to access other object models.

Putting our content in context, when we use the email body, we can use the Outlook object to perform some functions, such as accessing the Body property of the MailItem object. However, if you need more control over the body of the email, you need to make it a Word document. Next, we'll see some examples.

before the start

First, we'll see how to reference the Word Object Model from the Outlook 2013 and 2016 VSTO Add-in. It is important to select the same version you are using in the Outlook application and to select references to tools and utilities.

 

In my case I was using Outlook version 15.0.0.0.

Therefore, we will choose the same version of the Word reference.

5.1. How to get the selected text in an email via a button on the Ribbon.

The following example is a OnClick button with an event added to Ribbon(see previous section 4.3. How to add a control to a  Ribbon toolbar).

private void button2Demo_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) { Word.Document document = (Word.Document) inspector.WordEditor; string selectedText = document.Application.Selection.Text; MessageBox.Show(selectedText); } }
 

When a user creates a new email, the following image appears. Here we can see that the application displays a message with the text that the user has selected and clicked the "Get Text Selection" button.

5.2. How to subscribe to the events of the email body

In the following example, we will demonstrate how to subscribe our application to an event that the user executes through the body of the email. Specifically, we'll subscribe to an event in the Word document (which represents the email body), and when the user double-clicks on the text, we'll get the word when the click was done.

 

We'll start with the application entry point where we'll create an Inspector object to monitor when the user creates/edits an email.

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_RegisterEventWordDocument); }

Using this Inspector, we execute our code when the email editor is opened. At this point, we'll check if the Inspector object is a MailItem. Next, we'll check if the email editor is a Word editor (sometimes another type), and finally we'll get the Word document object.

 
void Inspectors_RegisterEventWordDocument(Outlook.Inspector inspector)
{
    Outlook.MailItem mailItem = inspector.CurrentItem as Outlook.MailItem;
    if (mailItem != null) {
        // Check that the email editor is Word editor // Although "always" is a Word editor in Outlook 2013, it's best done perform this check if (inspector.EditorType == Outlook.OlEditorType.olEditorWord && inspector.IsWordMail()) { // Get the Word document Word.Document document = inspector.WordEditor; if (document != null) { // Subscribe to the BeforeDoubleClick event of the Word document document.Application.WindowBeforeDoubleClick += new Word.ApplicationEvents4_WindowBeforeDoubleClickEventHandler( ApplicationOnWindowBeforeDoubleClick); } } } }
 

Next, we'll subscribe to the BeforeDoubleClick event of the Word document we got (in the previous code), and when the event fires, we'll select the word the user clicked.

private void ApplicationOnWindowBeforeDoubleClick(Word.Selection selection, ref bool cancel) { // Get the selected word Word.Words words = selection.Words; MessageBox.Show("Selection: " + words.First.Text); }

We can access the word selected by the user through the "selection" object, which has many functions. In our example, using the Word property, we get the set of all the user's selected words, the first property is where the user clicked.

 

When a user creates a new email, the following image appears. Here, we can see that the application displays a message with the text that the user double-clicked.

6 Conclusion

As can be seen, using the VSTO add-in tool, we can easily extend Outlook functionality in a number of ways. In my opinion, this kind of application in the enterprise sector has a lot of requirements to solve certain problems quickly, and usually office users are more satisfied with Microsoft Office products than other applications. Using the VSTO add-in, we can query the database for employee contacts, include product listings in emails, sync appointments between enterprise applications and Outlook, and more.

7. References

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324820429&siteId=291194637