1

I have been trying to send an HTML email using the Sendgrid API, but I have been unsuccessful in embedding the html inside the json request.

This is an example of the html I am trying to send (emailtpl):

<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></head><body></body></html>

Things I have tried:

  1. html.EscapeString(emailtpl)
  2. strconv.Quote(emailtpl)
  3. using backticks ` inside the json template
  4. wrapping value with single quotes for the value in the json template.
  5. base64.StdEncoding.EncodeToString([]byte(emailtpl)) only display the base64 gibberish.

Items #1 and #5 are the only solutions that Sendgrid has accepted, but the html sent is not correct (as shown in the screenshot).

escape-butchered

Items #2 - #4 all result in Status 400 Bad Request.

Does anyone know how to embed html into Sendgrid API request that Sendgrid accepts AND it renders correctly?

patricus
  • 59,488
  • 15
  • 143
  • 145
Darian Hickman
  • 853
  • 10
  • 26
  • 1
    Which part of [the docs](https://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/index.html) and [the Go API](https://godoc.org/github.com/sendgrid/sendgrid-go/helpers/mail#NewSingleEmail) is unclear? – Peter Apr 03 '18 at 10:48
  • The docs only offer examples of text/plain. There are no text/html examples to work from. – Darian Hickman Apr 03 '18 at 17:16
  • The established Go API doesn't work from google app engine standard environment. See my troubleshooting post here: https://stackoverflow.com/questions/49596003/how-to-use-sendgrid-from-google-app-engine-golang – Darian Hickman Apr 03 '18 at 17:18

1 Answers1

0

Looking at the Sendgrid api docs, it looks like it should accept html. You will need to have the html properly escaped in the json string (and set the content->type = "text/html").

In your example template, the only problem I see are the double quotes in your meta tag. As a quick test to make sure everything is working, I would attempt to send the following html string:

<html><head></head><body>Hi!</body></html>

If that html string is successful, then you need to work on escaping your original html string example. The only invalid characters I see are the double quotes, which need to be escaped in json with backslashes. I'm not sure if go has a specific function for this, but it looks like this should work:

// import "strings"

strings.Replace(emailtpl, `"`, `\"`, -1)
patricus
  • 59,488
  • 15
  • 143
  • 145