Skip to contentSkip to navigationSkip to topbar
On this page

Email API Quickstart for Go


In this quickstart, you'll learn how to send your first email using the Twilio SendGrid Mail Send API and Go(link takes you to an external page).


Prerequisites

prerequisites page anchor

Be sure to perform the following prerequisites to complete this tutorial. You can skip ahead if you've already completed these tasks.

  1. Sign up for a SendGrid account.
  2. Enable Two-factor authentication.
  3. Create and store a SendGrid API Key with Mail Send > Full Access permissions.
  4. Complete Domain Authentication.
  5. Install Go.

Skip the prerequisites

Sign up for a SendGrid account

sign-up-for-a-sendgrid-account page anchor

When you sign up for a free SendGrid account(link takes you to an external page), you'll be able to send 100 emails per day forever. For more account options, see our pricing page(link takes you to an external page).

Enable Two-factor authentication

enable-two-factor-authentication page anchor

Twilio SendGrid requires customers to enable Two-factor authentication (2FA). You can enable 2FA with SMS or by using the Authy(link takes you to an external page) app. See the 2FA section of our authentication documentation for instructions.

Create and store a SendGrid API key

create-and-store-a-sendgrid-api-key page anchor

Unlike a username and password — credentials that allow access to your full account — an API key is authorized to perform a limited scope of actions. If your API key is compromised, you can also cycle it (delete and create another) without changing your other account credentials.

Visit our API Key documentation for instructions on creating an API key and storing an API key in an environment variable. To complete this tutorial, you can create a Restricted Access API key with Mail Send > Full Access permissions only, which will allow you to send email and schedule emails to be sent later. You can edit the permissions assigned to an API key later to work with additional services.

Once your API key is assigned to an environment variable — this quickstart uses SENDGRID_API_KEY — you can proceed to the next step.

export SENDGRID_API_KEY=<Your API Key>

Verify your Sender Identity

verify-your-sender-identity page anchor

To ensure our customers maintain the best possible sender reputations and to uphold legitimate sending behavior, we require customers to verify their Sender Identities by completing Domain Authentication. A Sender Identity represents your 'From' email address—the address your recipients see as the sender of your emails.

(information)

Info

To get started quickly, you may be able to skip Domain Authentication and begin by completing Single Sender Verification. Single Sender Verification is recommended for testing only. Some email providers have DMARC policies that restrict email from being delivered using their domains. For the best experience, please complete Domain Authentication. Domain Authentication is also required to upgrade from a free account.

Before installing Go, you can see if you already have a version on your machine.

(information)

Info

The Twilio SendGrid Go helper library requires Go version 1.7 or later.

Go version check

go-version-check page anchor

Check your Go version by opening your terminal (also known as a command line, or console) and typing the following command.

go version

If you have Go installed, the terminal will print something like the following output.

go version go1.15.7 darwin/amd64

If you do not already have a version of Go installed, visit the Go website(link takes you to an external page) to download and install a version appropriate for your operating system.


Starting the project

starting-project page anchor

Using a Twilio SendGrid helper library(link takes you to an external page) is the fastest way to deliver your first email.

Start by creating a project folder for this app. The following examples will use a folder called sendmail.

mkdir sendmail

Next, navigate into the sendmail directory where you will complete the rest of the tutorial.

cd sendmail

This quickstart assumes you are using Go Modules(link takes you to an external page) to manage your Go project and dependencies. If you prefer to use the $GOPATH workspace, the Twilio SendGrid helper library will still work, but the project creation steps that follow will differ slightly from your setup.

(information)

Info

There are multiple ways to handle projects and their dependencies when writing Go. Beginning with version 1.11, Go introduced Go Modules as an official dependency management tool. For more information about Go dependencies, see "Migrating to Go Modules"(link takes you to an external page).

The Go mod(link takes you to an external page) package manager is included as part of the Go standard library beginning with version 1.11. You can use the mod command to initialize your project. You must pass mod a path for your module. The following examples will use example.com/sendgrid/sendmail, but you will use the path appropriate for your project. For example, if you intend to store your project on GitHub under the username sg_gopher, your path will be github.com/sg_gopher/sendmail.

go mod init example.com/sendgrid/sendmail

You will now have a go.mod file that lists the path for your module and the version of Go used to create it. You will also have a go.sum file that stores a cryptographic hash for the content of each dependency in your project.

Next, use the go get command to install the Twilio SendGrid helper library and save it as a project dependency.

Install the helper library

install-the-helper-library page anchor
go get github.com/sendgrid/sendgrid-go

The terminal will print something like the following output.

1
go: github.com/sendgrid/sendgrid-go upgrade => v3.7.2+incompatible
2
go: finding module for package github.com/sendgrid/rest
3
go: found github.com/sendgrid/rest in github.com/sendgrid/rest v2.6.2+incompatible

Your go.mod file will now include the Twilio SendGrid sendgrid-go and rest libraries as project dependencies.


You're now ready to write some code. First, create a main.go file in your project directory.

The following Go block contains all the code needed in your main.go file to successfully deliver a message with the SendGrid Mail Send API. You can copy this code, modify the to and from variables, and run the code if you like. We'll break down each piece of this code in the following sections.

1
package main
2
3
import (
4
"fmt"
5
"log"
6
"os"
7
8
"github.com/sendgrid/sendgrid-go"
9
"github.com/sendgrid/sendgrid-go/helpers/mail"
10
)
11
12
func main() {
13
from := mail.NewEmail("Tira", "tiramisu@example.com") // Change to your verified sender
14
subject := "Sending with Twilio SendGrid is Fun"
15
to := mail.NewEmail("Sou", "souffle@example.com") // Change to your recipient
16
plainTextContent := "and easy to do anywhere, even with Go"
17
htmlContent := "<strong>and easy to do anywhere, even with Go</strong>"
18
message := mail.NewSingleEmail(from, subject, to, plainTextContent, htmlContent)
19
client := sendgrid.NewSendClient(os.Getenv("SENDGRID_API_KEY"))
20
response, err := client.Send(message)
21
if err != nil {
22
log.Println(err)
23
} else {
24
fmt.Println(response.StatusCode)
25
fmt.Println(response.Headers)
26
}
27
}

Your API call must have the following components.

  • A host (the host for Web API v3 requests is always https://api.sendgrid.com/v3/)
  • An API key passed in an Authorization Header
  • A request (when submitting data to a resource via POST or PUT, you must submit your request body in JSON format)

In your main.go file, set the package to main, import the SendGrid helper library, and import the SendGrid mail helper from the library. The library will handle setting the Host, https://api.sendgrid.com/v3/, for you.

1
package main
2
3
import(
4
"github.com/sendgrid/sendgrid-go"
5
"github.com/sendgrid/sendgrid-go/helpers/mail"
6
)

Next, declare a function named main. This function is where you will build your email message and make a request to the Twilio SendGrid Mail Send API.

1
func main() {
2
3
}

Now you're ready to set up the from, to, subject, and message body htmlContent. These values are passed to the API in a Personalizations object when using the v3 Mail Send API. You can assign each of these values to variables, and the SendGrid library will handle creating a personalizations object for you. Be sure to set the to variable to an email address with an inbox you can access.

The subject and htmlContent variables are just strings. However, you will set the from and to variables using the helper library's NewEmail constructor. The NewEmail constructor takes two arguments, a name and an address.

(information)

Info

Notice that there is a plainTextContent and an htmlContent variable in the full code block. Only one of these values is needed. If you include both variables, only the htmlContent value will be used as the body text of your email.

1
from := mail.NewEmail("Tira", "tiramisu@example.com") // Change to your verified sender
2
subject = "Sending with SendGrid is Fun"
3
to := mail.NewEmail("Sou", "souffle@example.com") // Change to your recipient
4
htmlContent := "<strong>and easy to do anywhere, even with Go</strong>"

To properly construct the message, pass each of the previous variables into the SendGrid library's NewSingleEmail function. You can assign this to a variable named message.

message := mail.NewSingleEmail(from, subject, to, htmlContent)

Next, use the API key you set up earlier. Remember, the API key is stored in an environment variable, so you can use the os.Getenv() method to access it. This means you also need to import Go's os library.

1
import (
2
"os"
3
)

Assign the key to a variable named client using the helper library's NewSendClient method. The helper library will pass your key to the v3 API in an Authorization header using Bearer token authentication.

client := sendgrid.NewSendClient(os.Getenv("SENDGRID_API_KEY"))

Lastly, you need to make a POST request to the SendGrid Mail Send API to deliver your message. The SendGrid helper library provides a Send function from SendGrid's REST library(link takes you to an external page) to make this request. Call the Send method on the client and pass in your message as an argument.

1
# Send an HTTP POST request to /mail/send
2
client.Send(message)

You can also print the response status code and headers. Import the fmt and log libraries to do this. You can then assign your client.Send call to response and err variables for logging.

1
import (
2
"fmt"
3
"log"
4
)
5
6
response, err := client.Send(message)
7
if err != nil {
8
log.Println(err)
9
} else {
10
fmt.Println(response.StatusCode)
11
fmt.Println(response.Headers)
12
}

With all this code in place, you can run your main.go file in your terminal to send the email.

go run main.go

If you receive a 202 status code(link takes you to an external page) printed to the console, your message was sent successfully. Check the inbox of the to address, and you will see your demo message.

If you don't see the email, you may need to check your spam folder.

If you receive an error message, you can reference our response message documentation for clues about what may have gone wrong.

All responses are returned in JSON format. We specify this by sending the Content-Type header. The Web API v3 provides a selection of response codes, content-type headers, and pagination options to help you interpret the responses to your API requests.

(information)

Info

Get additional onboarding support. Save time, increase the quality of your sending, and feel confident you are set up for long-term success with our Email API Onboarding guide.


This is just the beginning of what you can do with our APIs. To learn more, check the resources below.

Need some help?

Terms of service

Copyright © 2024 Twilio Inc.