2011-01-11 70 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()); 
    } 
}