DEV Community

Lorna Watson
Lorna Watson

Posted on • Updated on

Using Node.js and Firebase Cloud Functions to send an email

I've longed to develop an email service for quite a while now, I developed one at work previously but I know that I can do better now. I was initially going to go down the root of using .NET Core 3.1, Swagger and then deploy using Azure Web App Services - but this isn't free. I wanted something new to play with and it being free doesn't hurt.

Email Service

I've been using Firebase Hosting for a few months and came across another one of their products called Cloud Functions. It sounded pretty cool. I have no experience with Node.js and have wanted to play around with it for my personal development. I wanted to use SMTP for my emails and after some brief research Nodemailer kept popping up.

The purpose of the project is to (at minimum so far) send emails. That's it. I have a contact form on my website and thought a good start would be to send me an email when someone has submitted the form with basic details being name, email and message.

Setup

Create a new folder for your project on your workspace and then cd into it.

Firebase

This blog post presumes you already have a Firebase project setup on the console and installed the CLI.

firebase init
Enter fullscreen mode Exit fullscreen mode

Select the functions option and then associate it with your existing Firebase project.

Alt Text
Alt Text

Packages

Go into your newly created functions folder and install the following packages.

cd email-service/functions
npm i firebase-admin
npm i firebase-functions
npm i nodemailer
npm i cors
Enter fullscreen mode Exit fullscreen mode

SMTP

I created a file within the functions folder called config.js where sensitive data such as username and passwords are stored. This file is then ignored in the repo and looks like the following:

Alt Text

Index.js

This file was created when the firebase-functions package as added.
Alt Text

Send email

For both local and live I've used postman to check the responses.

Local

firebase serve
Enter fullscreen mode Exit fullscreen mode

URL format: http://localhost:5001/<functionName>?parameter1=value1

Live

firebase deploy --only functions
Enter fullscreen mode Exit fullscreen mode

or

firebase deploy
Enter fullscreen mode Exit fullscreen mode

URL format: https://us-central1-<projectId>.cloudfunctions.net/<functionName>?parameter1=value1

Summary

I've really enjoyed having a play around with this project, more specifically Node.js. I am now able to send out an email with minimal code and setup! I'm going to look next at calling the function from my Angular 9 web app and more into error handling. Then I want to write another function to send the user who filled out the contact form an email of confirmation. And then who knows...! 😎

Thank you for reading, hope you enjoyed! 😀

Debugging in Node.js

Oldest comments (0)