Outlook 互操作发送的邮件事件未在 WPF 中触发,但在控制台应用程序中有效

Outlook interop sent mail event not triggered in WPF but works in Console Application

在我的 C# WPF 应用程序中,我使用 Outlook Interop 发送邮件。邮件发送后,我想从“已发送”文件夹中检索它以进行一些后期处理。

我创建了以下 class 来封装 Outlook 交互:

public class OutlookManager {
    public MAPIFolder SentMailFolder { get; set; }

    public Application MailApplication { get; set; }

    public OutlookManager() {
      MailApplication = new Application();
      SentMailFolder = MailApplication.Session.GetDefaultFolder(OlDefaultFolders.olFolderSentMail);
    }
}

如果我在控制台应用程序项目中使用这个 class,它工作正常。 outlook发邮件时方法SentMailHandler是运行,终端写主题window:

private static void SentMailHandler(object item) {
  var mail = (MailItem)item;
  Console.WriteLine(mail.Subject);
}

private static void Main() {
  OutlookManager Outlook = new OutlookManager();
  Outlook.SentMailFolder.Items.ItemAdd += SentMailHandler;
  MailItem mail = Outlook.MailApplication.CreateItem(OlItemType.olMailItem);
  mail.To = "my-address";
  mail.Subject = "Testing";
  mail.Body = "This is a test";
  mail.Send();

  Console.Read();
}

但是,当我尝试在我的 WPF 应用程序中合并相同的代码时,发送邮件时没有任何反应,即 SentMailHandler 方法永远不会 运行,并且在调试 window。我有一个上下文 class MassMailContext。这个 class 的实例被创建并设置为 UI 元素的 DataContext (我确定构造函数代码是 运行):

internal class MassMailContext : Context {
   public OutlookManager Outlook { get; set; }

   public MassMailContext(MainWindow view) : base(view) {
      Outlook = new OutlookManager();
      Outlook.SentMailFolder.Items.ItemAdd += SentMailHandler;
      MailItem mail = Outlook.MailApplication.CreateItem(OlItemType.olMailItem);
      mail.To = "my-address";
      mail.Subject = "Testing";
      mail.Body = "This is a test";
      mail.Send();
   }

   private void SentMailHandler(object item) {
      var mail = (MailItem)item;
      Console.WriteLine($"{mail.Subject}");
   }
}

请注意,邮件不是要从构造函数发送的,而只是为了调试目的而发送的。

为什么它在控制台应用程序项目中有效,但在 WPF 应用程序项目中无效?我能看到的唯一区别是,发送电子邮件时控制台应用程序项目的 Main() 方法仍在范围内,而 MassMailContext 构造函数并非如此。

引发事件的对象 (Items) 必须处于活动状态才能引发事件。您正在将事件处理程序设置在编译器创建的临时变量上。一旦超出范围,它将受到垃圾收集。

引入一个 class 成员来保存 Items 对象并在该变量上设置事件处理程序。