C# 在收件箱中搜索特定主题的电子邮件

C# searching the Inbox for specific subjects emails

我正在尝试搜索具有特定主题的特定电子邮件。

Outlook.Folder inbox = new Outlook.Application.ActiveExplorer().Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
            Outlook.Items items = inbox.Items;
            Outlook.MailItem mailItem = null;
            object folderItem;
            string subjectName = string.Empty;
            string filter = "[Subject] > 's' And [Subject] <'u'";
            folderItem = items.Find(filter);
            while (folderItem != null)
            {
                mailItem = folderItem as Outlook.MailItem;
                if (mailItem != null)
                {
                    subjectName += "\n" + mailItem.Subject;
                }
                folderItem = items.FindNext();

            }
            subjectName = "The follow e-mail messages were found: " + subjectName;
            MessageBox.Show(subjectName);

我遇到一个错误: "严重性代码说明项目文件行抑制状态 错误 CS0426 类型名称 'ActiveExplorer' 在类型 'Application'" 中不存在"=11=]

如果您开发的 Outlook 是自动化的独立应用程序,您需要先创建一个新的 Application 实例,或者如果您开发基于 VSTO 的加载项而不是使用内置的 属性以下代码:

Outlook.Folder inbox = new Outlook.Application.ActiveExplorer().Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);

独立应用程序应创建一个新的 Outlook 实例:

Outlook.Application app = new Outlook.Application();
Outlook.Explorer explorer = app.ActiveExplorer();
Outlook.Namespace ns = app.GetNamespace("MAPI");
Outlook.Folder inbox = ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);

对于 VSTO 加载项,您可以使用 ThisAddin class:

Application 属性
Outlook.Explorer explorer = Application.ActiveExplorer();
Outlook.Namespace ns = app.GetNamespace("MAPI");
Outlook.Folder inbox = ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);

您可以在以下文章中阅读有关 Items class 的 Find/FindNext or Restrict 方法的更多信息:

您可能还会发现 AdvancedSearch 方法很有帮助。在 Outlook 中使用 AdvancedSearch 方法的主要好处是:

  • 搜索在另一个线程中执行。您不需要手动 运行 另一个线程,因为 AdvancedSearch 方法 运行 它会自动在后台运行。
  • 可以在任何位置(即超出某个文件夹的范围)搜索任何项目类型:邮件、约会、日历、便笺等。 RestrictFind/FindNext 方法可以应用于特定的 Items 集合(请参阅 Outlook 中文件夹 class 的项目 属性 ).
  • 完全支持 DASL 查询(自定义属性也可用于搜索)。您可以在 MSDN 的过滤文章中阅读更多相关信息。要提高搜索性能,如果为商店启用了即时搜索,则可以使用即时搜索关键字(请参阅商店 class 的 IsInstantSearchEnabled 属性)。
  • 您可以随时使用搜索 class 的 Stop 方法停止搜索过程。

我不确定你为什么要访问 ActiveExplorer - 你没有使用它,如果 Outlook 之前没有 运行,就不会有任何打开的浏览器(和检查器) , 所以 ActiveExplorer 无论如何都会 return 为空。

另请记住,除非 Outlook 已经 运行,否则 Application.Session 将为空 - 您需要先登录。

第三,您没有调用构造函数 - 那将是 new Outlook.Application().Blah(注意 ())。

将您的代码更改为

Outlook.Application app = new Outlook.Application();
Outlook.Namespace session = app.GetNamespace("MAPI");
session.Logon();
Outlook.Folder inbox = session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);