How to Programmatically Read Outlook Inbox Mail using C#

This article describes how to create a C# program that reads mails from your outlook inbox. You can do this using the Microsoft.Office.Interop.Outlook.dll.

Here is the step by step procedure of creating automation of reading outlook mails by C#.

Step1: Add reference to Microsoft.Office.Interop.Outlook library to your project.

using Outlook = Microsoft.Office.Interop.Outlook;

Step 2: Define the function ReadOutlookMail().

Public void ReadOutlookMail()
{

}

Step 3: Create instance of Outlook application.

Outlook.Application oApp = new Outlook.Application();

Step 4: Get the MAPI namespace.

Outlook.NameSpace oNS = oApp.GetNamespace("mapi");

Step 5: Logon to outlook using default profile or existing session.

oNS.Logon("[email protected]", Missing.Value, true, true);

Step 6: Navigating to the folder of which mail are to be read.

Outlook.MAPIFolder oInbox = oNS.Folders["[email protected] "].Folders["Inbox"].Folders["myInbox"];

Step 7: Get the Items collection in the Inbox folder.

Outlook.Items oItems = oInbox.Items;

Step 8: Defining the foreach loop to iterate to each MailItem of Inbox.

foreach (Outlook.MailItem oMsg in oInbox.Items)
{

}

In this foreach loop, you can iterate to each mail in inbox to read. You can use various properties of MailItem to read the mail subject, mail received time, sender ID, count of attachment etc.

The entire code will like below.

Public void ReadOutlookMail()
{
    Outlook.Application oApp = new Outlook.Application();
    Outlook.NameSpace oNS = oApp.GetNamespace("mapi");
    oNS.Logon("[email protected]", Missing.Value, true, true);
    Outlook.MAPIFolder oInbox = oNS.Folders["[email protected] "].Folders["Inbox"].Folders["myInbox"];
    Outlook.Items oItems = oInbox.Items;
    foreach (Outlook.MailItem oMsg in oInbox.Items)
    {
      //Reading the subject of mail
      Console.WriteLine(oMsg.Subject);
      //Reading the name of sender
      Console.WriteLine(oMsg.SenderName);
      //Reading the receiving date, time of mail
      Console.WriteLine(oMsg.ReceivedTime);
      //Reading the body of mail
      Console.WriteLine(oMsg.Body);
      //Reading the count of attachment
      int AttachCnt = oMsg.Attachments.Count;
      Console.WriteLine("Attachments: " + AttachCnt.ToString());
    }
}

When you run the above code, it will read the subject, name of sender, receiving data & time, body and attachment count of each mail in myInbox folder of Inbox and will write on console.

Leave a Reply