Sending Emails with Firebase

Firebase is a Google-owned web and mobile application development platform that allows you to create high-quality apps and take your business to the next level. You can also use the platform to send emails and enhance the capabilities of your apps.

In this article, we’re going to talk about how to send emails with Firebase and Nodemailer and how to test them with Mailtrap.

What you’ll need

What we’ll cover

  • Setting up Firebase
  • Setting up Mailtrap
  • Setting up Nodemailer 
  • Creating a Nodemailer transporter
  • Creating a Firebase function
  • Building the email message
  • Deploying to Firebase

Are you ready?

Let’s get going…

1. Setting up Firebase

Step 1.1: Create a Firebase project

Go to your instance of the Firebase UI and create a new project.

Step 1.2: Install Firebase CLI

The Firebase CLI is a versatile utility that provides you with an easy way to manage, view, and deploy code and assets to your Firebase project. 

You can install the utility on your development environment using a method that matches your preferences and use cases. Regardless of how you install it, you’ll still get the same functionalities.

For this tutorial, we’ll use the following command in our Windows Command Prompt to install the CLI globally:

npm install -g firebase-tools

Note that you’ll need to have Node.js installed on your system before running the above command. 

After installing it, you can create a new directory that will contain the code for this Firebase project.

Then, go to the directory and run the following command to sign in to your Firebase account:

firebase login

Then, you’ll need to follow the ensuing prompts so that you can be authenticated into the Firebase platform. This way, you’ll be granted the right to access your Firebase projects locally, as your local machine will be connected to Firebase.

Inspect Your Emails

Step 1.3: Initialize Firebase SDK for Cloud Functions

Cloud Functions allow you to access Firebase events directly in your application. This way, you can easily integrate with the Firebase platform and accomplish a wide range of tasks.

Initializing Firebase SDK for Cloud Functions will allow you to create an empty project that contains some dependencies you can use to build the rest of your application. 

After logging in successfully, you can initialize a Firebase project in your local directory by following these steps:

  • Run the firebase init functions command
  • Follow the ensuing prompts to associate the project on your local machine with an existing Firebase project
  • The command gives you two language options for writing Cloud Functions: TypeScript and JavaScript. For this tutorial, choose JavaScript. 
  • If you want to use ESLint for catching bugs and enforcing style, you can accept that option. For this tutorial, just decline it. 
  • If you want to install dependencies with npm, you can accept that option. For this tutorial, just accept it.

After the installation is complete, the structure of your new directory will look something like this: 

firebaseproject
 +- .firebaserc    # Hidden file you can use to switch between 
 |                 # projects easily
 |
 +- firebase.json  # Has the properties for your project
 |
 +- functions/     # Directory that has all your functions code
      |
      +- .eslintrc.json  # Optional file that has JavaScript 
                         # linting rules
      |
      +- package.json  # npm package file that has Cloud Functions code
      |
      +- index.js      # Main source file for your Cloud Functions code
      |
      +- node_modules/ # Directory that has dependencies 

For the rest of this tutorial, we’ll only make use of the functions directory. And, we’ll use the index.js file to put all our code.

Step 1.4: Install Firebase Admin SDK

The Admin SDK allows you to access Firebase from privileged environments and carry out various tasks, such as sending Firebase Cloud Messaging messages programmatically. 

To install it, on the Command Prompt, navigate to your functions folder and run the following command:

npm install firebase-admin --save

Then, go to your index.js file and import and initialize the Admin SDK.

Here is the code:

const admin = require("firebase-admin");
admin.initializeApp();

2. Setting up Mailtrap

Mailtrap is a free email testing tool to view and share emails in a development environment. You can use it to inspect and debug your emails and avoid spamming your real customers.

Setting it up is quick and easy. Just go to the signup page and register for a free account. 

Then, go to the SMTP settings tab in your inbox and copy the details for host, port, username, and password. We’ll use these details in the next section of this tutorial.

3. Setting up Nodemailer

Nodemailer is a simple module for sending email with Node.js applications. It comes with a wide range of features for allowing you to send emails fast, efficiently, and securely. 

To install Nodemailer, go to your functions directory and run the following command:

npm install nodemailer

Then, go to your index.js file and import it into your project.

Here is the code:

const nodemailer = require('nodemailer');

4. Creating a Nodemailer transporter

Next, create a reusable Nodemailer transporter object using your Mailtrap’s SMTP information. 

Here is the code:

let transporter = nodemailer.createTransport({
    host: "smtp.mailtrap.io",
    port: 2525,
    auth: {
      user: "71b312d8f1a983", // generated by Mailtrap
      pass: "e7a8f2287183dd" // generated by Mailtrap
    }
  });

In this case, transporter will be an object that can be used to send emails. 

Notice that’s the same code available in your Mailtrap inbox—if you select Nodemailer, under the Integrations section. 

5. Creating a Firebase Cloud Function

For this tutorial, we’ll create a Firebase HTTP Cloud Function, which will be triggered whenever its URL is executed in the browser.

Here is its syntax:

exports.emailSender = functions.https.onRequest((req, res) => {...});

As you can see on the code above, we named the function emailSender (you can call it any name). Then, we used the functions library with the https API and the onRequest event to register the function. 

The callback event handler function accepts two parameters: req and res. While the req object provides you with access to the properties of the initial HTTP request sent by the client, the res object allows you to send a response back to the client.

6. Building the email message

Next, let’s use the Nodemailer module to build the email message inside the emailSender function. 

Here is the code:

exports.emailSender = functions.https.onRequest((req, res) => {   
      
            const mailOptions = {
            from: 'from@example.com', //Adding sender's email
            to: req.query.dest, //Getting recipient's email by query string
            subject: 'Email Sent via Firebase', //Email subject
            html: '<b>Sending emails with Firebase is easy!</b>' //Email content in HTML
        };
  
        return transporter.sendMail(mailOptions, (err, info) => {
            if(err){
                return res.send(err.toString());
            }
            return res.send('Email sent successfully');
        });
       
});

As you can see in the code above, we started by defining mailOptions using the following properties: from, to, subject, and html. More options are available on the Nodemailer documentation.

Notice that we used req.query.dest to get the recipient’s email address by a query string.

Next, we applied the previously created transporter object to send the email message using the sendMail() method. We passed two parameters to the method: the data that defines the mail content and a callback function that is executed once the message is delivered or fails. 

While err is the error object returned when the message fails, the info object includes the results of the sent message.

In this case, our function will return the sent email message, if everything is successful, or an error message if the message is not delivered. 

Try Mailtrap For Free

7. Deploying to Firebase

Lastly, we’ll need to deploy the project’s function to Firebase. So, we’ll use the Firebase CLI again.

To do this, navigate to your functions directory and run the following command:

firebase deploy

Once the upload process is completed successfully, you’ll get a function URL that you can use to trigger the Cloud Function. 

The URL will look like this:

https://us-central1-<project-id>.cloudfunctions.net/emailSender

Notice that the Firebase project ID and the function’s name are in the URL. To execute the function, we just include the dest parameter in the URL and run it in a browser:

https://us-central1-<project-id>.cloudfunctions.net/emailSender?dest=test@example.com

That’s how to send the email!

Wrapping up

Here is the entire code for the index.js file:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const nodemailer = require('nodemailer');
 
//Initializing Firebase Admin SDK
admin.initializeApp();
 
//Creating Nodemailer transporter using your Mailtrap SMTP details
let transporter = nodemailer.createTransport({
    host: "smtp.mailtrap.io",
  port: 2525,  
  auth: {
    user: "71b312d8f1a983",
    pass: "e7a8f2287183dd"
  }
});
 
//Creating a Firebase Cloud Function
exports.emailSender = functions.https.onRequest((req, res) => {   
      
            //Defining mailOptions
            const mailOptions = {
            from: 'alfo.opidi85@gmail.com', //Adding sender's email
            to: req.query.dest, //Getting recipient's email by query string
            subject: 'Email Sent via Firebase', //Email subject
            html: '<b>Sending emails with Firebase is easy!</b>' //Email content in HTML
        };
  
        //Returning result
        return transporter.sendMail(mailOptions, (err, info) => {
            if(err){
                return res.send(err.toString());
            }
            return res.send('Email sent succesfully');
        });
       
});

Conclusion

As we’ve illustrated in this tutorial, sending emails with Firebase, Nodemailer and Mailtrap is simple and straightforward.

Remember that you can always check the documentation of any of the tools in case you experience implementation issues or you want to integrate something more exciting.

Also, Mailtrap offers you a useful way to test your emails in a pre-production environment. This way, you can debug your email samples before distributing them to real users. 

Register for a free account today!

If you find this article useful, please share it with your friends. We (and them) will really appreciate it.

Happy sending emails!