【问题标题】:MailMessage - Error Opening AttachmentMailMessage - 打开附件时出错
【发布时间】:2013-12-31 06:57:09
【问题描述】:

我正在使用 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?

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

【问题讨论】:

  • 你试过“Document.xlsx”和“application/octet-stream”吗?

标签: c# mailmessage npoi


【解决方案1】:

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

ms.Position = 0;

就是这样!

【讨论】:

  • 简单。惊人的。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-02
  • 2015-04-29
  • 2023-04-10
  • 1970-01-01
相关资源
最近更新 更多