Efficiently Storing Website Submissions using AWS Lambda and S3

Published: January 27, 2022

Are you looking for a lightweight solution to handle occasional website submissions without the need for a full-fledged database? If your goal is to securely store these submissions in an easily accessible format like Excel, you can achieve it using AWS Lambda and Amazon S3.

Create a Lambda function that simply writes website submissions to a TXT file on an S3 bucket like this:

import boto3
import botocore
from botocore.exceptions import ClientError
import os
import json
from datetime import datetime
 
 
BUCKET_NAME = 'some-bucket'
KEY = f'emailSubmissions.txt'
LOCAL_FILE = '/tmp/submission.txt'
s3 = boto3.resource('s3')
 
def remove_local_file(filePath):
     # As file at filePath is deleted now, so we should check if file exists or not not before deleting them
    if os.path.exists(filePath):
        os.remove(filePath)
    else:
        print("Can not delete the file as it doesn't exists")
 
def lambda_handler(event, context):
    name = event["name"]
    email = event["email"]
    message = event["message"]
    now = datetime.now().strftime("%d/%m/%Y %H:%M:%S")
    try:
        obj=s3.Bucket(BUCKET_NAME).download_file(KEY, LOCAL_FILE)
    except ClientError as e:
        if e.response['Error']['Code'] == "404":
            print("The object does not exist.")
            remove_local_file(LOCAL_FILE)
            return {
                'statusCode': 403,
                'body': json.dumps(f'Unsuccessful in adding Date:{now}, Name:{name}, email:{email}, message:{message} to {KEY}')
            }
        else:
            raise
    with open('/tmp/submission.txt', 'a') as fd:
        fd.write(f"{now}   {name}	{email}	{message}\n")
 
    s3.meta.client.upload_file(LOCAL_FILE, BUCKET_NAME, KEY)
 
    return {
    'statusCode': 200,
    'body': json.dumps(f'Succesfully added Date:{now}, Name:{name}, email:{email}, message:{message} to {KEY}')
    }
 

With this simple Lambda function, you can process website submissions with. As new data comes in, it will be securely stored in the designated S3 bucket, accessible for analysis or review in a TXT file.

Another alternatives for this use case is a free API such as Web3Forms. It allows you to receive your html contact form submissions directly in your email inbox using their contact form api service without any server or backend code. Also, it's free!