Creating a Serverless Contact Form with AWS Lambda and SES

Creating a Serverless Contact Form with AWS Lambda and SES

Introduction

A contact form is an essential component of any website, allowing visitors to send messages, ask questions, or provide feedback. In this tutorial, we will create a serverless contact form using AWS Lambda and Simple Email Service (SES) to send emails without the need for a dedicated server.

Prerequisites

Before we begin, make sure you have the following:

  1. An AWS account.
  2. The AWS CLI installed and configured.
  3. Node.js installed.
  4. A website or web application where you want to add the contact form.

Step 1: Set up AWS Lambda and API Gateway

First, we will create a Lambda function to handle form submissions and an API Gateway endpoint to expose the function.

  1. Sign in to your AWS Management Console and navigate to the Lambda service.
  2. Click «Create function» and select «Author from scratch.»
  3. Give your function a name, like «contactFormHandler,» and choose the «Node.js» runtime.
  4. In the «Function code» section, select «Upload a .zip file» and upload the .zip file containing your Lambda function (we will write the code for this later).
  5. In the «Execution role» section, create a new role with the «AWSLambdaBasicExecutionRole» permission.
  6. Click «Create function.»

Next, set up the API Gateway:

  1. Navigate to the API Gateway service in the AWS Management Console.
  2. Click «Create API» and choose «HTTP API.»
  3. In the «Integration» section, select «Lambda» and choose the Lambda function you created earlier.
  4. Set the «API endpoint» to «POST» and enter a resource path, like "/contact."
  5. Click «Create API.»

Take note of the API endpoint URL, as you will need it later when configuring your contact form.

Step 2: Write the Lambda Function

Now we will write the code for the Lambda function to handle form submissions and send emails using SES.

1. Create a new directory for your Lambda function and navigate to it in your terminal.

2. Run `npm init -y` to create a package.json file.

3. Install the AWS SDK by running `npm install aws-sdk`.

4. Create an `index.js` file in the directory and add the following code:

  1. const AWS = require('aws-sdk');
  2. const ses = new AWS.SES({ region: 'us-east-1' });
  3.  
  4. exports.handler = async (event) => {
  5. const { name, email, message } = JSON.parse(event.body);
  6.  
  7. const params = {
  8. Destination: {
  9. ToAddresses: ['your@email.com'],
  10. },
  11. Message: {
  12. Body: {
  13. Text: {
  14. Charset: 'UTF-8',
  15. Data: `Name: ${name}\nEmail: ${email}\n\nMessage:\n${message}`,
  16. },
  17. },
  18. Subject: {
  19. Charset: 'UTF-8',
  20. Data: 'New contact form submission',
  21. },
  22. },
  23. Source: 'no-reply@yourdomain.com',
  24. };
  25.  
  26. try {
  27. await ses.sendEmail(params).promise();
  28. return {
  29. statusCode: 200,
  30. body: JSON.stringify({ message: 'Email sent successfully' }),
  31. };
  32. } catch (error) {
  33. console.error(error);
  34. return {
  35. statusCode: 500,
  36. body: JSON.stringify({
  37. message: 'An error occurred while sending the email',
  38. }),
  39. };
  40. }
  41. };

Replace 'your@email.com' with the email address you want to receive the contact form submissions, and 'no-reply@yourdomain.com' with a «from» address for the email.

5. Zip the contents of the directory, including `index.js` and `node_modules`, into a .zip file.

6. Go back to the Lambda function in the AWS Management Console, and upload the .zip file you created in the «Function code» section.

Step 3: Integrate the Contact Form with Your Website

Now that the Lambda function and API Gateway are set up, you can integrate the contact form with your website.

1. Add the following HTML code to your website where you want the contact form to appear:

  1. <form id="contact-form">
  2. <label for="name">Name:</label>
  3. <input type="text" id="name" name="name" required />
  4. <br />
  5. <label for="email">Email:</label>
  6. <input type="email" id="email" name="email" required />
  7. <br />
  8. <label for="message">Message:</label>
  9. <textarea id="message" name="message" required></textarea>
  10. <br />
  11. <button type="submit">Submit</button>
  12. </form

2. Add the following JavaScript code to handle the form submission:

  1. const contactForm = document.getElementById('contact-form');
  2. const apiEndpoint = 'https://your-api-gateway-url/contact';
  3.  
  4. contactForm.addEventListener('submit', async (event) => {
  5. event.preventDefault();
  6.  
  7. const formData = new FormData(contactForm);
  8. const data = {
  9. name: formData.get('name'),
  10. email: formData.get('email'),
  11. message: formData.get('message'),
  12. };
  13.  
  14. try {
  15. const response = await fetch(apiEndpoint, {
  16. method: 'POST',
  17. headers: { 'Content-Type': 'application/json' },
  18. body: JSON.stringify(data),
  19. });
  20.  
  21. if (response.ok) {
  22. alert('Message sent successfully!');
  23. contactForm.reset();
  24. } else {
  25. throw new Error('An error occurred while sending the message');
  26. }
  27. } catch (error) {
  28. alert(error.message);
  29. }
  30. });

Replace 'https://your-api-gateway-url/contact' with the API endpoint URL you noted down earlier.
That's it! Your serverless contact form is now integrated with your website, and you can receive messages from your visitors directly in your inbox.

We use cookies to improve your browsing experience. By continuing to use this website, you consent to our use of cookies. Learn More