DEV Community

ADITYA OKKE SUGIARSO
ADITYA OKKE SUGIARSO

Posted on

Send Email using aws-sdk-v2.sesv2 on golang

stack:

  • go
  • aws

ref:

prep:

step:

1. initiate ses service on aws
choose your region on aws

region list

2. create identities to use sandbox feature from aws ses

identities menu

click create identity button
Create identity button

fill form
identity details
create another identity for user@gmail.com
and you should get

identities
finally you just need to verify your email by click link verification on the email inbox

2.Initialize Project

$ mkdir ~/helloaws
$ cd ~/helloaws
$ go mod init helloaws
Enter fullscreen mode Exit fullscreen mode

3.Add SDK Dependencies

$ go get github.com/aws/aws-sdk-go-v2/aws
$ go get github.com/aws/aws-sdk-go-v2/config
$ go get github.com/aws/aws-sdk-go-v2/service/sesv2
Enter fullscreen mode Exit fullscreen mode

4.Write Code

package main

import (
    "context"
    "fmt"
    "log"

    "github.com/aws/aws-sdk-go-v2/aws"
    "github.com/aws/aws-sdk-go-v2/config"
    "github.com/aws/aws-sdk-go-v2/service/sesv2"
    "github.com/aws/aws-sdk-go-v2/service/sesv2/types"
)

func main() {
    // Using the SDK's default configuration, load additional config
    // and credentials values from the environment variables, shared
    // credentials, and shared configuration files
    cfg, err := config.LoadDefaultConfig(context.TODO(), config.WithRegion("ap-southeast-1"))
    if err != nil {
        log.Fatalf("unable to load SDK config, %v", err)
    }

    // Build the request with its input parameters
    resp, err := svc.SendEmail(context.TODO(), &sesv2.SendEmailInput{
        FromEmailAddress: aws.String("admin@gmail.com"),
        Destination: &types.Destination{
            ToAddresses: []string{"user@gmail.com"},
        },
        Content: &types.EmailContent{
            Simple: &types.Message{
                Subject: &types.Content{
                    Data: aws.String("Test Email"),
                },
                Body: &types.Body{
                    Text: &types.Content{
                        Data: aws.String("This is a test email sent using AWS SES."),
                    },
                },
            },
        },
    })
    if err != nil {
        fmt.Printf("Error sending email: %v\n", err)
    }

    fmt.Printf("Email sent successfully, message ID: %s\n", *resp.MessageId)
}

Enter fullscreen mode Exit fullscreen mode

5. Check user@gmail.com inbox or spam for the test email

email sent

Top comments (0)