Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MailMessage - Error Opening Attachment

I am using NPOI to create an excel workbook and attempting to send it as an attachment in an email. My code is as follows:

var wb = new HSSFWorkbook();

//create the workbook

using(var ms = new MemoryStream())
{
    wb.Write(ms);
    var msg = new MailMessage();

    //create email

    msg.Attachments.Add(new Attachment(ms, "Document.xls", "application/vnd.ms-excel"));

    client.Send(msg);
}

I have excluded the code to create the workbook, I have tested to make sure it works (I'm able to save the file and open it without issue) but if you want to see anything please ask. client is just my SmtpClient.

The email is sent without issue and the attachment is present as Document.xls (as expected), however when I open it I get the following message (in Excel 2010) and when I click 'Yes' to open, the worksheet is blank.

The file you are trying to open, 'Document.xls', is in a differrent format than specified by the file extension. Verify that the file is not corrupted and is from a trusted source before opening the file. Do you want to open the file now?

To the best of my knowledge I am specifying the format. Does anyone see what I'm doing wrong? Any help would be appreciated.

like image 616
aw04 Avatar asked Feb 14 '23 09:02

aw04


1 Answers

I finally figured it out. Before passing the Stream into the Attachment, I needed to set its position back to zero.

ms.Position = 0;

That's it!

like image 128
aw04 Avatar answered Feb 23 '23 03:02

aw04