2017-04-20 3 views
0

J'ai essayé de nombreuses solutions fournies sur ce site pour joindre un fichier à un e-mail, mais peu importe ce que j'essaie, je reçois toujours le message «Désolé, quelque chose s'est mal passé. pour réessayer "message à la ligne où j'essaye d'attacher le dossier à mon mailitem de perspectives.Joindre un fichier à un e-mail 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); 
     } 

Quelqu'un peut-il offrir une idée de comment cela fonctionnera? Je peux envoyer des e-mails sans problème, mais lorsque j'essaie d'ajouter une pièce jointe cela ne fonctionne pas :(

+0

Vous ajoutez un 'System.Net.Mail.Attachment' à l'élément de courrier Outlook, mais il attend une pièce jointe Outlook –

Répondre

1

La méthode Attachments.Add accepte un fichier (représenté par le chemin complet du système de fichiers avec un nom de fichier) ou un élément Outlook cela constitue la pièce jointe, mais pas l'objet de pièce jointe:

 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