Friday, August 16, 2019

How to send custom Email using AWS SES  on Node.js App?

Amazon Simple Email Service (AWS SES) enables you to send and receive email using a reliable and scalable email platform. It only provides a sandbox environment by default to prevent spamming. Amazon SES requires to verify your identities (the domains or email addresses that you used to send emails and receive emails ) in the sandbox environment to confirm that you own them. Because you are only allowed to send emails from verified identities.





Verifying an Email Address


There are two ways to verify your identity.

1. Verify an Email address using the Amazon SES console


Here you have to sign in to the AWS Management Console and verify your email address by sending a verification email and confirm it.

Path to verify an email address
       Services → Simple Email Service → Email Addresses → Verify a New Email Address



2. Verify an Email Address Using the Amazon SES API



First of all, you need to configure the AWS CLI on your machine. The aws configure command is the fastest way to set up your AWS CLI installation. When you type this command, the AWS CLI prompts to get the following information 

  • access key
  • secret access key
  • AWS Region
  • output format

That information will be used at any time you run an AWS CLI command that doesn't explicitly specify a profile to use.

Then run the following command at the AWS CLI by replacing sender@example.com with the email address that you want to verify.

     aws ses verify-email-identity --email-address sender@example.com



Send an Email


You can send an email with Amazon Simple Email Service (Amazon SES) using one of the following ways.

  • Amazon SES console
  • Amazon SES Simple Mail Transfer Protocol (SMTP) interface
  • Amazon SES API


In this article, I am going to describe how you can send an email using Amazon SES API with the help of AWS SDK in Node.js.

Setup the project


You can create a simple node project by following these instructions.


  1. Create an empty directory
  2. Open a console and navigate to the recently created directory
  3. Run npm init command and fill out the required information to initialize the project
  4. Run npm install --save express command to install express to create and run a web server with Node
  5. Create a file named server.js and add the following code snippet to it and save.

--------------------------------------------------------------------------------------------------------------


const express = require('express');
const app = express();
var AWS = require("aws-sdk");

app.post('/sendEmail', function (req, res) {
    const orgId = req.params.orgId;
     AWS.config.update({                                    //Configure AWS credentials
    accessKeyId: "AKIAIE3FIP1QWAESUP2Q",
    secretAccessKey: "wQf22vx81Wsdffsdfsduyuybs3r7",
    region: "us-east-1"
    });
    const ses = new AWS.SES({ apiVersion: "2010-12-01" });

    return new Promise(function (resolve, reject) {
    ses.sendEmail(
      {
        Source: "source@gmail.com",  //Senders email address
        //Reciever/s email address/es
        Destination: { ToAddresses: ["reciever@gmail.com"] }, 
        Message: { //content of the email
          Subject: {  
            Data: "Test Email"
          },
          Body: {
            Html: {
              Charset: "UTF-8",
              Data: "<html><body><h1>Hello User,</h1><p>This is a test email to check AWS SES</p> <p>Thanks...!</p></body></html>"
            }
          }
        }
      },
      function (err, data) {
        if (err) {
          console.log("Verification email sending process is failed", err);
          reject(res.status(500).send(err));          
        }
        console.log("Verification email sending process is success", data);
        resolve( res.send(data));
      }
    )  
})
})

app.listen(3000, function () {
  console.log('Node web app listening on port 3000!')
})


--------------------------------------------------------------------------------------------------------------


Please note that you have to replace the following variables' values in code snippet by adding valid values to them before run the Node server.  
  • accessKeyId :- AWS access key ID 
  • secretAccessKey :- AWS secret access key 
  • Source :- Verified source  email address 
  • ToAddresses :- Verified destination email address/es as elements of an array
  • Body.Subject.Data :- Subject of the email 
  • Body.Html.Data The message body in HTML format. 

7. Run node server.js  command to run the Node server.

8. Run following cURL command on the separate terminal
       
              curl -X POST \
                   http://localhost:3000/sendEmail \

                                 or 

create HTTP POST call using Postman on http://localhost:3000/sendEmail link 

to invoke email sending function.

Then an email will be sent to the verified email address/es and you will get the response.


PS - You can move out this email sending function from the Amazon SES Sandbox by referring to this documentation.








No comments:

Post a Comment

How to send Slack notification using a Python script?

 In this article,  I am focussing on sending Slack notifications periodically based on the records in the database. Suppose we have to monit...