Part 3: Lambda function for AWS SES using API Gateway

Alright, in the previous part, we have created a static website. Now it is the time to add functionality to it. Lets begin creating an AWS Lambda function to send an email using AWS Simple Email Service (SES). After creating the lambda function, we will use API Gateway to call this function. See introduction of this article to understand these AWS services.

Lambda function to send an email

  1. First of all, sign in to AWS account and navigate to console page.
  2. Then move to Lambda page. Use the search button on the top to find it easily.
  3. Important: Do not forget to move into the AWS region which is nearer to the intended user base.
  4. Now, in Lambda home page click on Create Function.
  5. In the form, fill in all the required details.

    Lambda Function
    Create Lambda Function
  6. Now you will have an empty lambda function. You can find it in your lambda home page in the AWS region that it is created.
  7. So in the lambda function, click lambda function (it will be with the function name, in our case, it is static-website-send-email) under configuration in the Designer,
  8. If you scroll down to the bottom, you will see the coding area under Function code, copy the following text inside that coding area, replacing the existing content. Don’t forget to save it by clicking the Save button. Note: Change youremail@email-provider.com (in 2 locations) in the following code with your email account. If your account is in sandbox mode, then you need to verify this email address.
    var aws = require('aws-sdk');
    var ses = new aws.SES({
       region: 'us-east-1'
    });
    
    exports.handler = function(event, context, callback) {
       var body = event.body;
       var subject = "Message from AWS SES";
       var from = event.from;
       var fromEmail = event.fromEmail;
     
       if ((!body || body.trim() == "") || (!from || from.trim() == "") || (!fromEmail ||fromEmail.trim() == "")) {
          var error = new Error("Data improper.");
          error.code = "DataImproper";
          error.status = 401;
          callback(error);
          return;
       }
       body += " \n SENDER: " + from;
       body += " \n SENDER Email: " + fromEmail;
    
       var eParams = {
          Destination: {
             ToAddresses: ["receiver@gmail.com"]
          },
          Message: {
             Body: {
                Text: {
                   Data: body
                }
             },
             Subject: {
                Data: subject
             }
          },
          Source: "sender@gmail.com"
       };
       console.log('===SENDING EMAIL===');
       var email = ses.sendEmail(eParams, function(err, data){
          if(err) {
             console.log(err);
             var error = new Error("Failed to send e-mail.");
             error.code = "InternalError";
             error.status = 500;
             callback(error);
             return;
          } else {
             console.log("===EMAIL SENT===");
             console.log(data);
             console.log("EMAIL CODE END");
             console.log('EMAIL: ', email);
             context.succeed(event);
          }
       });
    };
  9. The above code uses AWS SDK connects to SES in us-east-1 (N. Virginia). The handler expects its event to contain the body, from and fromEmail. If all parameters are valid, then an email will be sent using the given parameters. There is also a callback to send status to the lambda function caller.

IAM role access rights

  1. Until now we have created Lambda function but it is not given any access rights to access SES features. Lets do that now.
  2. While creating our lambda function, we have used a new role. In our case it is static-website-send-email-role.
  3. So we have to attach a policy to our role to add required access rights.
  4. Lets go back AWS Console home page and navigate to IAM (Identity Access Management) console home page. Click on Roles menu item.
  5. You can see static-website-send-email-role role. Click on it.
  6. Under Permissions tab, click Attach Policy.
  7. Search for AmazonSESFullAccess policy. This is an AWS managed policy. Attach this policy to your role.

    AWS Role png
    Add IAM role for SES

Verify E-mail account in SES (Only for Sandbox AWS SES Account)

  1. Now go back to AWS console page and navigate to SES home page. Note: Since we have created SES in N.Virginia, we have to change the region to N.Virginia.
  2. Click on Email Addresses under Identity Management.
  3. Inside this page you will see Verify Email Address. Click on it. Enter your email address and click Verify This Email Address.
  4. If you see the e-mail addresses list, you can see the new account status as pending verification.
  5. Check your e-mail for AWS email and click on the given link in the e-mail. Now refresh the AWS SES Email Addresses page and you can see that it is verified.

Test Lambda Function

  1. Since we have created all the required code and permissions. It should work now. Lets test it.
  2. Go back to Lambda function home page and click on our lambda function.
  3. Click on the Test button on top right. It will open a popup.
  4. Here we will add a new test case with the following parameters.
    {
     "body": "This is email body.",
     "from": "sender",
     "fromEmail": "sender@sender.com"
    }
  5. Give the test case a name and click Create.
  6. So we created a test case. Lets select that test case in the dropdown adjacent to Test button and then hit Test button. If everything is properly done, you should see result as succeeded. And you should receive an email.
  7. Hurray! You have created a lambda function that sends an email.

Lets do the final part, integrating with UI in the final tutorial. Do leave your feedback. 🙂

Previous: Create AWS S3 Static Website

Next: Integrate with API Gateway 

 

Please follow and like us:
error

Leave a Reply

Your email address will not be published. Required fields are marked *