2

我让SendGrid将传入的电子邮件作为原始 MIME 消息发布到我的 C# API。 这是原始有效负载的示例我希望能够从传入的 MIME 消息中打开 excel 附件并读取行和列数据

API 收到帖子后,我使用MimeKit处理附件,如下所示(假设我们在这里只处理 .xlsx 附件):

using (var emailSream = GenerateStreamFromString(emailString))
{
    var msg = MimeMessage.Load(emailSream);

    foreach (var attachment in msg.Attachments)
    {
        //  I want to be able to read the columns and rows of the excel sheet here.  
        //  I am already able to skip over any non-excel type attachments without issue.
    }
}

其中 GenerateStreamFromString 定义为:

private Stream GenerateStreamFromString(string s)
{
    MemoryStream stream = new MemoryStream();
    StreamWriter writer = new StreamWriter(stream);
    writer.Write(s);
    writer.Flush();
    stream.Position = 0;
    return stream;
}

我尝试将附件流加载到Excel 数据阅读器中

using (var attachmentStream = ((MimePart)attachment).ContentObject.Stream)
{
    IExcelDataReader reader = ExcelReaderFactory.CreateOpenXmlReader(attachmentStream);
    //  Reader has "Cannot Find Central Directory" error.
}

以及通过EPPlus

var attachmentStream = ((MimePart)attachment).ContentObject.Stream
using (ExcelPackage package = new ExcelPackage(attachmentStream))
{
    //  Errors are thrown before we get here.
}

但是这两个包都会抛出错误,这让我相信我没有从 MIME 消息中正确获取数据流。

非常感谢任何帮助或想法,在此先感谢。

4

1 回答 1

3

嗬!需要解码附件(SendGrid还给我提供了编码信息,只是我没听好):

using (var attachmentStream = new MemoryStream())
{
    ((MimePart)attachment).ContentObject.DecodeTo(attachmentStream);
    attachmentStream.Position = 0;
    IExcelDataReader reader = ExcelReaderFactory.CreateOpenXmlReader(attachmentStream);
}

问题解决了!

于 2016-09-09T00:19:30.697 回答