0

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)
{
}
user2281858
  • 1,957
  • 10
  • 41
  • 82

1 Answers1

2

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
    }
}
Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61
  • did that, but i get the following error - `'object' does not contain a definition for 'UnRead' and no extension method 'UnRead' accepting a first argument of type 'object' could be found` – user2281858 Jan 11 '18 at 10:20
  • `UnRead` property exists in `Outlook.MailItem`, I changed to use `as` operator for type conversion attempt. – Tetsuya Yamamoto Jan 11 '18 at 11:32