How to access Outlook (Office365) Emails using C#

The task I was assigned was to:

  • access an Outlook account from a C# program
  • read the content of each email
  • parse the content into a database and
  • move the emails to a folder (“Processed” folder for example).

To start, I created a Console application using Visual Studio. Added a reference to Microsoft.Office.Interop.Outlook library using NuGetPackage Manager.

NugetPackage

Once you add this library to your references, the following code should work.

Add this line in the usings section:

using Outlook = Microsoft.Office.Interop.Outlook;

Here is the class file with the logic.

public static void ReadEmails()
{
  try
  {
    Outlook.Application oApp = new Outlook.Application();

    // Get the MAPI namespace.
    Outlook.NameSpace oNs = oApp.GetNamespace("MAPI");

    oNs.Logon("Orders@company.com", System.Reflection.Missing.Value,
    System.Reflection.Missing.Value, System.Reflection.Missing.Value);

    Outlook.MAPIFolder inboxFolder = oNs.Folders["Account1"].Folders["Inbox"];
    Outlook.MAPIFolder processedFolder =
    oNs.Folders["Account1"].Folders["Processed"];

    Console.WriteLine(inboxFolder.Items.Count);
    foreach (Outlook.MailItem mailItem in inboxFolder.Items)
    {
      // read the email only if its unread
      if (mailItem.UnRead)
      {
         Console.WriteLine(mailItem.Subject);
         Console.WriteLine(mailItem.SenderName);
         Console.WriteLine(mailItem.ReceivedTime);
         Console.WriteLine(mailItem.Body);

         var body = mailItem.Body;
         if (!string.IsNullOrEmpty(body))
         {
            // parse the email body as needed
         }

         // check for attachments
         if (mailItem.Attachments.Count > 0)
         {
            // process the attachments as desired
         }

         // mark the email as read
         mailItem.UnRead = false;

         // Based on the folder structure, move the email to a particular folder
         mailItem.Move(processedFolder);
      }
    }

    oNs.Logoff();
  }
  catch (Exception e)
  {
    Console.WriteLine("{0} Exception caught: ", e);
  }
}

Notice that the code looks for “Account1”. You would use this code when you have access to more than one Outlook accounts/Folders and you want to access the account/Folder with name “Account1”.

If you do not know the name of your account/Folder, you can get the names of your accounts/Folders using the following code.

var folders = oNs.Folders;

The property that will give you the name of the Folder is the “FolderPath”.

But, if you only have one email account to access, this line will return the inbox.

Outlook.MAPIFolder inboxFolder = oNs.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);

That’s it. Hope that helps!