Reading Outlook Mail with C#

Soph picture Soph · Dec 3, 2011 · Viewed 38.7k times · Source

I am using the following code as I attempt to connect to my Outlook mail. Now, I must be doing something wrong because I try to get the inbox mails and I always get 0 mails (when this is not the case). This is my code

 Microsoft.Office.Interop.Outlook.NameSpace nameSpace = application.GetNamespace("MAPI");
 nameSpace.Logon("", "", Missing.Value, Missing.Value);

 inboxFolder = nameSpace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
 Console.WriteLine("Folders: {0}", inboxFolder.Folders.Count);

I have several email accounts in my Outlook profile. When I write the following

Console.WriteLine("Accounts: {0}",nameSpace.Accounts.Count);
Console.WriteLine("Name: {0}", nameSpace.Accounts[1].DisplayName);

The total number of accounts is displayed correctly, and so is the name of the account i really want to access (index 1). Now, the problem is that I need to access a specific folder within that account. How do I do this?

Answer

Soph picture Soph · Dec 3, 2011

I could solve this! It was quite easy actually. Here is how I could access the desired folder:

// [email protected] is the name of my account
// Unsent mails is the name of the folder I wanted to access
inboxFolder = nameSpace.Folders["[email protected]"].Folders["Unsent mails"];

foreach (Microsoft.Office.Interop.Outlook.MailItem mailItem in inboxFolder.Items)
{
    if (mailItem.UnRead) // I only process the mail if unread
    {
        Console.WriteLine("Accounts: {0}", mailItem.Body);
    }    
}