2

The above said task seems so simple as per this stack overflow question or this MSDN How To.

But I am just struck at the line foreach (Outlook.MailItem mail in items), where I get an exception saying "Unable to cast COM object of type 'System.__ComObject' to interface type 'Microsoft.Office.Interop.Outlook.MailItem' ...".

Though there are quite a few posts about this exception, none could help me in getting over it.

Can someone please help me to solve this and to be able to read the emails from C#.

Thanks

Community
  • 1
  • 1
ViV
  • 1,998
  • 8
  • 27
  • 54

1 Answers1

3

Not every item in an Outlook Explorer is necessarily a MailItem. For example, public folders contain PostItems. If I remember correctly, conflict messages and meetings request also have their own item type.

Thus, I would design the loop as follows:

foreach (object item in items) {
    var mail = item as MailItem;
    if (mail != null) {
        // do something useful
        ...
    } else {
        // log or show some message box, so that you can debug this case
        ...
    }
}
Heinzi
  • 167,459
  • 57
  • 363
  • 519
  • Agree. In debugger I am able to see the contents of the 'Item' and it happens to be the Welcome email from Gmail (first mail). Just a simple plain email. Wouldn't that be a MailItem? By your design, 'mail' is still null for this email. This is my first Outlook program hence I'm not sure of its types. – ViV Feb 02 '12 at 12:24
  • 1
    @Vishruth: Does this happen for *all* mails or are there some which are of type MailItem? – Heinzi Feb 02 '12 at 12:40
  • You are right. I doesn't happen for all mails. It happens only for some. Thanks for your help. – ViV Feb 02 '12 at 12:55