Wednesday, February 3, 2010

Working with Outlook Interop or how to read your email messages from C#

It is very staight forward to send emails using .NET SmtpClient and MailMessage class, but how to read email you get?

If you use Outlook, it can be done via Outlook Interop:


http://msdn.microsoft.com/en-us/library/ms268893(VS.80).aspx


The use is simple, but there is important "gotcha": your Inbox folder have many objects and they can be of diferent types, so you have to check type before you cast. Like this:

if (item is Microsoft.Office.Interop.Outlook.MailItem)
{
   // This is email mesage
}

Note, that there are many folders and you can have subfolders inside inbox. To iterate all these you need to write a bit more code than bellow.

Here is just a simple example of how to print out all messages in your Inbox on just one level:


namespace EmailReader

{

       using System;
       using Microsoft.Office.Interop.Outlook;

        class Program
       {

             static void Main(string[] args)
           {

                   Application outlook = new Microsoft.Office.Interop.Outlook.ApplicationClass();

                  NameSpace mapiNameSpace = outlook.GetNamespace("MAPI");

                  MAPIFolder inbox = mapiNameSpace.GetDefaultFolder(OlDefaultFolders.olFolderInbox);

                  foreach (Object item in inbox.Items)
                 {
                         if (item is Microsoft.Office.Interop.Outlook.MailItem)
                        { 
                               MailItem mailItem = (MailItem)item;

                               Console.WriteLine(mailItem.Subject);
                               Console.WriteLine(mailItem.SentOn); 
                               Console.WriteLine(mailItem.Body); 
                               Console.WriteLine(mailItem.To); 
                               Console.WriteLine(mailItem.CC);
                               Console.WriteLine("*********************************");
                       }
                 }
               // outlook.Quit();
     }
  }
}