Here's how to read emails from Outlook using C#

Here's how to read emails from Outlook using C#


You would like to build an application/addin that reads outlook mail and notify the user or would like to do some other operations based on your business need. For this, you will need to use the Microsoft Outlook APIs.

 

Today we are going to see, how this can be done using the Microsoft.Office.Interop.Outlook.dll to read the email from Outlook context and extract the data.

 

Here's how to read emails from Outlook using C# (www.kunal-chowdhury.com)

 

Most of the people uses Microsoft Outlook to read and responds to mails, either in office environments or personally. If you are going to build an app or and addin for Outlook, you will need to read the mails.

 

First you need to add the reference of Microsoft.Office.Interop.Outlook.dll file in your project. Then create the outlook application and get the MAPI namespace. Now grab the folder where you want to search for the mails.

 

Application outlookApplication = new Application();
NameSpace outlookNamespace = outlookApplication.GetNamespace("MAPI");
MAPIFolder inboxFolder = outlookNamespace.GetDefaultFolder(OlDefaultFolders.olFolderInbox);
Items mailItems = inboxFolder.Items;

 

In the above example, we have seen how to read the mail items present in the Inbox root folder. If you want to read mails present in root of Sent Items, Deleted Items etc. you can specify it using the Microsoft.Office.Interop.Outlook.OlDefaultFolders enum values. Here's the different values that the enum provides:

 

namespace Microsoft.Office.Interop.Outlook
{
    public enum OlDefaultFolders
    {
        olFolderDeletedItems = 3,
        olFolderOutbox = 4,
        olFolderSentMail = 5,
        olFolderInbox = 6,
        olFolderCalendar = 9,
        olFolderContacts = 10,
        olFolderJournal = 11,
        olFolderNotes = 12,
        olFolderTasks = 13,
        olFolderDrafts = 16,
        olPublicFoldersAllPublicFolders = 18,
        olFolderConflicts = 19,
        olFolderSyncIssues = 20,
        olFolderLocalFailures = 21,
        olFolderServerFailures = 22,
        olFolderJunk = 23,
        olFolderRssFeeds = 25,
        olFolderToDo = 28,
        olFolderManagedEmail = 29
    }
}

 

Once you have fetched the mail items out of the selected mail box, iterate through them, as shown in the below code snippet:

 

foreach (MailItem item in mailItems)
{
    stringBuilder.AppendLine("From: " + item.SenderEmailAddress);
    stringBuilder.AppendLine("To: " + item.To);
    .
    .
    .
    .
}

 

Don't forget to release the COM objects properly. You have to call 'Marshal.ReleaseComObject' method to release them. If you need the entire code from the sample shown above, here it is for your reference:

 

private static void ReadMailItems()
{
    Application outlookApplication = null;
    NameSpace outlookNamespace = null;
    MAPIFolder inboxFolder = null;
    Items mailItems = null;
 
    try
    {
        outlookApplication = new Application();
        outlookNamespace = outlookApplication.GetNamespace("MAPI");
        inboxFolder = outlookNamespace.GetDefaultFolder(OlDefaultFolders.olFolderInbox);
        mailItems = inboxFolder.Items;
 
        foreach (MailItem item in mailItems)
        {
            var stringBuilder = new StringBuilder();
            stringBuilder.AppendLine("From: " + item.SenderEmailAddress);
            stringBuilder.AppendLine("To: " + item.To);
            stringBuilder.AppendLine("CC: " + item.CC);
            stringBuilder.AppendLine("");
            stringBuilder.AppendLine("Subject: " + item.Subject);
            stringBuilder.AppendLine(item.Body);
 
            Console.WriteLine(stringBuilder);
            Marshal.ReleaseComObject(item);
        }
    }
    catch { }
    finally
    {
        ReleaseComObject(mailItems);
        ReleaseComObject(inboxFolder); 
        ReleaseComObject(outlookNamespace); 
        ReleaseComObject(outlookApplication);
    }
}
 
private static void ReleaseComObject(object obj)
{
    if (obj != null)
    {
        Marshal.ReleaseComObject(obj);
        obj = null;
    }
}

 

Hope the information and the code shared above is helpful. Make sure to release COM objects as mentioned above. Remember that, the code will execute only when Outlook is installed in the user system as the referenced dll (i.e. Microsoft.Office.Interop.Outlook.dll) is a wrapper on top of Outlook.exe file. If you have any queries/issues let me know. Have a great day ahead!

 

 



If you have come this far, it means that you liked what you are reading. Why not reach little more and connect with me directly on Twitter, Facebook, Google+ and LinkedIn. I would love to hear your thoughts and opinions on my articles directly. Also, don't forget to share your views and/or feedback in the comment section below.

6 comments

  1. This is the code I was talking about reading of Outlook Contacts reading:

    using System.Collections;
    using System.Runtime.InteropServices;
    using OutLook = Microsoft.Office.Interop.Outlook;
    using System.Data;

    protected ArrayList GetOutlookContactsEmails()
    {
    ArrayList OutlookContacts = new ArrayList();
    OutLook._Application objOutlook = null;
    OutLook.NameSpace objNamespace = null;
    OutLook.MAPIFolder objContactsFolder = null;
    OutLook.ContactItem item = null;
    bool QuitOutlook = true;
    try
    {
    //Is Outlook running? If so we don't want to quit when closing COM object references.
    if (System.Diagnostics.Process.GetProcessesByName("OUTLOOK").Length > 0)
    QuitOutlook = false;
    else
    QuitOutlook = true;


    objOutlook = new OutLook.ApplicationClass();

    //Logging into Outlook namespace.
    objNamespace = objOutlook.GetNamespace("MAPI");

    //Loading Contacts MAPI folder.
    objContactsFolder = objNamespace.GetDefaultFolder(OutLook.OlDefaultFolders.olFolderContacts);

    if (objContactsFolder.Items.Count != 0)
    {
    for (int contacts = 1; contacts < objContactsFolder.Items.Count + 1; contacts++)
    {
    if (objContactsFolder.Items[contacts] != null)
    {
    try
    {
    //In Outlook you can put emails etc into the contact list. When we try to
    //cast these items an exception will be raised. We will only display
    //Outlook contacts in the Outlook Contact directory.
    if (objContactsFolder.Items[contacts] is OutLook.ContactItem)
    item = (OutLook.ContactItem)objContactsFolder.Items[contacts];
    }
    catch
    {
    item = null;
    }

    if (item != null)
    {
    OutlookContacts.Add(item);
    }
    }

    //There may be sub folders within this folder
    foreach (OutLook.MAPIFolder subfolder in objContactsFolder.Folders)
    {
    if (subfolder != null)
    {
    for (int subcontacts = 1; subcontacts < subfolder.Items.Count + 1; subcontacts++)
    {
    if (subfolder.Items[subcontacts] != null)
    {
    try
    {
    if (subfolder.Items[subcontacts] is Microsoft.Office.Interop.Outlook.ContactItem)
    item = (OutLook.ContactItem)subfolder.Items[subcontacts];
    }
    catch
    {
    item = null;
    }

    if (item != null)
    {
    OutlookContacts.Add(item);
    }
    }
    }
    }
    }
    }
    }
    }
    catch (Exception ex)
    {
    //throw ex;
    }
    finally
    {
    try
    {
    //Close all Outlook components.
    if (item != null)
    {
    Marshal.ReleaseComObject(item);
    item = null;
    }
    if (objContactsFolder != null)
    {
    Marshal.ReleaseComObject(objContactsFolder);
    objContactsFolder = null;
    }
    if (objNamespace != null)
    {
    //Logging out of and closing Outlook namespace.
    objNamespace.Logoff();
    Marshal.ReleaseComObject(objNamespace);
    objNamespace = null;
    }

    if (objOutlook != null)
    {
    //Closing Outlook application

    //If Outlook was started by this process then close it afterwards. If Outlook was open
    //anyway then keep it open.
    if (QuitOutlook)
    objOutlook.Quit();

    Marshal.ReleaseComObject(objOutlook);
    objOutlook = null;
    }

    //Perform garbage collection.
    GC.Collect();
    GC.WaitForPendingFinalizers();
    }
    catch (Exception ex)
    {
    throw ex;
    }
    }
    return OutlookContacts;
    }


    This is a bit of rough code. Not a polished one.

    ReplyDelete
    Replies
    1. Hi Rino,

      It's similar to what I have shared above. Only difference is, I have iterated for mail items whereas your code demonstrates it for contact items. Thanks again for sharing. It will help others who are looking for code to iterate contact items.

      Delete
  2. Hi Kunal

    I'm new to C# development and I want to use enum as you do above. May I please know where to put the below? Need to open a new class file? Or just put in the same file as with my current namespace?

    namespace Microsoft.Office.Interop.Outlook
    {
    public enum OlDefaultFolders
    {
    olFolderDeletedItems = 3,
    olFolderOutbox = 4,
    olFolderSentMail = 5,
    olFolderInbox = 6,
    olFolderCalendar = 9,
    olFolderContacts = 10,
    olFolderJournal = 11,
    olFolderNotes = 12,
    olFolderTasks = 13,
    olFolderDrafts = 16,
    olPublicFoldersAllPublicFolders = 18,
    olFolderConflicts = 19,
    olFolderSyncIssues = 20,
    olFolderLocalFailures = 21,
    olFolderServerFailures = 22,
    olFolderJunk = 23,
    olFolderRssFeeds = 25,
    olFolderToDo = 28,
    olFolderManagedEmail = 29
    }
    }

    ReplyDelete
    Replies
    1. Hi,

      You don't have to place it anywhere. It is already part of the Outlook COM library (namespace: Microsoft.Office.Interop.Outlook). This was pasted in the blog, above, just for providing clear understanding of the API.

      Delete
  3. What about providing credentials ?

    ReplyDelete
    Replies
    1. If your outlook requires a password to launch, you have to provide it in the dialog. If outlook is already opened, it will pickup the context from the open session.

      Delete

 
© 2008-2017 Kunal-Chowdhury.com - Microsoft Technology Blog for developers and consumers | Designed by Kunal Chowdhury
Back to top