How to send an email using Amazon SES?

In the post What is Amazon SES(Simple Email Service)?, we discussed what is Amazon SES and what are the various use cases it solves for us. In this post, I will use javascript and AWS SDK to show you an example of how to send an email using Amazon SES.

Pre-requisites

You need to verify the identity of the sender\’s email with the Amazon SES. This can be done using the console. You will provide your email and Amazon will send you an email with a verification link. Once your email is verified, you will be able to send email using the Amazon SES.

Sending An Email

First of the steps are similar, a set of access key and secret key for AWS SDK. We will set them up in our environment for accessing the resources in AWS.

export AWS_ACCESS_KEY_ID=your_access_key_idexport AWS_SECRET_ACCESS_KEY=your_secret_access_keyexport AWS_REGION=the_region_you_are_using

Once the environment is set up, you can use the sdk to send the email.

Sending a Text Email

const AWS = require(\"aws-sdk\");// Create a new SES object. const ses = new AWS.SES();const params = { Source: \"sender@sender.com\", // use the verified email address Destination: { ToAddresses: [ \"recipient@email.com\" ], }, Message: { Subject: { Data: \"Subject\", Charset: \"UTF-8\" }, Body: { Text: { Data: \"Text Body here\", Charset: \"UTF-8\" } } }};// using callbackses.sendEmail(params, function(err, data) { if(err) { console.log(err.message); } else { console.log(\"Email sent\"); }});

Sending a HTML Email

const AWS = require(\"aws-sdk\");// Create a new SES object. const ses = new AWS.SES();const params = { Source: \"sender@sender.com\", // use the verified email address Destination: { ToAddresses: [ \"recipient@email.com\" ], }, Message: { Subject: { Data: \"Subject\", Charset: \"UTF-8\" }, Body: { Html: { Data: \"HTML String here\", Charset: \"UTF-8\" } } }};// using callbackses.sendEmail(params, function(err, data) { if(err) { console.log(err.message); } else { console.log(\"Email sent\"); }});

Using Promise instead of callback

const AWS = require(\"aws-sdk\");// Create a new SES object. const ses = new AWS.SES();const params = { Source: \"sender@sender.com\", // use the verified email address Destination: { ToAddresses: [ \"recipient@email.com\" ], }, Message: { Subject: { Data: \"Subject\", Charset: \"UTF-8\" }, Body: { Html: { Data: \"HTML String here\", Charset: \"UTF-8\" } } }};// using callbackses.sendEmail(params).promise().then(() => console.log(\"email sent\"));

You can find the examples above in the github repo. Stay tuned for more examples and till then Happy Coding.