Angular 4 Transactional Email with Google Firebase Cloud Functions
Fireship
https://angularfirebase.com/lessons/angular4-transactional-email-with-cloud-functions-and-sendgrid/
In this episode, I am going to show you how send transactional email in Angular as a background task in cloud. To facilitate this, the emails will be send with Google Cloud Functions for Firebase and the email service Sendgrid. You can use any email provider you want such as mailgun or postmark or even Gmail, but I will chose Sendgrid for this tutorial because they have a solid helper library and a detailed NodeJS example in their documentation. They also offer a free trail with no credit card requirements, so get your API key to follow along with this lesson.
What is a Cloud Function?
Google Cloud Functions is a serverless architecture that allows you to run isolated code in a NodeJS runtime - as opposed to deploying your own server. It is Google's answer to AWS Lambda and has only been available to the public since 2017. It's an awesome tool for Firebase developers because it allows you to run code in the background that would otherwise slow down an Angular app, and email is definitely a task that should be delegated to its own background task or micro service.
We can trigger cloud functions in many different ways, but this lesson will demonstrate the use of cloud functions via HTTP. When the function is deployed, Google Cloud Platform will give us a URL endpoint that we can hit with query params that tell SendGrid how to deliver the email. The process is no different than working with any other RESTful API.
It's also useful to know that you can trigger cloud functions on database writes, storage uploads, authentication events, and even analytic events, all of which are common use cases for transactional email. Some examples include sending a welcome email after a new user signs up or when they've reached the max capacity on file uploads. I plan on covering these scenarios in future videos.
First, I am assuming you have an Angular app started with the firebase-tools installed.
Start by run the firebase init command and select functions.
This will create a functions directory and give us an index.js file, which is were the functions are defined. The functions directory is its own isolated Node environment, completely separate from your angular app - its logic has no direct connection to angular. That's great because it keeps your frontend app lightweight and delegates CPU or Memory intensive operations to the cloud.
First we need to install the sendgrid package, so we cd into the functions directory then run NPM install.
cd functions npm install sendgrid
First, I import the send grid package and pass it my API key.
Next, I define a parseBody helper to convert the email params into JSON with SendGrid's mail helper. This is a pre ... https://www.youtube.com/watch?v=wCtNjP9gcqk
25322928 Bytes