I have SendGrid posting incoming emails as raw MIME messages to my C# API. Here is an example of the raw payload. I want to be able to open the excel attachments from the incoming MIME message and read the row and column data.
Once the API receives the post, I use MimeKit to process the attachments as follows (assume we are only dealing with .xlsx attachments here):
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.
}
}
Where GenerateStreamFromString is defined as:
private Stream GenerateStreamFromString(string s)
{
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write(s);
writer.Flush();
stream.Position = 0;
return stream;
}
I have tried loading the attachment stream into Excel Data Reader:
using (var attachmentStream = ((MimePart)attachment).ContentObject.Stream)
{
IExcelDataReader reader = ExcelReaderFactory.CreateOpenXmlReader(attachmentStream);
// Reader has "Cannot Find Central Directory" error.
}
As well as through EPPlus
var attachmentStream = ((MimePart)attachment).ContentObject.Stream
using (ExcelPackage package = new ExcelPackage(attachmentStream))
{
// Errors are thrown before we get here.
}
But both packages throw errors, which leads me to believe I am not getting the data stream properly from the MIME message.
Any help or thoughts are greatly appreciated, thanks in advance.