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

本文关键字:中的 读取 excel 数据 消息 SendGrid MIME 原始 | 更新日期: 2023-09-27 18:06:12

我让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 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发布的原始MIME消息中读取c#中的excel附件数据

好!需要解码附件(SendGrid甚至为我提供了编码信息,我只是没有听好):

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

问题解决了!