首页 > 解决方案 > C# Outlook 阅读主题

问题描述

我的收件箱中的循环功能有问题,它向我显示了电子邮件的主题。

private void button3_Click(object sender, EventArgs e)
        {

            Outlook.Application OutlookApp = new Outlook.Application();
            Outlook.NameSpace nameSpace = OutlookApp.GetNamespace("MAPI");
            Outlook.MAPIFolder folderInbox = nameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
            Outlook.Folders inboxFolders = folderInbox.Folders;
            Outlook.Items mails = folderInbox.Items;
            Outlook.MAPIFolder subFolderInbox = null;
            try
            {
                
                Console.WriteLine(" numarul de emailuri" + mails.Count);

                foreach (Outlook.MailItem item in mails)
                {

                    string subj = item.Subject;
                    MessageBox.Show(subj);
                    Console.WriteLine(subj);
                    Marshal.ReleaseComObject(item);


                }

                //subFolderInbox = inboxFolders.Add("LP History", Outlook.OlDefaultFolders.olFolderInbox);
            }
            catch (Exception exception)
            {
                if (exception.ErrorCode == -2147352567)
                //cannot creat folder error
                MessageBox.Show("Cannot creater folder error");
            }
            if (subFolderInbox != null) Marshal.ReleaseComObject(subFolderInbox);
            if (inboxFolders != null) Marshal.ReleaseComObject(inboxFolders);
            if (folderInbox != null) Marshal.ReleaseComObject(folderInbox);
            if (nameSpace != null) Marshal.ReleaseComObject(nameSpace);
                                 
        }

甚至没有进入 foreach 循环:我在控制台中生成的内容:“ numarul de emailuri340 'OLP.exe' (CLR v4.0.30319: OLP.exe): Loaded 'C:\windows\Microsoft.Net\assembly\GAC_32 \CustomMarshalers\v4.0_4.0.0.0__b03f5f7f11d50a3a\CustomMarshalers.dll'。跳过加载符号。模块已优化并启用调试器选项“仅我的代码”。抛出异常:OLP.exe 中的“System.InvalidCastException”

标签: c#visual-studio

解决方案


根据我的测试,我可以使用您的代码成功获取电子邮件的主题。

因此,我建议您可以检查以下步骤。

首先,请检查您当前的 Outlook 应用程序是否正在运行。

二、请将outlook的引用删除,重新安装在nuget包中。

在此处输入图像描述


推荐阅读