7

I am able to send an attachment in a mail but the attachment content is blank and size is being shown as 0 bytes.

After doing some search over the internet found that we need to reset the memory stream position to 0 in order to start from start.

I tried that as well but it seems it is not working. Can you please help?

Please find below my code snippet:

NOTE: I am able to save the workbook and Data is present in the saved workbook.

        MemoryStream memoryStream = new MemoryStream();

        StreamWriter writer = new StreamWriter(memoryStream);
        writer.Write(xlWorkbook);
        writer.Flush();
        memoryStream.Position = 0;
        MailMessage mail = new MailMessage();
        SmtpClient SmtpServer = new SmtpClient("smtpclient");
        mail.From = new MailAddress("from@gmail.com");
        mail.To.Add("To@gmail.com");
        mail.Subject = "Entry";
        mail.Body = "Hello, PFA ";
        System.Net.Mail.Attachment attachment;

        attachment = new System.Net.Mail.Attachment(memoryStream,"xls");
        attachment.ContentDisposition.FileName = "Input" + DateTime.Now.ToString("yyyyMMdd_hhss") + ".xls";
        mail.Attachments.Add(attachment);
        SmtpServer.Port = 465;
        SmtpServer.UseDefaultCredentials = false;
        SmtpServer.Credentials = new System.Net.NetworkCredential("Username", "password");
        SmtpServer.EnableSsl = true;
        SmtpServer.Send(mail);
        writer.Dispose();
Rik
  • 26,673
  • 13
  • 47
  • 65
Vineet More
  • 161
  • 1
  • 1
  • 8

1 Answers1

5

I think the attachment is confusing the mail system. Microsoft's recommendation is to specify the content type as an octet. Below is a replacement for initializing the attachment. The reset of your code looks fine.

string filename = "Input" + DateTime.Now.ToString("yyyyMMdd_hhss") + ".xls";
attachment = new System.Net.Mail.Attachment(memoryStream, filename, MediaTypeNames.Application.Octet);
Virmundi
  • 2,157
  • 1
  • 21
  • 31
  • See this: https://stackoverflow.com/questions/3710677/email-attachment-from-the-memorystream-comes-empty?rq=1 – Dan_J Jul 07 '17 at 10:48