Simple email forwarding with AWS Lambda and Serverless (and SES)

If forwarding emails (with some calculations in-between) is what you need, then AWS Lambda is the simplest solution for you.

Estimate reading 4 minutes

As the official documentation says:

AWS Lambda is a compute service that lets you run code without provisioning or managing servers. AWS Lambda executes your code only when needed and scales automatically, from a few requests per day to thousands per second.

Lambda executes the code (and its dependencies) stored in Functions; We can write a Function directly inside the AWS Lambda or we can use a distinct service to create Lambdas and upload Functions: this service is named Serverless and it does just what we want!

Enough talking, let’s dive into some code!

Setup the service

First of all, we want to run npm install serverless -g to install
Serverless, and then create our service:

serverless create --template aws-nodejs --path email_sender

Our Serverless project is ready and we just need to setup our AWS IAM credentials that we will store inside ~/.aws/credentials.

note: serverless-offline is a very useful plugin which allows you to make requests to localhost without having to deploy to Lambda every time you make a change. Run npm install serverless-offline -g to install the offline plugin

The handler.js file is where we will write our methods, the code that we want to execute. From the serverless.yml file we declare which method has to be executed when we call a certain function. So as you might have guessed, in the handler.js file our method will be named ‘send’: