3

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);
naffie
  • 519
  • 1
  • 9
  • 28
  • 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`? – James Thorpe May 03 '17 at 14:32
  • Possible duplicate. Try the Server.MapPath to get full path http://stackoverflow.com/questions/37945281/sending-an-email-with-attachment-using-sendgrid – Papa Burgundy May 03 '17 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 May 03 '17 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 May 03 '17 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 May 03 '17 at 18:49

2 Answers2

4

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.

naffie
  • 519
  • 1
  • 9
  • 28
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);
Luis Gouveia
  • 4,095
  • 5
  • 34
  • 51