naffie
naffie

Reputation: 729

Sending email Attachment via SendGrid c# fails

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);

Upvotes: 4

Views: 8207

Answers (2)

Luis Gouveia
Luis Gouveia

Reputation: 8925

Try this:

var message = MailHelper.CreateSingleTemplateEmail(fromEmail, toEmail, "yourTemplateId", dictionaryWithVariablesToReplaceOnTemplate);

using var webClient = new WebClient();
webClient.Encoding = Encoding.UTF8;
var attachmentByteArray = webClient.DownloadData(attachmentFileUri);
var attachmentAsStringBase64 = Convert.ToBase64String(attachmentByteArray);
message.AddAttachment(attachmentFileName, attachmentAsStringBase64);

await client.SendEmailAsync(message);

Upvotes: 0

naffie
naffie

Reputation: 729

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.

Upvotes: 5

Related Questions