2017-04-20 81 views
0

我已經嘗試了許多在本網站上提供的解決方案以將文件附加到電子郵件,但無論我嘗試什麼,我總是會收到「對不起,出錯了,您可能想要嘗試再次嘗試「的消息,我嘗試將該文件附加到我的outlook mailitem。將文件附加到電子郵件中C#

try 
     { 
      App = new Microsoft.Office.Interop.Outlook.Application(); 

      MailItem mailItem = App.CreateItem(OlItemType.olMailItem); 

      mailItem.Subject = Subject; 
      mailItem.To = To; 
      mailItem.CC = CC; 
      mailItem.BCC = BCC; 
      mailItem.Body = Body; 

      // make sure a filename was passed 
      if (string.IsNullOrEmpty(FileAtachment) == false) 
      { 
       // need to check to see if file exists before we attach ! 
       if (!File.Exists(FileAtachment)) 
        MessageBox.Show("Attached document " + FileAtachment + " does not exist", "File Error", MessageBoxButtons.OK, MessageBoxIcon.Error); 
       else 
       { 
        System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(FileAtachment); 
        mailItem.Attachments.Add(attachment, Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue, Type.Missing, Type.Missing); 
       } 
      } 
      mailItem.Display();  // display the email 
     } 
     catch (System.Exception ex) 
     { 
      MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); 
     } 

任何人都可以提供任何想法如何讓這個工作?我可以發送電子郵件沒有任何問題,但是當我嘗試添加附件它不工作:(

+0

你加入'System.Net.Mail.Attachment'到Outlook郵件項目,但它預計Outlook附件 –

回答

1

Attachments.Add方法接受一個文件(通過文件名的完整文件系統路徑來表示)或Outlook項目構成附件,而不是附件對象:

 App = new Microsoft.Office.Interop.Outlook.Application(); 

     MailItem mailItem = App.CreateItem(OlItemType.olMailItem); 

     mailItem.Subject = Subject; 
     mailItem.To = To; 
     mailItem.CC = CC; 
     mailItem.BCC = BCC; 
     mailItem.Body = Body; 

     // make sure a filename was passed 
     if (string.IsNullOrEmpty(FileAtachment) == false) 
     { 
      // need to check to see if file exists before we attach ! 
      if (!File.Exists(FileAtachment)) 
       MessageBox.Show("Attached document " + FileAtachment + " does not exist", "File Error", MessageBoxButtons.OK, MessageBoxIcon.Error); 
      else 
      { 
       Attachment attachment = mailItem.Attachments.Add("D:\\text.txt", Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue, Type.Missing, Type.Missing); 
      } 
     } 
     mailItem.Display();  // display the email