[PYTHON] Add mail form to serverless web application ~ Backend version ~

Add mail form to serverless web application ~ Backend version ~

Introduction

Add a mail form to the web application created in Creating a serverless web application using AWS. It is composed of two parts, and I think it is better to look at the front end first. Additional implementation of mail form to serverless web application-Front end-

Back end

Since the base web application uses AppSync, AppSync is also the means to call Lambda to send an email from the front end.

Creating a Lambda function

When creating a new Lambda function, add "Amazon SNS publishing policy" in the selection and creation of execution roles. Screenshot 2020-03-29 at 08.53.11.png

Added IF for Lambda calls to AppSync

Add an IF that calls Lambda to the AppSync you are already using. The following article I wrote the other day will be useful at once. Call Lambda with AppSync

Add the above Lambda to your data source, add an IF like the one below to your schema, and attach it to your resolver.

input ProcessSendMailInput {
	name: String!
	email: String!
	message: String!
}
type ProcessSendMailResult @aws_cognito_user_pools {
	statusCode: Int!
	body: String
}
type Mutation {
	processSendMail(input: ProcessSendMailInput!): ProcessSendMailResult
		@aws_cognito_user_pools
 :

AWS SNS settings

We will set up an SNS to notify you by email of the contents sent via AppSync.

Creating a topic

At the very least, it seems good to enter only the name. Screenshot 2020-03-29 at 10.05.32.png

Create a subscription

Create a subscription for the topic you created. The protocol is "email" and the endpoint is "destination email address". ink.png When you create a subscription, a confirmation email will be sent to the email address you specified for your endpoint. ink (1).png Select the Confirm subscription link in the body of the email to complete the subscription verification and change the status from Pending Confirmation to Confirmed.

You can send a test email from "Issue Message" at the top right of the topic screen, so it's a good idea to check it. Also, the ARN in the topic details will be used later in the program.

Implementation of Lambda function

This is a Python code that notifies you on SNS of the content sent via AppSync.

lambda_function.py


import boto3
import json
import logging

logger = logging.getLogger()
logger.setLevel(logging.INFO)

sns = boto3.client("sns")
TOPIC_ARN = "arn:aws:sns:ap-northeast-1:888888888888:sample_sns_topic"
REQUEST_BODY_TEMPLATE = """
name : {0}
email : {1}
message : 
{2}
"""

def lambda_handler(event, context):
    try:
        logger.info(event)
        name = event["input"]["name"]
        email = event["input"]["email"]
        message = event["input"]["message"]
        
        requestBody = REQUEST_BODY_TEMPLATE.format(name, email, message)
        logger.info(requestBody)
        
        request = {
            "TopicArn": TOPIC_ARN,
            "Message": requestBody,
            "Subject": "mail from form by {0}".format(name)
        }
        response = sns.publish(**request)

        return {
            "statusCode": 200,
            "body": json.dumps("Email sent successfully.")
        }

    except Exception as e:
        logger.exception(e)
        return {
            "statusCode": 500,
            "body": json.dumps(e)
        }

Call AppSync from the front end

It is described in Front end bias.

Afterword

The email form was easier than I expected. With this alone, the man-hours are about 1.0H. However, I think that a separate mechanism is required to prevent tampering.

You want to use Google's reCAPTCHA service. I will write it again when I introduce it next time.

Recommended Posts

Add mail form to serverless web application ~ Backend version ~
Dynamically add fields to Form objects in Django
Steps to develop a web application in Python