Send Mail Using Aws SES & Lambda Function
In this blog, we will be going to create a post API to send mail to the user using the following tools or technologies
- AWS SES
- AWS Lambda Function
- Node Js
I Assumed hear you have installed your node js and also set up node js in your local machine.
So now we discuss the use-case for this API and why we create this API
we are taking an example of the contact form of any website and we need to send the mail when the user fills out the contact form for any reason or receives any help from the website. shown in the below image
In this form Name, E-mail & Message these three fields are present now our task is we send this data to the receiver’s E-mail id, then our receiver fulfills the user requirement or replies to the user’s email.
We are using two things for Api :
1) AWS (Amazon Web Services)
2) Code Editor ( VS code)
First, we set up our AWS account if we don’t have an account on AWS if we already have an account that’s good.
Step 1) Sign in with Aws Account:
I am sharing the URL for sign in/sign up AWS account
URL : https://000369398001.signin.aws.amazon.com/console
This screen will be appeared now sign in with your credential Account Id and Password
Step 2) Set your region as per your requirement.
As shown in the above image the region is available on the right side of the console page here we are using the us-east-1 region for our function.
Now our AWS console setup is ready we move toward the coding part
Step 3) Create a new Project in VS code
You can use any code editor but now we are using Visual Studio(VS) code.
i) Create a file with any name we are creating a folder aws_Send_mail in the code editor.
ii) Right a command on cmd or your integrated terminal of vs code
npm init -yAfter entering this command
C:\Aws_Send_Mail>npm init -y
Wrote to C:\Aws_Send_Mail\package.json:{
"name": "aws_send_mail",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}C:\Aws_Send_Mail>
This result shows that we set our folder name: aws_send_mail and the rest of the code is automatically set for our project.
iii) install npm using the below command
npm iOur npm package is ready.
iv) Create a new file with the name sendMail.js
v) And we also need to install a few dev dependencies, so enter the command
npm i aws-sdk serverlessIn the above command, we install the aws software development kit and serverless in the lambda function.
vi) Create a serverless.yml file in the root file
service: email-service
provider:
name: aws
runtime: nodejs14.x
functions:
sendEmail:
handler: sendEmail.handlerIn the above code, we provide the service, provider, and our function name with the same name we create a function in our sendEmail.js file
Get Devendra patil’s stories in your inbox
Join Medium for free to get updates from this writer.
Now our sendEmail.js file like
const AWS = require('aws-sdk');AWS.config.update({ region: "us-east-1" });
// Create SES service object
const ses = new AWS.SES({ apiVersion: '2010-12-01' });exports.handler = async (event, context, callback) => { // Get the email and user name from the POST request body
const { email, username,message} = JSON.parse(event.body);
const sourceMail = 'abc@gmail.com'; // Create the email parameters
const params = {
Destination: {
ToAddresses:[sourceMail]
},
Message: {
Body: {
Text: {
Data: `User Name : ${username},\nEmail : ${email},\nMessage : ${message},\n`
}
},
Subject: { Data: `abc@gmail.com` },
},
Source: sourceMail
}; try {
// Send the email using SES
const result = await ses.sendEmail(params).promise();
console.log('Email sent successfully:', result);
// Return a success response
const response = {
statusCode: 200,
body: JSON.stringify({ message: 'Email sent successfully' })
};
callback(null, response);
} catch (error) {
console.error('Error sending email:', error);
// Return an error response
const response = {
statusCode: 500,
body: JSON.stringify({ message: 'Error sending email' })
};
callback(null, response);
}
};
Now we need to deploy this function on our AWS.
Using the below command enter in cmd
serverless deployNow we need to create post API and routes for our post Api on the AWS console
Step 4: Check on the lambda function on the AWS console :
Click on lambda on the console shown in the below images
After that check whether a lambda function with the same name we have given in our code is available there or not if the function is deployed successfully then our function with the same name is available there like shown in the below image
Hey….our lambda function is successfully deployed. and also show in our function list now we need to create an ApiGateway
Step 5: Create ApiGateway
For this click on ApiGateway below to the lambda function as shown in the above console image
now we need to click on Create Api button on the right-hand side of the console and then select our api 4 api type are there.
HTTP Api
WebSocket Api
Rest Api(private)
Rest Api(public)
For now, we are selecting HTTP api now click on the build button on the right-hand side of the console.
In the integration field select lambda to select our aws region and select lambda function name from dropDown and click on the next button.
Select our method we are creating post requests so we choose the POST method and our resource path is already there and click on next.=> next => next our ApiGateway is ready with POST request.
Now we need to find invoke URL and function path
Step 6: Find Invoke URL and function path :
To invoke the URL, we need to click on ApiGateway = >select our Api name =>SendEmail
We get our invoke URL in the red box now we find the function path so click on Routes shown in the blue color box in the above image. and we get the function path shown below the image in the red Box.
Now copy both invoke Url first and function path second and pest in Postman URL and choose post method
Boom……. we received a response now check your mail you also received a mail.
I hope you found this informative, a👏 is always appreciated, thanks!







