How to Send an SMS in 30 Seconds with Golang

June 23, 2021
Written by
Reviewed by

How to Send an SMS in 30 Seconds with Golang

Twilio is all about powering communication and doing it conveniently and fast in any language.  

In this tutorial you’ll learn how to deliver a quick message or notification via SMS directly from a Go application. You’ll use the new Twilio Go Helper Library to send an SMS in an insanely fast manner. Ready? Let's get started!

Tutorial requirements

Buy a Twilio phone number

If you haven't done so already, purchase a Twilio phone number to send the SMS from.

Log in to the Twilio Console, select Phone Numbers, and then click on the red plus sign to buy a Twilio number. Note that if you are using a free account you will be using your trial credit for this purchase.

On the “Buy a Number” page, select your country and check “SMS” in the capabilities field. If you’d like to request a number from your region, you can enter your area code in the “Number” field.

Buy a phone number

Click the “Search” button to see what numbers are available, and then click “Buy” for the number that you like from the results. After you confirm your purchase, click the “Close” button.

Configure Twilio credentials and phone numbers

To be able to send an SMS via Twilio, the Go application will need to have access to your Twilio account credentials to authenticate. Likewise, to send an SMS, it will need to have two phone numbers: the number of the sender, which is the number you bought in the previous section, and the number of the recipient, which can be your personal mobile number.

The most convenient and secure way to define these configuration values is to set environment variables for them.

The Twilio credentials that you need are your “Account SID” and your “Auth Token”. You can find both on the dashboard of the Twilio Console:

Twilio account SID and auth token

In your terminal, define the following environment variables:

export TWILIO_ACCOUNT_SID=xxxxxxxxx
export TWILIO_AUTH_TOKEN=xxxxxxxxx
export TWILIO_PHONE_NUMBER=xxxxxxxxx
export TO_PHONE_NUMBER=xxxxxxxxx

If you are following this tutorial on a Windows computer, use set instead of export to define your environment variables in the command prompt. For the phone numbers, use the E.164 format, which includes a plus sign and the country code.

If you want to learn more about environment variables, check out our how to set environment variables tutorial.

Send an SMS with Go

With the four environment variables set as shown in the previous section, you can now write a short Go program to send an SMS. Open a terminal window, find a suitable location, and create a new directory where the Go project will live:

mkdir go-sms
cd go-sms

Then create a Go module for your new project:

go mod init example.com/sms

After you execute the above command, a *go.mod* file will be added to your project.

The only dependency that you need for this project is the Twilio Go Helper library. You can install it as follows:

go get github.com/twilio/twilio-go

To write the application, launch your favorite code editor and open a file named sms.go inside the project directory you created above. Enter the following code in it:

package main

import twilio "github.com/twilio/twilio-go"
import openapi "github.com/twilio/twilio-go/rest/api/v2010"
import "os"
import "fmt"

func main() {
    client := twilio.NewRestClient()

    params := &openapi.CreateMessageParams{}
    params.SetTo(os.Getenv("TO_PHONE_NUMBER"))
    params.SetFrom(os.Getenv("TWILIO_PHONE_NUMBER"))
    params.SetBody("Hello from Golang!")

    _, err := client.Api.CreateMessage(params)
    if err != nil {
        fmt.Println(err.Error())
    } else {
        fmt.Println("SMS sent successfully!")
    }
}

This application begins by creating a Twilio client object, which is automatically initialized with the Account SID and Auth Token credentials you set in environment variables earlier.

Then, a CreateMessageParams structure is created and initialized with the “to” and “from” phone numbers (also imported from environment variables) and the body of the text message you are about to send.

The Twilio client object is finally used to create a new message resource, initialized with the parameter structure created above. This is all it takes to send a text message with Twilio!

The call to CreateMessage() will return a response (which is not used in this short example) and an error object that will give you useful information should the message fail to send.

Save the sms.go file and then go back to your terminal to run it as follows:

go run sms.go

In just a moment, you will receive the SMS on your mobile phone!

Received SMS

Note that if you are using a free Twilio account, Twilio requires that the number that you use as an SMS recipient is verified in your account. This requirement does not apply if you are using a paid account.

Conclusion

I hope this short tutorial gives you ideas to continue working with the Go helper library. At the time I’m writing this article, this library is still being actively developed, so be sure to check the documentation and source code repository often to learn about new releases.

I can’t wait to see what you build with Twilio and Go!

Miguel Grinberg is a Principal Software Engineer for Technical Content at Twilio. Reach out to him at mgrinberg [at] twilio [dot] com if you have a cool project you’d like to share on this blog!