Send Email with attachment in WPF

Pratham Jain 301 Reputation points
2025-08-23T02:18:19.6566667+00:00

Hi All,

I have a WPF application in which I have to send email with attachment. I have designed a new window to send email in application which will be displayed when user click on "send email" button on any screen. This window will be displayed to user with default values and it should have an excel file as attachment which will be generated in application and will not be saved on any drive in the system. I have written code to generate the excel file with required data but not able to send this file as attachment in email. I have been trying like below:

public byte[] GenerateReportInBytes()

{

 try

 {

             MemoryStream ms = new MemoryStream();

             workBook.SaveAs(ms);

                 ms.Seek(0, SeekOrigin.Begin);

                 return ms.ToArray();

         }

         return null;

     }

     return null;

 }

 catch (Exception e)

 {

     MessageBox.Show("Error while generating Excel report");

     return null;

 }   
```}

Please advise how can I achieve the same.

Regards,

Pratham

Developer technologies | Windows Presentation Foundation
{count} votes

Accepted answer
  1. Castorix31 91,066 Reputation points
    2025-08-24T08:32:43.7033333+00:00

    I did some tests and it worked with ClosedXML NuGet Package :

      using var workbook = new XLWorkbook();
      var ws = workbook.Worksheets.Add("Sheet1");
      ws.Cell("A1").Value = "Hello world!";                    
      using var ms = new MemoryStream();
      workbook.SaveAs(ms);
      ms.Position = 0;
    
    

    then with System.Net.Mail.MailMessage for mail :

     var attachment = new Attachment(ms, "Test.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
     mail.Attachments.Add(attachment);
    
    

    then with SmtpClient.Send, I received the mail with Test.xlsx attached and correct format

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 79,601 Reputation points Volunteer Moderator
    2025-08-23T23:54:21.9233333+00:00

    The call

    workBook.SaveAs(ms);

    is not writing to the stream, but rather converting value of ms to a string value (which returns the class name) and using the string as a filename. You need to write a temp file, then read the temp file in to a memory stream.

    note: System.Net.Mail only works with SMTP servers that support basic authentication. So google and office 365 are not supported anymore.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.