C# – : ‘Unable to cast COM object of type ‘System.__ComObject’ to interface type

asp.netcinteropoutlook

I am getting the following error:

System.InvalidCastException: '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)).'

The code from which the error arises:

foreach (MailItem item in mailItems)
{
}

Best Answer

It is possible that mailItems contains more objects other than Microsoft.Office.Interop.Outlook.MailItem as defined in the loop. The safest way is using object type to iterate mailItems, then check its type with as operator before running Outlook handler:

foreach (object item in mailItems)
{
    // try casting to Outlook.MailItem first
    var obj = item as Outlook.MailItem;

    // check if the conversion works and UnRead property can be accessed as well
    if (obj != null && obj.UnRead == true)
    {
        // do something
    }
    else
    {
        // do something else
    }
}
Related Topic