2011-01-11 72 views
12

我写了这个代码来查看我的Outlook邮箱中的未读项目,这里是代码:无法投COM对象 - 微软Outlook和C#

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()); 
      } 
     } 

但foreach循环我得到这个错误:

"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))."

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

+0

这是一个加载项? – Bolu 2011-01-11 10:10:23

+0

@Bolu不,这是我写在我的C#Windows应用程序 – Zerotoinfinity 2011-01-11 10:23:01

+1

MAPIFolder已弃用,请使用文件夹。 – 2011-01-11 10:29:38

回答

19

我不得不解决一些问题。

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

希望有所帮助。

这里的问题是_explorer.CurrentFolder.Items可以包含更多的对象,而不仅仅是MailItemPostItem是其中之一)。

3

当我测试它时,下面的代码工作正常。但我必须提到,我的参考是“Microsoft Outlook 14.0 Object Library”。你碰巧使用另一个版本?

 
    public class Outlook 
    { 
    readonly Microsoft.Office.Interop.Outlook.Items  _items; 
    readonly Microsoft.Office.Interop.Outlook.NameSpace _ns; 
    readonly Microsoft.Office.Interop.Outlook.MAPIFolder _inbox; 
    readonly Microsoft.Office.Interop.Outlook.Application _application = new Microsoft.Office.Interop.Outlook.Application(); 

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

     foreach (var item in _items) 
     { 
      string subject= string.Empty; 
      var mail = item as Microsoft.Office.Interop.Outlook.MailItem; 
      if (mail != null) 
       var subject = mail.Subject; 
      else 
       Debug.WriteLine("Item is not a MailItem"); 
     } 
    } 
    } 

请注意,在Outlook中,许多项目具有一些共同的特性(如过期时间),所以你可以像一个绝望的解决方案是使用“动态”数据类型 - 无论是作为未知项目类型后备方案或者作为你的默认值(只要你对性能的要求不错)。

6

尝试检查的项目是一个有效的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()); 
    } 
}