【发布时间】:2023-03-09 16:15:01
【问题描述】:
我正在尝试使用 Outlook 对象模型从 .NET 应用程序发送电子邮件。
我的应用程序显示 Outlook 消息窗口,因此用户可以看到我们发送的内容并首先对其进行编辑。当用户点击“发送”按钮时,Outlook 窗口将关闭,并发送消息。只要 Outlook 应用程序已经在运行,它就可以完美运行。
如果 Outlook 应用程序尚未运行,则邮件会卡在发件箱中,并且在我启动 Outlook 之前不会发送。当我启动 Outlook 时,我可以看到邮件在发件箱文件夹中停留了几秒钟,然后它就会被发送出去。
这是我用来发送电子邮件的代码的简化版本:
Outlook.Application app = new Outlook.Application();
var ns = app.GetNamespace("MAPI");
// (ref: https://msdn.microsoft.com/en-us/library/office/ff861594.aspx)
// If outlook is already running, this does nothing. If it isn't, this has the
// side-effect of initializing MAPI to use the default profile and make the object
// model fully functional
var mailFolder = ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
var mailItem = (Outlook.MailItem)ns.Application.CreateItem(Outlook.OlItemType.olMailItem);
mailItem.To = "me@nowhere.com";
mailItem.Subject = "This is a test";
mailItem.HTMLBody = "<html>A bunch of HTML</html>";
mailItem.Display(true);
注意:如果我用 mailItem.Send() 替换对 mailItem.Display() 的调用,无论 Outlook 是否正在运行,它都有效。 不幸的是,这不是一个选项,因为我需要用户能够在发送之前编辑消息。
我在想我需要一种方法来检测消息何时完成发送,并在此之前保持 Outlook.Application 对象处于活动状态......但我不知道该怎么做。我的应用程序是一个控制台应用程序,发送电子邮件后需要退出。让线程休眠一段时间不会这样做(可能是因为我正在等待的任何事情都发生在同一个线程上)。
【问题讨论】: