从 SendGrid 发布的原始 MIME 消息中读取 C# 中的 excel 附件数据

Reading excel attachment data in C# from raw MIME message posted by SendGrid

我有SendGrid posting incoming emails as raw MIME messages to my C# API. Here is an example of the raw payload我希望能够从传入的 MIME 邮件中打开 excel 附件并读取行和列数据

一旦 API 收到 post,我使用 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 Data Reader:

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 消息中正确获取数据流。

非常感谢任何帮助或想法,提前致谢。

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

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

问题已解决!