Skip to content

Instantly share code, notes, and snippets.

@lgs
Forked from codediodeio/index.js
Created January 16, 2018 13:12
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 lgs/e20ce17478c75b51270eb7412e645b6c to your computer and use it in GitHub Desktop.
Save lgs/e20ce17478c75b51270eb7412e645b6c to your computer and use it in GitHub Desktop.
Transactional Email Firebase Cloud Function with Sendgrid
var functions = require('firebase-functions');
const sendgrid = require('sendgrid')
const client = sendgrid("YOUR_SG_API_KEY")
function parseBody(body) {
var helper = sendgrid.mail;
var fromEmail = new helper.Email(body.from);
var toEmail = new helper.Email(body.to);
var subject = body.subject;
var content = new helper.Content('text/html', body.content);
var mail = new helper.Mail(fromEmail, subject, toEmail, content);
return mail.toJSON();
}
exports.httpEmail = functions.https.onRequest((req, res) => {
return Promise.resolve()
.then(() => {
if (req.method !== 'POST') {
const error = new Error('Only POST requests are accepted');
error.code = 405;
throw error;
}
const request = client.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: parseBody(req.body)
});
return client.API(request)
})
.then((response) => {
if (response.body) {
res.send(response.body);
} else {
res.end();
}
})
.catch((err) => {
console.error(err);
return Promise.reject(err);
});
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment