无法转换COM对象 - Microsoft Outlook和C#

Zer*_*ity 16 c# outlook office-interop outlook-2003 c#-2.0

我已编写此代码以查看Outlook邮箱中的未读项目,以下是代码:

 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());
            }
        }
Run Code Online (Sandbox Code Playgroud)

但在foreach循环中我收到此错误:

"无法将类型为'System .__ ComObject'的COM对象转换为接口类型'Microsoft.Office.Interop.Outlook.MailItem'.此操作失败,因为QueryInterface调用COM组件上的接口与IID'{00063034-0000- 0000-C000-000000000046}由于以下错误而失败:不支持此类接口(HRESULT异常:0x80004002(E_NOINTERFACE)).

你能帮我解决一下这个错误吗?

And*_*rpi 25

我不得不在一段时间内解决你的问题.

        foreach (Object _obj in _explorer.CurrentFolder.Items)
        {
            if (_obj is MailItem)
            {
                 MyMailHandler((MailItem)_obj);
            }
        }
Run Code Online (Sandbox Code Playgroud)

希望有所帮助.

这里的问题是_explorer.CurrentFolder.Items可以包含更多的对象而不仅仅是MailItem(PostItem作为其中之一).


Bol*_*olu 8

mailitem在检查其属性之前,尝试检查该项是否有效:

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());
    }
}
Run Code Online (Sandbox Code Playgroud)


KBo*_*oek 5

当我测试以下代码时,它工作正常。但是我必须提到,我的参考是“ Microsoft Outlook 14.0对象库”。您是否碰巧使用其他版本?

    公共类展望
    {
    只读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(); 

    公开Outlook()
    {
        _ns = _application.Session;
        _inbox = _ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
        _items = _inbox.Items;

        foreach(_items中的var项目)
        {
            字符串subject = string.Empty;
            var mail = item as Microsoft.Office.Interop.Outlook.MailItem;
            如果(邮件!= null)
                var subject = mail.Subject;
            其他
                Debug.WriteLine(“项目不是邮件项目”);
        }
    }
    }

请注意,在Outlook中,许多项目具有一些共同的属性(例如,到期时间),因此,您可以作为一种绝望的解决方法,使用“动态”数据类型-作为未知项目类型的后备方案或作为默认方案(因为您对性能方面的影响还不错)。