Skip to content

Instantly share code, notes, and snippets.

@damieng
Last active November 14, 2023 15:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save damieng/4ad28f47a8f063804a98448c5d8777d3 to your computer and use it in GitHub Desktop.
Save damieng/4ad28f47a8f063804a98448c5d8777d3 to your computer and use it in GitHub Desktop.
AWS Lambda mail sender via Brevo with Recaptcha
/* 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