C# outlook : Unable to cast COM object of type 'System._ComObject' to Interface type 'Microsoft.Office.Interop.Outlook.MailItem.'

0

I'm new to c#.

I have been trying on my own to fix this issue since 1 week until i've got no other alternative than to ask for help here.

My goal is to create a console app which would look for Unread Mails on the secondary mailbox[mailboxB@gmail.com]/second outlook account and reply those mails based on the Subject.

The code works fine on my Machine.

Unfortunately when the same exe is deployed on other machine, the following error gets generated:

unable to cast com object of 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))

Please note i've tried the following to resolve the issue but the issue still prevails:

  1. Restarted Outlook as administrator.

    Change the compatibility of the app under properties-> compatibility to run as administrator

  2. Checked the outlook version which is 16.0 and the same ref is being used for in the code.

Please find my code below:

            Outlook.Application oApp = new Outlook.Application();
            Outlook.NameSpace oNS = (Outlook.NameSpace)oApp.GetNamespace("MAPI");
            
            MAPIFolder theInbox = oNS.Folders["mailboxB@gmail.com"].Folders["Inbox"];
            
            Outlook.Items unreadItems = theInbox.Items.Restrict("[Unread]=true");
            string t = "Test Mail";
            try
            {
                foreach (Outlook.MailItem it in unreadItems)
                {
                    if (it.Subject == t)
                    {
                        Outlook.MailItem replyMail = it.Reply();
                        it.HTMLBody = DateTime.Now.ToString("HH:mm:ss");
                        
                        
                        replyMail.Send();
                        it.Unread=false;
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }

Any sort of help would be highly appreciated.

c#
outlook
asked on Stack Overflow May 22, 2021 by Juv

1 Answer

1

You can have items other than MailItem in your Inbox folder, e.g. ReportItem or MeetingItem.

Change your code to

foreach (object obj in unreadItems)
{
   if (obj is Outlook.MailItem it)
   {
      ...

User contributions licensed under CC BY-SA 3.0