4

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);
5
  • 2
    "fails" and "does not work" doesn't give us much to go on - do you get any exceptions raised? Are there any indication of problems within the SendGrid admin interfaces? Have you inspected the contents of response? Commented May 3, 2017 at 14:32
  • Possible duplicate. Try the Server.MapPath to get full path stackoverflow.com/questions/37945281/… Commented May 3, 2017 at 14:37
  • @JamesThorpe, so far no exceptions are raised and I see no problems within the SendGrid interface. I have printed out the body of the response and this is what I have "response": "System.Net.Http.StreamContent", "file": "~\\sample\\adherence.txt" }}.
    – naffie
    Commented May 3, 2017 at 18:00
  • @PapaBurgundy I made that change as you suggested - msg.AddAttachment(System.Web.HttpContext.Current.Server.MapPath(@"~\sample\adherence.csv"), "Testing", null, null, null); . I still do not get an email even after this change. If I comment out this line however, I receive the email.
    – naffie
    Commented May 3, 2017 at 18:02
  • The status code value I printed out from the response also says it was a BadRequest. "response": "BadRequest", "file": "~\\sample\\adherence.txt" }}. I'm not sure what I'm doing wrong in this case. My code seems correct based on the samples I've seen.
    – naffie
    Commented May 3, 2017 at 18:49

2 Answers 2

5

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.

2
  • 1
    For reference, an example of Base64Encode could be: stackoverflow.com/a/11743162/459102 Commented Aug 12, 2018 at 16:04
  • Must be carefull extension of file.If you send pdf document , you must write msg.AddAttachment("myfile.pdf", sampleContent, "text/pdf", "attachment", "banner");
    – Mehmet
    Commented Jun 23, 2022 at 6:26
0

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.