Last active
November 14, 2023 15:47
-
-
Save damieng/4ad28f47a8f063804a98448c5d8777d3 to your computer and use it in GitHub Desktop.
AWS Lambda mail sender via Brevo with Recaptcha
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* global fetch */ | |
export const handler = async (event, context) => { | |
// Validate parameters | |
const { firstName, lastName, email, message, token } = JSON.parse(event.body) | |
if (!firstName || !lastName || !email || !message || !token) { | |
return { statusCode: 400, body: JSON.stringify({ statusMessage: "Missing required fields" })} | |
} | |
// Validate captcha | |
const verifyResponse = await fetch("https://www.google.com/recaptcha/api/siteverify", { | |
method: "POST", | |
headers: { | |
"content-type": "application/x-www-form-urlencoded", | |
}, | |
body: `secret=${process.env.RECAPTCHA_SECRET}&response=${token}`, | |
}) | |
const verifyResponseBody = await verifyResponse.json() | |
if (!verifyResponse.ok) { | |
return "Unable to validate captcha at this time." | |
} | |
if (verifyResponseBody.success !== true) { | |
return "Invalid captcha response." | |
} | |
// Send email | |
const emailSendResponse = await fetch("https://api.brevo.com/v3/smtp/email", { | |
method: "POST", | |
headers: { | |
accept: "application/json", | |
"api-key": process.env.BREVO_KEY, | |
"content-type": "application/json", | |
}, | |
body: JSON.stringify({ | |
to: [ | |
{ | |
email: process.env.EMAIL_TO_ADDRESS, | |
name: process.env.EMAIL_TO_NAME | |
} | |
], | |
sender: { | |
email: email, | |
name: `${firstName} ${lastName}`, | |
}, | |
subject: process.env.EMAIL_SUBJECT, | |
textContent: message, | |
}), | |
}) | |
if (!emailSendResponse.ok) { | |
return "Message could not be sent at this time." | |
} | |
return "Message sent!" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment