Search code examples
sendgridemail-attachments

Excel file send through Send grid attachment C# is corrupted


I'm using sendgrid to send mails with attachments. But seems like excel file is corrupted in the mail. This is the code I'm using

byte[] byteData = System.Text.Encoding.ASCII.GetBytes(File.ReadAllText(@"fullpath\test.xlsx"));

msg.Attachments = new List<SendGrid.Helpers.Mail.Attachment>
{
    new SendGrid.Helpers.Mail.Attachment
    {
        Content = Convert.ToBase64String(byteData),
        Filename = "test.xlsx",
        Type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        Disposition = "attachment"
    }
};

On opening of excel file, I'm getting a popup "We found a problem with content...If you trust click "Yes". On Yes, Excel cannot open this file. Can anyone please help me on this #Sendgrid


Solution

  • Twilio SendGrid developer evangelist here.

    I think the issue may be that you are getting the byte data by reading the file as text and then converting that text to bytes through the lens of ASCII encoding. It may work better to just read the file as bytes initially.

    Try:

    byte[] byteData = File.ReadAllBytes(@"fullpath\test.xlsx");
    
    msg.Attachments = new List<SendGrid.Helpers.Mail.Attachment>
    {
        new SendGrid.Helpers.Mail.Attachment
        {
            Content = Convert.ToBase64String(byteData),
            Filename = "test.xlsx",
            Type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            Disposition = "attachment"
        }
    };