Contact Form and Send as Email with AWS SES, Netlify and Gatsby
Faith Morante

Faith Morante @idiglove

About: Senior Software Engineer

Location:
Vancouver, Canada
Joined:
Nov 12, 2019

Contact Form and Send as Email with AWS SES, Netlify and Gatsby

Publish Date: Feb 25 '20
16 6

This tutorial assumes you have Netlify, Gatsby and AWS SES set up. SES stands for Simple Email Service.

In the page you want to create a contact form, code your UI components like so:

import React, { useState } from 'react'
import { Button, Form, Input } from 'reactstrap'
import axios from 'axios'

export default function Index() {
    const [name, setName] = useState('')
    const [email, setEmail] = useState('')
    const [message, setMessage] = useState('')

    const send = (e) => {
        e.preventDefault()

        axios.post('/.netlify/functions/ses-send-email', {
            name,
            email,
            message
        }).then((res) => {
            console.log(res)
        })
    }

    return (
        <div>
                <Form onSubmit={(e) => send(e)}>
                    Name
                    <Input type="text" required onChange={(e) => setName(e.target.value)} />
                    Email
                    <Input type="email" required onChange={(e) => setEmail(e.target.value)} />
                    Message
                    <Input type="textarea" required onChange={(e) => setMessage(e.target.value)}/>
                    <Button>Send Message</Button>
                </Form>
        </div>
    )
}
Enter fullscreen mode Exit fullscreen mode

Use axios for calling your Netlify function.

In your root dir, create a file named netlify.toml with these inside:

[build]
    functions = "./functions"
Enter fullscreen mode Exit fullscreen mode

Now create a folder and file accordingly
New file

Your sending email function should look like this:

exports.handler = async event => {
  const AWS = require("aws-sdk")

  let requestParams = JSON.parse(event.body)
  let name = requestParams.name
  let email = requestParams.email
  let message = requestParams.message

    AWS.config.update({
        accessKeyId: 'your-aws-access-key-here',
        secretAccessKey: 'your-secret-access-key-here',
        region: 'aws-region-here'
    })

    const ses = new AWS.SES({ apiVersion: "2010-12-01" })
    const params = {
      Destination: {
        ToAddresses: [email] // Email address/addresses that you want to send your email
      },
    //   ConfigurationSetName: <<ConfigurationSetName>>,
      Message: {
        Body: {
          Html: {
            // HTML Format of the email
            Charset: "UTF-8",
            Data:
              `<html>
                  <body>
                    From: ${name}
                    <br />
                    Message: ${message}
                  </body>
              </html>`
          },
          Text: {
            Charset: "UTF-8",
            Data: ""
          }
        },
        Subject: {
          Charset: "UTF-8",
          Data: "From Contact Form"
        }
      },
      Source: email
    }

    return ses.sendEmail(params).promise().then(data => {
        console.log("email submitted to SES", data);
        return {
          statusCode: 200,
          body: `Message sent`,
        }
      })
      .catch(error => {
        console.log(error);
        return {
          statusCode: 500,
          body: `Message unsuccesfully sent, error: ${error}`,
        }
    })
}
Enter fullscreen mode Exit fullscreen mode

And there you go, publish to Netlify or use netlify dev to replicate sending emails on your local machine.

Comments 6 total

  • diek
    diekFeb 26, 2020

    Thank you! I have this task in my to-do right now, sending an email from a lambda :)

    • Faith Morante
      Faith MoranteFeb 26, 2020

      No problem! I knew this is a common task problem. Shoot me a message if you get any blockers, I'll be glad to help :)

      • diek
        diekFeb 26, 2020

        Hi. I'm trying now, it says to me that the email address is not verified. I have a domain with aws and it has been added correctly and verified.
        I'm confused with the rule that origin and destination must be verified, so, how can i send an email, for example, to a destination that is inputed by an user in my app?
        Thank you.

        • Faith Morante
          Faith MoranteFeb 26, 2020

          Hi, yea that happens because you are still in sandbox mode.

          • diek
            diekFeb 27, 2020

            Thank you, i didn't notice that. Case open :)

  • ashleynexvelsolutions
    ashleynexvelsolutionsJun 11, 2020

    You are a lifesaver! Thank you.

Add comment