user2852270
user2852270

Reputation: 51

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

Upvotes: 3

Views: 1646

Answers (2)

Zahid Mustafa
Zahid Mustafa

Reputation: 195

Try below

msg.AddAttachment("test.xlsx"); // Physical file path

Make assure file path is relevant

or You try with Bytes as well,

var bytes = File.ReadAllBytes(filePath); 
var file = Convert.ToBase64String(bytes);
msg.AddAttachment("Name.xls", file);

Upvotes: 0

philnash
philnash

Reputation: 73029

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"
    }
};

Upvotes: 1

Related Questions