2015-01-08 71 views
1

我寫了這個代碼的COM對象使用Outlook從我的.NET應用程序發送的附加檔案,這裏是代碼:InvalidCastException的 - 無法投型「Microsoft.Office.Interop.Outlook.ApplicationClass」

Microsoft.Office.Interop.Outlook.Application outlook = new Microsoft.Office.Interop.Outlook.Application(); 
      Microsoft.Office.Interop.Outlook.Application session = new Microsoft.Office.Interop.Outlook.Application(); 
      Microsoft.Office.Interop.Outlook.NameSpace ns = outlook.Session; 
      Outlook.MailItem mail = outlook.Application.CreateItem(Outlook.OlItemType.olMailItem) as Outlook.MailItem; 
      mail.Subject = txtSubject.Text; 
      mail.To = txtTo.Text; 
      mail.Subject = txtSubject.Text; 
      mail.Body = txtBody.Text; 
      mail.Attachments.Add(@"c:\Users\admin\Desktop\Excel.txt", 
        Outlook.OlAttachmentType.olByValue, Type.Missing, 
        Type.Missing); 
      Outlook.Accounts accounts = outlook.Session.Accounts; 

      foreach (Outlook.Account account in accounts) 
      { 
       // When the e-mail address matches, send the mail. 
       if (string.Equals(account.SmtpAddress, txtFrom.Text, StringComparison.OrdinalIgnoreCase)) 
       { 
        mail.SendUsingAccount = account; 
        mail.Save(); 
        ((Outlook._MailItem)outlook).Send(); 
        lblStatus.Text = "Report Sent"; 
        break; 
       } 
      } 

但是,當它達到了send()方法調用,我得到這個錯誤:

Unable to cast COM object of type 'Microsoft.Office.Interop.Outlook.ApplicationClass' 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)). 

回答

2

您是鑄造錯了對象

outlook被定義爲Microsoft.Office.Interop.Outlook.Application

您需要更改

((Outlook._MailItem)outlook).Send(); 

到:

((Outlook._MailItem)mail).Send(); 

Reference

+1

感謝的人!它解決了這個問題! – Quoros

相關問題