Skip to content

Instantly share code, notes, and snippets.

@flatlinediver
Last active March 10, 2021 13:37
Show Gist options
  • Save flatlinediver/0bdca4c2ae09d34d351d45230d3b2489 to your computer and use it in GitHub Desktop.
Save flatlinediver/0bdca4c2ae09d34d351d45230d3b2489 to your computer and use it in GitHub Desktop.
Form handler using Mailgun and Netlify Functions
const { MAILGUN_API_KEY: apiKey, DOMAIN: domain, RECEIVER_MAIL: receiver_mail } = process.env
const mailgun = require('mailgun-js')({ apiKey, domain })
exports.handler = function(event, context, callback) {
if(event.httpMethod!='POST' || !event.body){
return callback(new Error('An error occurred!'))
}
const data = JSON.parse(event.body)
if(data.antibot.length>0){
return callback(new Error('Forbidden access'))
}
let messageData = {
from: data.email,
to: receiver_mail,
subject: `Message received from ${data.name}`,
text: `${data.message}`
}
mailgun.messages().send(messageData, function (error) {
if (error) {
return callback(error);
} else {
return callback(null, {
statusCode: 200,
body: 'success'
});
}
})
}
@smhmd
Copy link

smhmd commented Dec 8, 2019

const apiKey = process.env.MAILGUN_API_KEY
const domain = process.env.DOMAIN
const receiver_mail = process.env.RECEIVER_MAIL

can be written as such:

const { MAILGUN_API_KEY: apiKey, DOMAIN: domain, RECEIVER_MAIL: receiver_mail } = process.env

@flatlinediver
Copy link
Author

const apiKey = process.env.MAILGUN_API_KEY
const domain = process.env.DOMAIN
const receiver_mail = process.env.RECEIVER_MAIL

can be written as such:

const { MAILGUN_API_KEY: apiKey, DOMAIN: domain, RECEIVER_MAIL: receiver_mail } = process.env

indeed!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment