While email automation is a vital part of modern business workflows, integrating with services like Amazon Simple Email Service (SES) often requires a robust and concise programming language. Golang, with its strong standard library and straightforward syntax, is an excellent choice for developers needing to interact with AWS SES for email operations. This blog will explore how to harness Golang's capabilities to effectively send emails using AWS SES.
Prerequisites
Before diving into the implementation, let's ensure you have everything needed to start sending emails with AWS SES using Golang:
- Install Go: On your Mac, use Homebrew by running the command in your terminal:
brew install go
- AWS Account: Make sure you have an active AWS account and have obtained the necessary credentials with permissions to use AWS SES.
. Configure AWS credentials: Next, you need to configure your AWS credentials. You can do this through a shared credentials file or by setting environment variables. For the shared credentials file, run aws configure
and enter the AWS_ACCESS_KEY_ID
and the AWS_SECRET_ACCESS_KEY
along with the AWS_REGION
(make sure to have the AWS CLI installed beforehand). If you don't have the AWS CLI installed, you can alternatively create a file named ~/.aws/credentials
with the following content:
[default]
aws_access_key_id = YOUR_ACCESS_KEY
aws_secret_access_key = YOUR_SECRET_KEY
aws_region = YOUR_AWS_REGION
Replace YOUR_ACCESS_KEY
and YOUR_SECRET_KEY
with your actual AWS access key and secret key. If you prefer to use environment variables, you can set AWS_ACCESS_KEY_ID
and AWS_SECRET_ACCESS_KEY
in your shell.
Note: If you would like to directly deploy a Lambda function based on Go to your AWS Account without setting anything up locally, check out our [GitHub project](https://github.com/semplates/aws-ses-template-manager) and follow along the readme to easily set everything up and test it within the AWS environment.
Setting Up on macOS
Setting up your Go application on macOS involves a few straightforward steps:
- Create a Folder for Your Application: Choose a suitable location on your system and create a new folder to house your Go application.
- Create main.go: Within your new folder, create a file named
main.go
– this will be where you write your Go code to send emails using AWS SES.
The main.go Breakdown
package main
import (
"context"
"encoding/json"
"fmt"
"os"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/ses"
"github.com/aws/aws-sdk-go-v2/service/ses/types"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
"net/http"
)
type EmailRequestBody struct {
ReceiverEmail string `json:"receiverEmail"`
SenderEmail string `json:"senderEmail"`
TemplateName string `json:"templateName"`
Placeholders map[string]string `json:"placeholders"`
}
func sendTemplatedEmail(client *ses.Client, input *ses.SendTemplatedEmailInput) (string, error) {
output, err := client.SendTemplatedEmail(context.Background(), input)
if err != nil {
errorMessage := fmt.Sprintf(`{"error_message": "%s"}`, err.Error())
return "", fmt.Errorf(errorMessage)
}
return *output.MessageId, nil
}
func handleRequest(ctx context.Context, request EmailRequestBody) (events.APIGatewayProxyResponse, error) {
cfg, err := config.LoadDefaultConfig(ctx, config.WithRegion(os.Getenv("AWS_REGION")))
if err != nil {
return events.APIGatewayProxyResponse{}, err
}
client := ses.NewFromConfig(cfg)
templateData, err := json.Marshal(request.Placeholders)
if err != nil {
return events.APIGatewayProxyResponse{}, err
}
input := &ses.SendTemplatedEmailInput{
Source: aws.String(request.SenderEmail),
Destination: &types.Destination{ToAddresses: []string{request.ReceiverEmail}},
Template: aws.String(request.TemplateName),
TemplateData: aws.String(string(templateData)),
}
messageId, err := sendTemplatedEmail(client, input)
if err != nil {
return events.APIGatewayProxyResponse{
StatusCode: http.StatusInternalServerError,
Body: err.Error(),
}, nil
}
successMessage := fmt.Sprintf("Message successfully sent with Message ID: %s", messageId)
return events.APIGatewayProxyResponse{
StatusCode: http.StatusOK,
Body: successMessage,
}, nil
}
func main() {
if os.Getenv("AWS_LAMBDA_RUNTIME_API") != "" {
lambda.Start(handleRequest)
} else {
localTest()
}
}
func localTest() {
// Mimic an event
request := EmailRequestBody{
ReceiverEmail: "jondoe@semplates.io",
SenderEmail: "jondoe@semplates.io",
TemplateName: "SEMPLATES_DEMO_TEMPLATE",
Placeholders: map[string]string{
"FIRST_NAME": "John",
"LAST_NAME": "Doe",
},
}
response, err := handleRequest(context.Background(), request)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("Response:", response.Body)
}
Building and Running Locally
Once you have your main.go
ready with the provided code, you can build and run your Go application locally with the following steps:
- Open a terminal and navigate to the folder containing your
main.go
file. - Install the dependencies.
- Update the receiver and sender email and make sure the used template name exists in AWS SES.
- Execute your program by running
go run .
within your project directory.
Now, let's take a closer look at your main.go
file and what each part does.
Managing Templates on AWS SES the New Way with Semplates
Managing AWS SES templates can be a complicated and time-consuming process when using the AWS CLI. It's a technical task that requires deep knowledge of command-line operations and JSON formatting. This complexity becomes a roadblock for teams that need to iterate rapidly and make frequent updates to their email templates.
Enter Semplates
Semplates offers an innovative and user-friendly solution for managing AWS SES templates. By providing a graphical user interface, Semplates dramatically simplifies the process of creating, updating, and deleting email templates. It's not just about improving efficiency; it's about revolutionizing the way teams handle email automation.
With Semplates, developers have reported an 8 to 10 times increase in workflow efficiency when managing SES templates. This efficiency boost is a game-changer for businesses, freeing up developer time and allowing teams to focus on core product development.
Empowering Teams
Semplates empowers design and product teams to take control of email template management without constantly relying on developer support. This newfound autonomy speeds up iteration cycles and streamlines the email development process.
Experience the Future of Email Template Management
We invite you to step into the future of email automation with Semplates. Sign up for a free trial and explore a new world of productivity, where managing AWS SES templates is no longer a chore but a seamless part of your workflow.
Join Semplates — the platform where developers, designers, and product managers work together effortlessly to achieve email excellence within the AWS ecosystem.
In conclusion, by integrating AWS SES with Golang and harnessing the power of Semplates for template management, businesses can streamline their email operations, enhance productivity, and focus more on innovation and development.
Ready to get started with AWS SES and Golang? Set up your environment, and begin sending emails smarter, not harder.
Remember to replace the email addresses in the localTest()
function with the actual recipient and sender email addresses you intend to use. This Markdown-formatted blog post is ready for publication, containing both the explanatory text and the main.go
code.