Created
August 26, 2021 14:07
-
-
Save joawan/d9a3dfc5b204162d538c1de1bd4b4add to your computer and use it in GitHub Desktop.
Lambda code to send email
This file contains 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
const { readFile } = require('fs').promises; | |
const mjml = require('mjml'); | |
const i18n = require('i18n'); | |
const htmlToText = require('html-to-text'); | |
const assert = require('assert'); | |
const mustache = require('mustache'); | |
const AWS = require('aws-sdk'); | |
i18n.configure({ | |
directory: `${process.cwd()}/locales`, | |
defaultLocale: 'en', | |
}); | |
exports.handler = async (event) => { | |
const promises = event.Records.map(async (record) => { | |
const body = JSON.parse(record.body); | |
const mail = await render(body); | |
return send(mail, body); | |
}); | |
return Promise.all(promises); | |
}; | |
const render = async (data) => { | |
assert.ok(/^[a-z0-9_-]+$/i.test(data.template)); | |
const buf = await readFile(`${process.cwd()}/templates/${data.template}.mjml`); | |
const content = buf.toString(); | |
const { html: mjmlToHtml, errors } = mjml(content, { | |
filePath: `${process.cwd()}/templates`, | |
minify: true, | |
}); | |
assert.ok(errors.length === 0, JSON.stringify(errors)); | |
const html = mustache.render(mjmlToHtml, { | |
...data, | |
t() { | |
return (phrase, fn) => fn( | |
i18n.__({ phrase, locale: data.locale }, data), | |
); | |
}, | |
}); | |
const subject = html.replace(/\n/g, '').match(/<title>(.+)<\/title>/).pop().trim(); | |
return { | |
html, | |
subject, | |
text: htmlToText.fromString(html, { ignoreImage: true }), | |
}; | |
}; | |
const send = async ({html, text, subject}, data) => { | |
const params = { | |
Destination: { | |
ToAddresses: [`${data.userName} <${data.userEmail}>`], | |
}, | |
Message: { | |
Body: { | |
Html: { Charset: 'UTF-8', Data: html }, | |
Text: { Charset: 'UTF-8', Data: text }, | |
}, | |
Subject: { Charset: 'UTF-8', Data: subject }, | |
}, | |
Source: `Schibsted <${process.env.SENDER_EMAIL}>`, | |
ConfigurationSetName: process.env.SES_CONFIG_SET, | |
Tags: [ | |
{ Name: 'template', Value: data.template }, | |
{ Name: 'locale', Value: data.locale }, | |
{ Name: 'userId', Value: data.userId }, | |
], | |
}; | |
return new AWS.SES({ apiVersion: '2010-12-01' }).sendEmail(params).promise(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment