Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to cast COM object - Microsoft outlook & C#

Tags:

I have written this code to view the unread items in my outlook mail box and here is the code:

 Microsoft.Office.Interop.Outlook.Application app;  Microsoft.Office.Interop.Outlook.Items items;   Microsoft.Office.Interop.Outlook.NameSpace ns;   Microsoft.Office.Interop.Outlook.MAPIFolder inbox;   Microsoft.Office.Interop.Outlook.Application application = new Microsoft.Office.Interop.Outlook.Application();         app = application;         ns =  application.Session;         inbox = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);         items = inbox.Items;         foreach (Microsoft.Office.Interop.Outlook.MailItem mail in items)         {             if (mail.UnRead == true)             {                 MessageBox.Show(mail.Subject.ToString());             }         } 

but on the foreach loop I am getting this error:

"Unable to cast COM object of type 'System.__ComObject' to interface type 'Microsoft.Office.Interop.Outlook.MailItem'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{00063034-0000-0000-C000-000000000046}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE))."

Can you please assist me how to resolve this error?

like image 906
Zerotoinfinity Avatar asked Jan 11 '11 10:01

Zerotoinfinity


2 Answers

I had to get around something like your problem a while back.

        foreach (Object _obj in _explorer.CurrentFolder.Items)         {             if (_obj is MailItem)             {                  MyMailHandler((MailItem)_obj);             }         } 

Hope that helps.

The issue here is that _explorer.CurrentFolder.Items can contain more objects than just MailItem (PostItem being one of them).

like image 195
Anders Arpi Avatar answered Sep 28 '22 12:09

Anders Arpi


try to check the item is a valid mailitem before checking its properties :

foreach (Object mail in items) {     if ((mail as Outlook.MailItem)!=null && (mail as Outlook.MailItem).UnRead == true)     {         MessageBox.Show((mail as Outlook.MailItem).Subject.ToString());     } } 
like image 33
Bolu Avatar answered Sep 28 '22 12:09

Bolu