Create MAPIFolder object in C# on non default Outlook 2007 account

1.3k views Asked by At

I am creating a C# console application in Visual Studio 2015 that prints to the console all emails. I am having problems when I try to create the MAPIFolder object. I used the code from this post: Read emails from non default accounts in Outlook. I can create a MAPIFolder object from the default account using the namespace, but I can’t create any folder object using the Stores.

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

namespace MoveEmailsDriver

{
    class ProcessEmails
    {
        static void Main(string[] args)
        {
                PrintEmailBody();
        }
        public static void PrintEmailBody()
        {
            Application app = new Application();
            _NameSpace ns = app.GetNamespace("MAPI");
            Stores stores = ns.Stores;

            foreach(Store store in stores)
            {
                MAPIFolder inboxFolder = store.GetDefaultFolder(OlDefaultFolders.olFolderInbox);

                foreach(MailItem item in inboxFolder.Items)
                {
                    WriteLine(item.Body);
                }
            }
        }

    }
}

This is the exception error I am getting.

1

There are 1 answers

0
Al G On

I figured it out. I had to create a MAPIFolder object with the GetRootFolder() method. This is the updated code:

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

namespace OutlookDriverProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            Application app = new Application();
            NameSpace ns = app.GetNamespace("MAPI");
            Stores stores = ns.Stores;

            foreach (Store store in stores)
            {
                //Uncomment next line to see the folder names
                //WriteLine("Folder name = {0}", store.DisplayName);
                if (store.DisplayName.Equals("YOURFOLDERNAME"))
                {

                    MAPIFolder YOURFOLDERNAME = store.GetRootFolder();

                    foreach (Folder subF in YOURFOLDERNAME.Folders)
                    {

                        if (subF.Name.Equals("Inbox"))
                        {
                            foreach (MailItem email in subF.Items)
                            {
                                WriteLine("Email subject = {0}", email.Subject);
                            }

                        }

                    }
                }

            }
        }

    }
}