MVC Excel Email Attachment with NPOI
The First Question I had after successfully creating a Excel sheet was how do I create an attachment from a stream? A second to be more specific was how do I add an attachment to an email using System.Net.Mail? Ultimately I wanted to have the Excel Exports in C# using NPOI but I started small and thankfully others had already asked and answered these questions. After which was just a matter of knowing What the correct content-type for excel files was?
MailMessage mail = new MailMessage(); HSSFWorkbook workbook = CreateExcel(OrderId); MemoryStream ms = new MemoryStream(workbook.GetBytes()); mail.Attachments.Add(new Attachment(ms, "example.xls", "application/vnd.ms-excel")); _emailService.SendEmail("firstname.lastname@example.org", "Email test", "Testing 123");
Changed it to..
MemoryStream ms = new MemoryStream(); workbook.Write(ms);This was based on the QA "NPOI - Sending workbook as email attachment."
HSSFWorkbook (POI API Documentation)
MemoryStream.Position Property (System.IO)