MailMessage - 打开附件时出错

时间:2013-12-12 17:55:38

标签: c# mailmessage npoi

我正在使用NPOI创建excel工作簿并尝试将其作为附件发送到电子邮件中。我的代码如下:

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);
}

我已经排除了创建工作簿的代码,我已经过测试以确保它可以正常工作(我可以保存文件并打开它而不会出现问题)但是如果你想查看任何内容请咨询。 client只是我的SmtpClient

电子邮件发送没有问题,附件以Document.xls(如预期的那样)出现,但是当我打开它时,我收到以下消息(在Excel 2010中),当我单击“是”打开时,工作表是空白的。

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?

据我所知,我正在指定格式。有谁看到我做错了什么?任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:7)

我终于明白了。在将Stream传递给Attachment之前,我需要将其位置设置为零。

ms.Position = 0;

就是这样!