I personally find programming against Outlook from .Net (C# in my case) a bit of trial and error. I recently found out that it is not good to assume that any type of folder only has a particular kind of items in it. In particular, I found out that Undeliverable messages are not of type MailItem, they are of type ReportItem. Go figure! The clue for me was that the icon for these messages in Outlook are different than a normal email message.
Below is a snippet of code that will loop through all the items in your inbox and try to cast it to all the types I could find, and prints out some interesting information about the item. If someone knows of other types, please let me know. If an item is of an unknown type it will write that line with “ERROR: Unknown Item at Index:” message.
There are obviously lots of ways you could write this, but this code was my first thought, and it allows me to actually see the exception if one occurs.
// Create an Outlook Application object.
Microsoft.Office.Interop.Outlook.Application outLookApp = new Microsoft.Office.Interop.Outlook.Application();
// Print all emails.
NameSpace outlookNS = outLookApp.GetNamespace("MAPI");
MAPIFolder theEmails = outlookNS.GetDefaultFolder(OlDefaultFolders.olFolderInbox);
for (int i = 1; i <= theEmails.Items.Count; i++)
{
object obj = theEmails.Items[i];
// **********************
try
{
AppointmentItem item = (AppointmentItem)obj;
WriteLine(item.Subject);
}
catch (System.Exception ex1)
{
// **********************
try
{
ContactItem item = (ContactItem)obj;
WriteLine(item.FirstName);
}
catch (System.Exception ex2)
{
// **********************
try
{
DistListItem item = (DistListItem)obj;
WriteLine(item.Subject);
}
catch (System.Exception ex3)
{
// **********************
try
{
JournalItem item = (JournalItem)obj;
WriteLine(item.Subject);
}
catch (System.Exception ex4)
{
// **********************
try
{
MailItem item = (MailItem)obj;
WriteLine(item.Subject);
}
catch (System.Exception ex5)
{
// **********************
try
{
NoteItem item = (NoteItem)obj;
WriteLine(item.Subject);
}
catch (System.Exception ex6)
{
// **********************
try
{
PostItem item = (PostItem)obj;
WriteLine(item.Subject);
}
catch (System.Exception ex7)
{
// **********************
try
{
TaskItem item = (TaskItem)obj;
WriteLine(item.Subject);
}
catch (System.Exception ex8)
{
// **********************
try
{
ReportItem item = (ReportItem)obj;
WriteLine(item.Subject);
}
catch (System.Exception ex9)
{
WriteLine(string.Format("ERROR: Unknown Item at Index: {0}", i));
}
}
}
}
}
}
}
}
}
}
A good starting point is: http://msdn.microsoft.com/en-us/library/aa289167(VS.71).aspx#ol03cs_topic11
Also see: http://www.outlook-code.com
No comments:
Post a Comment