【问题标题】:Create MAPIFolder object in C# on non default Outlook 2007 account在 C# 中在非默认 Outlook 2007 帐户上创建 MAPIFolder 对象
【发布时间】:2026-02-14 18:25:01
【问题描述】:

我正在 Visual Studio 2015 中创建一个 C# 控制台应用程序,它将所有电子邮件打印到控制台。我在尝试创建 MAPIFolder 对象时遇到问题。我使用了这篇文章中的代码:Read emails from non default accounts in Outlook。我可以使用命名空间从默认帐户创建一个 MAPIFolder 对象,但我无法使用 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.

【问题讨论】:

    标签: c# email outlook-2007


    【解决方案1】:

    我想通了。我必须使用 GetRootFolder() 方法创建一个 MAPIFolder 对象。这是更新后的代码:

    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);
                                }
    
                            }
    
                        }
                    }
    
                }
            }
    
        }
    }
    

    【讨论】: