本文转自:https://www.codeproject.com/Articles/1112815/How-to-Create-an-Add-in-for-Microsoft-Outlook

This is a tutorial on how to create a VSTO Add-in to extend the Microsoft Outlook functionalities.

1. Introduction

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.

2. 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.

3. How to Start

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

3.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.

3.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:

Hide   Copy Code
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
}

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:

Hide   Copy Code
using Outlook = Microsoft.Office.Interop.Outlook;

And it would be like this:

Hide   Copy Code
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:

Hide   Copy Code
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:

Hide   Copy Code
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:

Quote:

“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.

Hide   Copy Code
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";
}
}
}

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.

Hide   Copy Code
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:

  • Add a new item to the project. In my case, I named it RibbonDemo.

  • In the ribbon designer, select the ribbon component and go to the Properties Window.
  • 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.
  • 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.

  • Next, we add the button from the ToolBox and ready.
  • 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.

Hide   Copy Code
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 With Other Models

In the following section, we'll see examples where access is needed to other models.

Placing ourselves in context, when we are working with an email body, there are just a few functionalities we can perform using the Outlook objects, for example, accessing the Body properties of the MailItem object. But if it's needed to get more control over the email body, it's necessary to work with it as a Word document. Next, we'll see some examples about it.

Before Starting

First, we'll see how to include the references to the Word Object Model from "Outlook 2013 and 2016 VSTO Add-in". It's important to select the same versions you're using in the Outlook application and also, select the references of tools and utilities.

In my case, I'm using the version 15.0.0.0 for Outlook.

Therefore, we'll select the same versions of the Word references.

5.1. How to Get the Selected Text in an Email Message from a Button on the Ribbon

The following example takes place in the OnClick event of a button added to the Ribbon (see previous section 4.3. How to add a control to the Ribbon toolbar).

Hide   Copy Code
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);
}
}

The following picture takes place when the user is creating a new email. In this, we can see that the application shows a message with the text where the user has selected and clicked on the "Get text selected" button.

5.2. How to Subscribe to Events Over the Email Body

In the following example, we'll demonstrate how to subscribe our application to the mouse's events that the user performs over an email body. Specifically, we'll subscribe to events from the Word document (that it represent the email body) and when the user performs a double-click on the text, we'll get the word where the click was done.

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

Hide   Copy Code
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);
}

With this Inspector, let's execute our code when the email editor is opened. At this time, we'll check that the Inspector object is a MailItem. Next, we'll check that the email editor is a Word editor (sometimes it is of another type) and, at last, we'll get the Word document object.

Hide   Copy Code
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're going to subscribe to the BeforeDoubleClick event of the Word document that we got (in previous code) and when the event is triggered, we'll select the word where the user has clicked.

Hide   Copy Code
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 get access to the user selected words by the selection object, which it has a lot of functionalities. In our example, using the Word property, we get a collection of all the selected words by the user and, the Firstproperty is where the user has clicked.

The following picture takes place when the user is creating a new email. In this, we can see that the application shows a message with the text where the user has done a double-click.

6. 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.

7. References

 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

[转]How to Create an Add-in for Microsoft Outlook的更多相关文章

  1. Home not found. Define system property "openfireHome" or create and add the openfire_init.xml file to the classpath

    启动openfire后出现这个错误,貌似什么配置没对吧.网上搜索了下,找到解决办法, $ vi /etc/profile在里面加入:export openfireHome=/opt/openfire ...

  2. Problem to create "New Database Diagram" in Microsoft SQL Server Management Studio for SQL Server 2012

    Error: when click "New Database Diagram", a error popped up and said "Attempted to re ...

  3. WMIC命令的利用技巧

    WMIC扩展WMI(Windows Management Instrumentation,Windows管理工具),提供了从命令行接口和批命令脚本执行系统管理的支持.在WMIC出现之前,如果要管理WM ...

  4. SharePoint自动化系列——Create a local user and add to SharePoint

    转载请注明出自天外归云的博客园:http://www.cnblogs.com/LanTianYou/ 实现过程:在本地创建一个local user并将该user添加到Administrators组中, ...

  5. 通过TStringList保存csv文件,只要循环.Add表格里面的每行记录进去,保存即可

    dlgSave := TSaveDialog.Create(nil); dlgSave.filter := 'CSV文件|*.CSV'; dlgSave.DefaultExt := '*.CSV'; ...

  6. Add AI feature to Xamarin.Forms app

    Now, AI is one of important technologies.Almost all platforms have API sets of AI. Following list is ...

  7. How to automate Microsoft Word to create a new document by using Visual C#

    How to automate Microsoft Word to create a new document by using Visual C# For a Microsoft Visual Ba ...

  8. 使用create react app教程

    This project was bootstrapped with Create React App. Below you will find some information on how to ...

  9. CREATE FUNCTION - 定义一个新函数

    SYNOPSIS CREATE [ OR REPLACE ] FUNCTION name ( [ argtype [, ...] ] ) RETURNS rettype { LANGUAGE lang ...

随机推荐

  1. asp.net—单例模式

    一.单例模式是什么? 定义:确保一个类仅仅能产生一个实例,并且提供一个全局访问点来获取该实例. 二.单例模式怎么用? class SingleCase { public string Name{get ...

  2. Ruby on Rails 目录结构

    目录结构 + app/ #控制器.模型.视图.帮助方法.邮件.静态资源 + bin/ #rails脚本 + config/ #路由.数据库等 + db/ #数据库模式.迁移文件 + lib/ #扩展模 ...

  3. 673. Number of Longest Increasing Subsequence

    Given an unsorted array of integers, find the number of longest increasing subsequence. Example 1: I ...

  4. linux parallel rsync 拷贝N多文件

    先来个对比图看一下, 左边图是普通 rsync 目录拷贝, 右边图是借助 parallel 工具并发起了多个 rsync centos6.5安装 parallel #!/bin/bash # Inst ...

  5. Centos出现-bash: unzip: command not found的解决办法

    利用unzip命令解压缩的时候,出现-bash:  unzip: command not found的错误. unzip——命令没有找到,其原因肯定是没有安装unzip. 利用一句命令就可以解决了.  ...

  6. Python小白学习之路(四)——第一次练习题

    写在前面: 今天下雪了呢!连着两天都没有更新学习记录. 我没有偷懒呢.做了一天的练习题,昨天学的内容还没总结完,太累了就回去睡觉了 连续一周早起,强大的内心也无法支撑我疲惫的身体 今天早起做了整理.加 ...

  7. python多态和鸭子类型

    多态与多态性 多态指的是一类事物有多种形态,(一个抽象类有多个子类,因而多态的概念依赖于继承). 比如:文件分为文本文件,可执行文件(在定义角度) 比如 我们按下 F1 键这个动作: 如果当前在 Fl ...

  8. iOS开发证书与配置文件的使用

    前提 众所周知,开发iOS应用必须要有iOS证书(Certificates)和配置文件(Provisioning Profiles),那么问题来了: 1.什么是iOS证书,它是如何与app应用关联的? ...

  9. MySQL介绍及安装(一)

    一.关系型数据库和非关系型数据库 1.1:关系型数据库 关系型数据库是把复杂的数据结构归结为简单的二元关系(即二维表格的形式),在关系型数据库中,对数据的操作几乎全部建立在一个或多个关系表格上的,通过 ...

  10. Neko and Aki's Prank CodeForces - 1152D (括号序列,dp)

    大意: 将所有长度为2*n的合法括号序列建成一颗trie树, 求trie树上选出一个最大不相交的边集, 输出边集大小. 最大边集数一定不超过奇数层结点数. 这个上界可以通过从底层贪心达到, 所以就转化 ...