If you have a non-library SendGrid issue, please contact our support team.
If you can't find a solution below, please open an issue.
- Migrating from v2 to v3
- Continue Using v2
- Testing v3 /mail/send Calls Directly
- Error Messages
- Versions
- Environment Variables and Your SendGrid API Key
- Viewing the Request Body
Please review our guide on how to migrate from v2 to v3.
Here is the last working version with v2 support.
Download:
Click the "Clone or download" green button in GitHub and choose download.
Here are some cURL examples for common use cases.
An error is returned if caused by client policy (such as CheckRedirect), or failure to speak HTTP (such as a network connectivity problem).
To read the error message returned by SendGrid's API:
func main() {
from := mail.NewEmail("Example User", "[email protected]")
subject := "Hello World from the SendGrid Go Library"
to := mail.NewEmail("Example User", "[email protected]")
content := mail.NewContent("text/plain", "some text here")
m := mail.NewV3MailInit(from, subject, to, content)
request := sendgrid.GetRequest(os.Getenv("SENDGRID_API_KE"), "/v3/mail/send", "https://api.sendgrid.com")
request.Method = "POST"
request.Body = mail.GetRequestBody(m)
response, err := sendgrid.API(request)
if err != nil {
log.Println(err)
} else {
fmt.Println(response.StatusCode)
fmt.Println(response.Body)
fmt.Println(response.Headers)
}
}
CAUTION: A non-2xx status code doesn't cause an error on sendgrid.API and the application has to verify the response:
resp, err := sendgrid.API(request)
if err != nil {
return err
}
if resp.StatusCode >= 400 {
// something goes wrong and you have to handle (e.g. returning an error to the user or logging the problem)
log.Printf("api response: HTTP %d: %s", resp.StatusCode, resp.Body)
// OR
// return fmt.Errorf("api response: HTTP %d: %s", resp.StatusCode, resp.Body)
}
We follow the MAJOR.MINOR.PATCH versioning scheme as described by SemVer.org. Therefore, we recommend that you always pin (or vendor) the particular version you are working with to your code and never auto-update to the latest version. Especially when there is a MAJOR point release, since that is guaranteed to be a breaking change. Changes are documented in the CHANGELOG and releases section.
All of our examples assume you are using environment variables to hold your SendGrid API key.
If you choose to add your SendGrid API key directly (not recommended):
os.Getenv("SENDGRID_API_KEY")
becomes
"SENDGRID_API_KEY"
In the first case SENDGRID_API_KEY is in reference to the name of the environment variable, while the second case references the actual SendGrid API Key.
When debugging or testing, it may be useful to examine the raw request body to compare against the documented format.
You can do this right before you call response, err := client.Send(message)
like so:
fmt.Println(string(mail.GetRequestBody(message)))