Skip to content

Instantly share code, notes, and snippets.

@benjick
Created July 7, 2017 13:43
Show Gist options
  • Save benjick/3dda241a2206019382af7bfed1756a1d to your computer and use it in GitHub Desktop.
Save benjick/3dda241a2206019382af7bfed1756a1d to your computer and use it in GitHub Desktop.
const { send, text } = require('micro')
const post = require('micro-post')
const redirect = require('micro-redirect')
const qs = require('qs');
const mailgun = require('mailgun.js');
const fetch = require('node-fetch');
const cheerio = require('cheerio');
const domain = process.env.MAILGUN_DOMAIN;
const sender = process.env.MAILGUN_SENDER;
var mg = mailgun.client({
username: 'api',
key: process.env.MAILGUN_API_KEY,
public_key: process.env.MAILGUN_API_PUBLIC_KEY,
});
const validateRecipient = async (to, origin) => {
try {
if (!to || to === '') {
return false;
}
const result = await fetch(origin);
const html = await result.text();
const $ = cheerio.load(html);
const meta = $('meta[name="emails" i]').first();
const emails = meta[0].attribs.content.split(',').map(email => email.trim());
return emails.includes(to);
} catch (e) {
return false;
}
}
const app = async (req, res) => {
const { referer, origin } = req.headers;
if (!referer.includes(origin)) {
return send(res, 403, 'Bye')
}
const urlencoded = await text(req);
const js = qs.parse(urlencoded);
console.log('js', js);
const validRecipient = await validateRecipient(js.to, origin);
if (!validRecipient) {
return send(res, 400, 'Invalid recipient');
}
const validate = await mg.validate.get(js.from);
console.log('validate', validate);
if (!validate.is_valid) {
return send(res, 400, 'Invalid sender');
}
const msg = await mg.messages.create(domain, {
from: "A Website Visitor <" + sender + ">",
to: [js.to],
subject: "Hello",
text: "Testing some Mailgun awesomness!",
html: "<h1>Testing some Mailgun awesomness!</h1>"
})
console.log('msg', msg);
if (referer) {
const statusCode = 302;
return redirect(res, statusCode, referer);
}
return send(res, 200, `It's a POST request!`);
}
module.exports = post(app);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment