Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending email Attachment via SendGrid c# fails

Tags:

c#

sendgrid

I'm working with an Azure mobile services backend and I can send an email successfully via SendGrid. However, each time I try to add an attachment, it fails. I never receive the email. After a little research, I found out that all I needed was a virtual path. I modified the path name but it still does not work.

I can't seem to figure out why this fails.

Below is my code:

var client = new SendGridClient("apiKey");

var msg = new SendGridMessage()
        {
            From = new EmailAddress(sender),
            Subject = "Adherence Report",
            PlainTextContent = "Sample Content ",
            HtmlContent = "<strong>Hello, Email!</strong>"
        };
            msg.AddTo(new EmailAddress(receipient, null));
            msg.AddAttachment(@"~\sample\adherence.csv", "Testing", null, null, null);

        var response = await client.SendEmailAsync(msg);
like image 994
naffie Avatar asked Oct 19 '25 13:10

naffie


1 Answers

I checked the contents of the response and realized that is was failing because the scheduled send was being canceled with a 400 BAD REQUEST error.

After some research, I came across this link mail errors from the SendGrid website. Under the section for Attachment Errors, they explain that

The attachment content must be base64 encoded.

This is why my attachment was failing. So to finally get it working, I edited my code as follows:

string sampleContent = Base64Encode("Testing");  // base64 encoded string
var client = new SendGridClient("apiKey");

var msg = new SendGridMessage()
    {
        From = new EmailAddress(sender),
        Subject = "Adherence Report",
        PlainTextContent = "Sample Content ",
        HtmlContent = "<strong>Hello, Email!</strong>"
    };
        msg.AddTo(new EmailAddress(recipient, null));
        msg.AddAttachment("myfile.csv", sampleContent, "text/csv", "attachment", "banner");

    var response = await client.SendEmailAsync(msg);

Turns out this wasn't a duplicate question after all since I was facing a different kind of issue with sending emails via SendGrid. The filename also works just as is. The call to Server.MapPath isn't necessary for me.

I'm able to receive emails with attachments successfully.

like image 172
naffie Avatar answered Oct 27 '25 07:10

naffie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!