Freigeben über


How To: Add Outlook Ribbon Button That Generates A Document From Emails

Sharepoint 2010 Development I needed a functionality that allows me to generate Word documents out of email items managed in my Outlook 2010. The scenario would be:

  • Search emails using Outlook 2010 instant search.
  • Copy related items to a designated folder
  • Press a button
  • Work document is generated including all email items in the designated folder

I used this resource to get started – Building and deploying an Outlook 2010 Add-in (part 1 of 2). Part 2 is here - Building and deploying an Outlook 2010 Add-in (part 2 of 2).

After completing the steps of adding a button to a ribbon, I added a code to the button click event handler that collects all email items in the specific folder (3rd one under the Inbox folder).

Here is the code that runs:

 MAPIFolder inBox = (MAPIFolder)e.Control.Context.Application.ActiveExplorer().Session.GetDefaultFolder
   (OlDefaultFolders.olFolderInbox);
try
{
    MAPIFolder inBoxfolder = inBox.Folders[3];
    e.Control.Context.Application.Application.ActiveExplorer().CurrentFolder = inBoxfolder;
    e.Control.Context.Application.Application.ActiveExplorer().CurrentFolder.Display();
    StringBuilder sb = new StringBuilder();
    for (int i = 1; i <= inBoxfolder.Items.Count; i++)
    {
        if (inBoxfolder.Items[i] is PostItem)
        {
            PostItem pi = (PostItem)inBoxfolder.Items[i];
            sb.Append("<h1>");
            sb.Append(pi.Subject);
            sb.Append("</h1>");
            sb.Append(pi.HTMLBody);
        }
    }
    using (StreamWriter sw = new StreamWriter(@"C:\GeneratedFile.doc"))
    {
        sb.Replace("<html>", "");
        sb.Replace("</html>", "");
        sw.Write(sb.ToString());

        Process.Start(@"C:\GeneratedFile.doc");
    } 
}

NTOE: This code is less than optimal and should be improved for its quality. But it can perfectly get you started if you have the same goal as I did in first place.