I am looking to monitor all new emails from Outlook 2013 and get the email's subject. After reading several blogs, I understood that the best/easy way is to use Microsoft.Office.Interop.Outlook with MAPI and ApplicationEvents_11_NewMailExEventHandler event.
I try this base on a blog and I did a bit of modification:
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;
}
}
}
However, when I have a new email in outlook, the console display the EntryID and the subject, but Outlook become frozen for some specific emails and throw this error message: "Email has stoppped working."
- Did I forgot to delete some objects?
- Is there a more elegant way to do that? I do not like the fact that I need to define 2 Outlook.Applications.
- Do you recommend any blogs/books which describe how to do that?