Monday, July 1, 2013

Looping through your e-mails with outlook interop with c#

Last week we needed a small tool that checked the body of an e-mail. I found out that it only takes a couple of lines using Outlook Interop to do so. Super fast, super easy:
using System;
using Microsoft.Office.Interop.Outlook;

namespace OutlookReader
{
    class Program
    {
        static void Main(string[] args)
        {
            Microsoft.Office.Interop.Outlook.Application app = null;
            Microsoft.Office.Interop.Outlook._NameSpace ns = null;
            Microsoft.Office.Interop.Outlook.MailItem item = null;
            Microsoft.Office.Interop.Outlook.MAPIFolder inboxFolder = null;
            Microsoft.Office.Interop.Outlook.MAPIFolder subFolder = null;

            try
            {
                app = new Application();
                ns = app.GetNamespace("MAPI");
                ns.Logon(null, null, false, false);

                inboxFolder = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
                subFolder = inboxFolder; // or use folder.Folders["Folder Name"];

                Console.WriteLine("Folder Name: {0}, EntryId: {1}", subFolder.Name, subFolder.EntryID);
                Console.WriteLine("Num Items: {0}", subFolder.Items.Count.ToString());

                for (int i = 1; i <= subFolder.Items.Count; i++)
                {
                    item = (MailItem)subFolder.Items[i];
                    Console.WriteLine("Subject: {0}", item.Subject);
                }
            }
            catch (System.Runtime.InteropServices.COMException ex)
            {
                Console.WriteLine(ex.ToString());
            }
            finally
            {
                ns = null;
                app = null;
                inboxFolder = null;
            }
        }
    }
}
This only works with outlook installed, so if you want to use it on your server, you'll have to install outlook. Does anybody know any other good way to access mail without the native MAPI32?

Cheers,
Luuk