How to Send an Email with Go and SendGrid in 30 Seconds

July 22, 2022
Written by
Reviewed by
Dainyl Cua
Twilion

How to Send an Email with Go and SendGrid in 30 Seconds

SendGrid is all about delivering exceptional email experiences. In this tutorial, you'll learn how to send your first email with Go and SendGrid in 30 seconds. To do this, you'll use the official Twilio SendGrid Golang API library to save yourself a lot of time and effort.

Ready? Let's get started!

Tutorial requirements

To follow along with the tutorial, you're only going to need three things:

  1. A SendGrid account. If you are new to Twilio Sendgrid you can create a free account, which allows you to send 100 emails per day — forever.
  2. Go, version 1.18 or newer. You can download an installer from the official Go website.
  3. An email address to receive the email.
  4. An email address to send the email which has a verified identity.

Create the project directory

Create a new directory named send-email-with-sendgrid in your Go workspace (somewhere inside $GOPATH/src), and change into it by running the following commands.

mkdir send-email-with-sendgrid
cd send-email-with-sendgrid

Import the required dependencies

The code will make use of two external libraries, ones not part of Go's standard library. These are GoDotEnv and SendGrid's Golang API library. To import them, in the terminal, run the following two commands.

go get github.com/joho/godotenv
go get github.com/sendgrid/sendgrid-go

Write the code

Then create a new file named send-email.go and paste the code below into the new file.

package main

import (
    "fmt"
    "log"
    "os"

    "github.com/joho/godotenv"
    "github.com/sendgrid/sendgrid-go"
    "github.com/sendgrid/sendgrid-go/helpers/mail"
)

func main() {
    // Load the environment variables from .env
    err := godotenv.Load()
    if err != nil {
            log.Fatal("Error loading .env file")
    }

    // Initialise the required mail message variables
    from := mail.NewEmail(os.Getenv("SEND_FROM_NAME"), os.Getenv("SEND_FROM_ADDRESS"))
    subject := "Let's Send an Email With Golang and SendGrid"
    to := mail.NewEmail(os.Getenv("SEND_TO_NAME"), os.Getenv("SEND_TO_ADDRESS"))
    plainTextContent := "Here is your AMAZING email!"
    htmlContent := "Here is your <strong>AMAZING</strong> email!"
    message := mail.NewSingleEmail(from, subject, to, plainTextContent, htmlContent)

    // Attempt to send the email
    client := sendgrid.NewSendClient(os.Getenv("SENDGRID_API_KEY"))
    response, err := client.Send(message)
    if err != nil {
            fmt.Println("Unable to send your email")
            log.Fatal(err)
    }

    // Check if it was sent
    statusCode := response.StatusCode
    if statusCode == 200 || statusCode == 201 || statusCode == 202 {
            fmt.Println("Email sent!")
    }
}

The code starts off by importing all of the required libraries. Then, it uses GoDotEnv to import the required environment variables from .env, which you'll create shortly. Following that, it initialises a series of variables, one for the recipient, sender, and email subject and body, both in plain text and HTML formats.

After that, it initialises a new email message with those variables. With the email message ready, a SendGrid Client object, which simplifies interacting with SendGrid's API is initialised and an attempt is then made to send the email.

If sending the email fails, "Unable to send your email" is printed to the terminal along with the specific reason why, returned from the API. Otherwise, if the status code from the response is 200, 201, or 202, the email is considered sent, and "Email sent!" is printed to the terminal.

Retrieve the required environment variables

The last thing to do is to retrieve the environment variables which the code relies upon. There are five of them:

SENDGRID_API_KEYThis authenticates your requests to SendGrid's API, allowing the code to interact with it.
SEND_FROM_NAMEThe human-readable name of the sender.
SEND_FROM_ADDRESSThe email address of the sender.
SEND_TO_NAME`The human-readable name of the recipient.
SEND_TO_ADDRESS`The email address of the recipient.


As previously mentioned, they'll be retrieved from .env by using the GotDotEnv library. So, create a new file named .env, and paste the following code in it.

SENDGRID_API_KEY=<SENDGRID API KEY>
SEND_FROM_NAME="<SENDER'S NAME>"
SEND_FROM_ADDRESS=<SENDER'S EMAIL ADDRESS>
SEND_TO_NAME="<RECIPIENT'S NAME>"
SEND_TO_ADDRESS=<RECIPIENT'S EMAIL ADDRESS>

Then, set the sender and recipient's details to the names and email addresses that you want to use.

Create a SendGrid API key

Now, you need to create a SendGrid API key. To do that, login to your SendGrid account. Then, in the SendGrid Dashboard, under "Settings > API Keys", click "Create API Key", in the upper right-hand corner.

Create SendGrid API key. Step One.

From there, add a meaningful name for the API key, such as "Send an email with Golang", and click "Create & View" in the lower right side of the page.

Copy SendGrid API key.

You'll then be shown your API key. In .env, replace <SENDGRID API KEY> with the new API key. It's important that you do this now, as once you leave the page you won't be able to see or copy the key again.

Send the email

Now, you're ready to send an email. To do that, run the following command from the command line.

go run send-email.go

If all went well, you'll see "Email sent!" written to the terminal, similar to the screenshot below.

The first email sent with Go and SendGrid viewed in Gmail

If not, from the SendGrid Dashboard, under "Suppressions > Blocks", have a look in the Blocks table to see if you have any records listed with the sender's email address, as in the example below. If so, then you're likely not allowed to send emails with that email address yet.

View blocked SendGrid senders

That's how to send an email with Go and SendGrid in 30 seconds

I hope that this tutorial has given you a taste for just how simple it can be to send an email when using the official Twilio SendGrid Golang API library. Have a deeper look at the library and the API documentation to get a fuller understanding of the available functionality.

Otherwise, I can't wait to see what you build with Golang and SendGrid!

Matthew Setter is a PHP Software Engineer of Technical Content at Twilio and a PHP and Go developer. He’s also the author of Deploy With Docker Compose. When he’s not writing PHP or Go code, he’s writing and editing great PHP articles here at Twilio. You can find him at msetter@twilio.com, Twitter, GitHub, and LinkedIn.