Skip to content

Instantly share code, notes, and snippets.

@blackspike
Last active July 15, 2023 13:55
Show Gist options
  • Save blackspike/1028400d33e25810a7fbd6c08c17d919 to your computer and use it in GitHub Desktop.
Save blackspike/1028400d33e25810a7fbd6c08c17d919 to your computer and use it in GitHub Desktop.
import formData from 'form-data'
import Mailgun from 'mailgun.js'
const DOMAIN = 'mg.example.com'
const USERNAME = 'api'
const mailgun = new Mailgun(formData)
const client = mailgun.client({ username: USERNAME, key: process.env.MAILGUN_API_KEY, url: 'https://api.eu.mailgun.net' })
exports.handler = async function (event, context) {
try {
// Test that is POST
if (event.httpMethod !== 'POST') {
return { statusCode: 405, body: 'Method Not Allowed', headers: { Allow: 'POST' } }
}
// Get sent json
const { html, toAddress } = JSON.parse(event.body)
const messageData = {
from: 'example bot <info@example.com>',
to: toAddress || 'your@email.com',
subject: `example test ${Date.now()}`,
text: 'Testing the newsletter',
html
}
const messagSentStatus = await client.messages
.create(DOMAIN, messageData)
.catch((err) => console.error(err))
return {
statusCode: 200,
body: JSON.stringify({ messagSentStatus }),
}
} catch (error) {
console.error(error)
return {
statusCode: 500,
body: JSON.stringify({ error }),
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment