Outlook Add-in to read a mail


In this article, we will look into creating outlook add-in using VSTO. This add-in will read the content of a mail, once it is arrived. I am using VS 2008 and Outlook 2007 template for this add-in. Create a new Outlook 2007 project and name it as OutlookReader as shown below:

1.gif
 
Add reference to System.Speech dll in the project. We need to load the add-in on outlook startup by writing below code in ThisAddIn_Startup event:

private Office.CommandBar newToolBar;
private Office.CommandBarButton newToolBarButton;
private System.Speech.Synthesis.SpeechSynthesizer syn = new System.Speech.Synthesis.SpeechSynthesizer();
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
    // Add new Toolbar, if not exist
    if (newToolBar == null)
    {
        newToolBar = Application.ActiveExplorer().CommandBars.Add("MyToolBar", Office.MsoBarPosition.msoBarTop, false, true);
        // Add Button to Toolbar
        newToolBarButton = (Office.CommandBarButton)newToolBar.Controls.Add(Office.MsoControlType.msoControlButton, missing, missing, missing, true);
        newToolBarButton.Caption = "Stop Voice";
        newToolBarButton.Click += new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(newToolBarButton_Click);
        newToolBar.Visible = true;
    }
    Application.NewMailEx += new Microsoft.Office.Interop.Outlook.ApplicationEvents_11_NewMailExEventHandler(Application_NewMailEx);
}
// New Mail Event Handler
void Application_NewMailEx(string EntryIDCollection)
{
    try
    {
        if (((Outlook.MailItem)this.Application.Session.GetItemFromID(EntryIDCollection, missing)).UnRead)
        {
            var body = ((Outlook.MailItem)this.Application.Session.GetItemFromID(EntryIDCollection, missing)).Body;
            var subject = ((Outlook.MailItem)this.Application.Session.GetItemFromID(EntryIDCollection, missing)).Subject;
            var sender = ((Outlook.MailItem)this.Application.Session.GetItemFromID(EntryIDCollection, missing)).SenderName;
            syn.SpeakAsync("Mail From " + sender + "Subject is " + subject + body);
        }
    }
    catch
    {
    }
}

First, we are adding a toolbar button to stop reading a mail. Then, we are handling new mail event and getting subject, body of the mail using Application_NewMailEx event. Finally, the mail's content will be sent to SpeechSynthesizer's object to start speaking the mail content asynchronously. We can break the reading of the mail in middle by stopping speak/voice on toolbar button click using below code:

void newToolBarButton_Click(Microsoft.Office.Core.CommandBarButton Ctrl, ref bool CancelDefault)
{
   syn.SpeakAsyncCancelAll();
}

We can still enhance this application by adding UI and extra functionality. I am attaching source code for reference. I hope this article will be helpful for all.

Up Next
    Ebook Download
    View all
    Learn
    View all