【发布时间】:2017-05-03 07:24:51
【问题描述】:
我希望监视来自 Outlook 2013 的所有新电子邮件并获取电子邮件的主题。 在阅读了几篇博客之后,我了解到最好/简单的方法是使用 Microsoft.Office.Interop.Outlook 与 MAPI 和 ApplicationEvents_11_NewMailExEventHandler 事件。
我在博客上尝试了这个基础,并做了一些修改:
using System;
using System.Windows.Forms;
using Microsoft.Office.Interop.Outlook;
class EmailMonitoring
{
static void Main(string[] args)
{
// Create an Outlook application object.
Microsoft.Office.Interop.Outlook.Application app = null;
Microsoft.Office.Interop.Outlook._NameSpace ns = null;
try
{
//Email
app = new Microsoft.Office.Interop.Outlook.Application();
ns = app.GetNamespace("MAPI");
ns.Logon(null, null, false, false);
// Ring up the new message event.
app.NewMailEx += new ApplicationEvents_11_NewMailExEventHandler(outLookApp_NewMailEx);
Console.WriteLine("Please wait for new messages...");
Console.ReadLine();
}
catch (System.Exception e)
{
Console.WriteLine("Exception in Main "+e);
}
finally
{
ns = null;
app = null;
}
}
private static void outLookApp_NewMailEx(string EntryIDCollection)
{
Console.WriteLine("You've got a new mail whose EntryIDCollection is \n" + EntryIDCollection);
Microsoft.Office.Interop.Outlook.Application app = new Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.MailItem item = null;
Microsoft.Office.Interop.Outlook._NameSpace ns = app.GetNamespace("MAPI");
try
{
ns.Logon(null, null, false, false);
item = ns.GetItemFromID(EntryIDCollection);
Console.WriteLine("test" + item.Subject);
}
catch(System.Exception e)
{
Console.WriteLine("Exception in event Handler "+e);
}
finally
{
ns = null;
app = null;
}
}
}
但是,当我在 Outlook 中有一封新电子邮件时,控制台会显示 EntryID 和主题,但 Outlook 会冻结某些特定电子邮件并抛出此错误消息: “电子邮件已停止工作。”
- 我忘记删除一些对象了吗?
- 有没有更优雅的方法来做到这一点?我不喜欢需要定义 2 个 Outlook.Applications 的事实。
- 您是否推荐任何描述如何做到这一点的博客/书籍?
【问题讨论】:
-
您的代码没有清理显式的非托管 Outlook COM 资源。毫无疑问,这就是导致挂起的原因。这可能是全部原因,但可以肯定的是,这至少是问题的一部分。