You have unlimited access as a PRO member
You are receiving a free preview of 3 lessons
Your free preview as expired - please upgrade to PRO
Contents
Recent Posts
- Object Oriented Programming With TypeScript
- Angular Elements Advanced Techniques
- TypeScript - the Basics
- The Real State of JavaScript 2018
- Cloud Scheduler for Firebase Functions
- Testing Firestore Security Rules With the Emulator
- How to Use Git and Github
- Infinite Virtual Scroll With the Angular CDK
- Build a Group Chat With Firestore
- Async Await Pro Tips
Firebase Cloud Function for Transactional Email With Sendgrid
Episode 10 written by Jeff DelaneyThis lesson has been updated for Angular 5, Firestore, and the new SendGrid v3 NodeJS packages. Get the latest and greatest Transactional Email Lesson.
An example of SendGrid integrated with Firebase cloud functions. This function can be triggered via http to send transactional email in a Firebase app.
This file contains hidden or 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
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); | |
}); | |
}) |