从SendGrid

时间:2016-09-08 22:37:06

标签: c# mime sendgrid mimekit

我有SendGrid将传入的电子邮件作为原始MIME邮件发布到我的C#API。 Here is an example of the raw payload我希望能够从传入的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消息中正确地获取数据流。

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

1 个答案:

答案 0 :(得分:2)

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

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

问题解决了!