Send an Email through AWS SES with GoLang

Learn how to send an email through AWS SES, GoLang & GO-AWS-SDK

Table of contents

No heading

No headings in the article.

Hello Gophers,

Video tutorial for the below tutorial

image.png

image.png

In this blog, we are going to see how to send a message to an email address with Golang and AWS-SDK for Go. The AWS SDK for Go provides APIs and utilities that developers can use to build Go applications that use AWS services. We are going to use AWS SES (Simple Email Service) to send an email.

Install the AWS SDK for Go

$ go get -u github.com/aws/aws-SDK-go/...

Get your AWS Access Keys

  1. Open the IAM console.
  2. On the navigation menu, choose Users.
  3. Choose your IAM user name (not the check box).
  4. Open the Security credentials tab, and then choose to Create access key.
  5. To see the new access key, choose Show. Your credentials resemble the following: Access key ID: AKIAIOSFODNN7EXAMPLE Secret access key: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
  6. To download the key pair, choose the Download .csv file. Store the keys in a secure location.

Config Setup

  1. Your AWS config and credentials will be stored under ~/.aws/config and ~/.aws/credentials. Those are the default values for your AWS SDK Environment. If you want you can edit them.

  2. Run the below command in the terminal to let the Go Program know that it should pick up the AWS config from the ~/.aws directory

$ export AWS_SDK_LOAD_CONFIG=true

Execution

Now let us jump into the execution part:

  • First verify your sender email address in the AWS SES Console. If your AWS SES is in Sandbox then you also need to verify the receiver email address as well.

Screenshot 2022-03-20 at 6.00.44 PM.png

  • Setup your Go Project and in your .go file add the below import statements
package main

import (
    "fmt"

    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/awserr"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/ses"
)
  • Define the required const variables for AWS SES to send an email:
const (
    Sender    = "sender@gmail.com"
    Recipient = "receiver@gmail.com"
    Subject   = "Vasanth through Amazon SES (AWS SDK for Go)"
    HtmlBody  = "<h1 style='color:blue'>Amazon SES Test Email (AWS SDK for Go)</h1><p>This email was sent with " +
        "<a href='https://aws.amazon.com/ses/'>Amazon SES</a> using the " +
        "<a href='https://aws.amazon.com/sdk-for-go/'>AWS SDK for Go</a>.</p>"
    TextBody = "This email was sent with Amazon SES using the AWS SDK for Go."
    CharSet  = "UTF-8"
)
  • In your function first, create an AWS session
    sess, err := session.NewSessionWithOptions(session.Options{
        Profile: "ProfileName",
    })

    if err != nil {
        panic(err)
    }

You can find your profile name in the ~/.aws/config file. It automatically creates a session if you follow the setup carefully at the start of this blog. And also check if there is an error or not while creating the session.

  • Create a service from AWS Session
svc := ses.New(sess)
  • Define your SES Email Input
    input := &ses.SendEmailInput{
        Destination: &ses.Destination{
            CcAddresses: []*string{},
            ToAddresses: []*string{
                aws.String(Recipient),
            },
        },
        Message: &ses.Message{
            Body: &ses.Body{
                Html: &ses.Content{
                    Charset: aws.String(CharSet),
                    Data:    aws.String(HtmlBody),
                },
                Text: &ses.Content{
                    Charset: aws.String(CharSet),
                    Data:    aws.String(TextBody),
                },
            },
            Subject: &ses.Content{
                Charset: aws.String(CharSet),
                Data:    aws.String(Subject),
            },
        },
        Source: aws.String(Sender),
    }

Here we used our previously defined const variables to frame up our Email Input. We use AWS and see from the SDK to define our email input. For ses content we are passing Charset and Data. And remaining all is straightforward as we can understand by looking at the code.

  • After we have framed our SES SendEmailInput. Now we are going to send the email.
result, err := svc.SendEmail(input)

With the above-created service from the session, we are calling the SendEmail Function.

  • We will now check if there is an error while sending the email with the below with the help of given pre-defined ErrCodes given by the AWS SDK
    if err != nil {
        if aerr, ok := err.(awserr.Error); ok {
            switch aerr.Code() {
            case ses.ErrCodeMessageRejected:
                fmt.Println(ses.ErrCodeMessageRejected, aerr.Error())
            case ses.ErrCodeMailFromDomainNotVerifiedException:
                fmt.Println(ses.ErrCodeMailFromDomainNotVerifiedException, aerr.Error())
            case ses.ErrCodeConfigurationSetDoesNotExistException:
                fmt.Println(ses.ErrCodeConfigurationSetDoesNotExistException, aerr.Error())
            default:
                fmt.Println(aerr.Error())
            }
        } else {
            fmt.Println(err.Error())
        }

        return

    }
  • Now if there is no error while sending the email we are going to print the result
    fmt.Println("Email Sent to address: " + Recipient)
    fmt.Println(result)
  • After executing the above program
$ go run main.go

I can receive the message-id

{
  MessageId: "0100017fa720252b-b635338c-fa69-49a9-9285-3c87920b-000000"
}

Finally, This is how we can send an email with AWS SES with GoLang and AWS-SDK for Go.

Thanks for reading :)

Did you find this article valuable?

Support Vasanth Korada by becoming a sponsor. Any amount is appreciated!