Search code examples
c#winformsxtrareport

Add XtraReport as attachment in outlook


This Is my code :

   using (RepMissingStatusProject report = new RepMissingStatusProject())
        {
            report.DataSource = await inventory.RepMissingStatusProject(Convert.ToInt32(oListProject.cmbProject.EditValue)).ConfigureAwait(true);
            report.CreateDocument();

            Microsoft.Office.Interop.Outlook.Application oApp = new Microsoft.Office.Interop.Outlook.Application();
            Microsoft.Office.Interop.Outlook.MailItem oMsg = (Microsoft.Office.Interop.Outlook.MailItem)oApp.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);

            MemoryStream mem = new MemoryStream();
            report.ExportToPdf(mem);
            mem.Seek(0, System.IO.SeekOrigin.Begin);

            oMsg.To = "[email protected]";
            oMsg.Subject = "Test";
            oMsg.BodyFormat = Microsoft.Office.Interop.Outlook.OlBodyFormat.olFormatHTML;
            oMsg.Display(false); 
            oMsg.HTMLBody = "Veuillez trouver ci-joint:" + "<br />" + oMsg.HTMLBody;
            oMsg.Attachments.Add(mem, Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue, Type.Missing, Type.Missing);
        }

the outlook open fine and all data are correct except for the attachment file I get this error :

System.Runtime.InteropServices.COMException: 'Member not found. (Exception de HRESULT : 0x80020003 (DISP_E_MEMBERNOTFOUND))'

How can I solve this problem?.
Thanks in advance for your help

Update:
I try to use this code

System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Application.Pdf);
System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(mem,ct);
attach.ContentDisposition.FileName = "État De Manque.pdf";

but i get another error

System.ArgumentException HResult=0x80070057 Message=Sorry, something went wrong. You may want to try again. StackTrace "at Microsoft.Office.Interop.Outlook.Attachments.Add(Object Source, Object Type, Object Position, Object DisplayName)\r\n at Smart_Industrial_Management.PL.FrmInventory.d__44.MoveNext() in D:\SIM Windows7\Smart Industrial Management\PL\FrmInventory.cs:line 859" string


Solution

  • oMsg.Attachments.Add(mem

    the first argument should be the path to file on your file system. so you need to export pdf to file (with randomly generated name) and put the path into the oMsg.Attachments.Add() method call as first argument.

    so your code should be lilke

    report.ExportToPdf(randomName);
    ...
    oMsg.Attachments.Add(randomName,...);
    File.Delete(randomName);