Sending Emails Using Firebase Cloud Function

Cy Uket
7 min readJul 12, 2019

Before now I thought sending mails front-end was impossible without a server side scripting language, until I came across Firebase cloud function. This article is detailed to help you Send Emails with just HTML, CSS and JavaScript

Prerequisites

  • Basics knowledge of HTML, CSS and JavaScript.
  • Node installed: click here to Node it installed.
  • Firebase account — Click here to create Firebase account.
  • Text Editor (Virtual Code Studio)

Introduction

Firebase is a mobile and web app development platform that provides developers with a plethora of tools and services to help them develop high-quality apps, grow their user base, and earn more profit.

Firebase offer different services, including:

Authentication: Functions which authenticate users in your applications using different methods including, sign-in and sign-up with:

  • email and password,
  • social media,
  • Google account etc.

Hosting Services: you can Host your Web application Using Firbase. Visit Firebase Documentation

Real Time Database: Firebase offers a NO SQL database for your application.

Cloud Storage: Firebase also offers services for storage of files using the cloud storage.

Cloud Function: Firebase Also allows You to deploy Functions to the cloud and could be access either from an HTTPS Request or could be called by references it name anywhere around your application.

What We are Building

At the end of the article We will be building a simple web application that will send Mails to Emails through a contact form.

Setting up Firebase Tools

Install Firebase to your computer by opening your computer terminal (run as administrator if you are using Windows operating System) and running the command below:

npm install -g firebase-tools

or

yarn add firebase-tools

Now that we have installed firebase in our local mention, we can now go to our Firebase console and create an application for this purpose so we can use the cloud function

When installation is done, open your terminal and navigate into your desktop through the terminal by runing the command below:

cd Desktop

Next, We need to intialize a new Firebase app and call it `EmailWithFirebase` by runing the command below

firebase init EmailWithFirebase

After this We need to Install the mailgun package to our project with the following commands:

cd EmailWithFirebasecd functionsnpm install -save mailgun-js

Or

yarn add mailgun-js

Open the folder In your preferred text editor and open the index.js file inside functions folder

take out the commented code and replace with the code below:

exports.firebaseEmail = functions.https.onCall((request, response) => {let email = request.email;let name = request.name;let body = request.body;let subject = request.subjectvar api_key = 'YOUR API_KEY';var DOMAIN = 'YOUR DOMAIN';var mailgun = require('mailgun-js')({apiKey: api_key,domain: DOMAIN});var data = {from: `${name} <${email}>`,to: `Company <cyriluket12@gmail.com>`,subject: `Subject: ${subject}!`,text: `${body}`};mailgun.messages().send(data, function (error, body) {if (error) {console.log(error)}console.log(body);});});

You need to provide in the your mailgun api_key, to get you API_Key Create a Mailgun account here if you don’t have one or Login in here if you already.

When you are already logged, You can get you API_KEY by going to your account setting and clicking on security or follow this link

copy the Private API Key and replace it with YOUR API KEY

Next For the purpose of testing we will be using the domain provided for us by mailgun by clicking on Domain on the Nav bar and copy the domain name provided for you, replace it with YOUR DOMAIN

Disclaimers: Because the domain is for test email sent will go to spam of the receiver

Deploying

Before deploying Your index.js should be similar to this

const functions = require('firebase-functions');exports.firebaseEmail = functions.https.onCall((request, response) => {let email = request.email;let name = request.name;let body = request.body;let subject = request.subjectvar api_key = '';var DOMAIN = 'YOUR DOMAIN NAME';var mailgun = require('mailgun-js')({apiKey: api_key,domain: DOMAIN});var data = {from: `${name} <${email}>`,to: `Company <cyriluket12@gmail.com>`,subject: `Subject: ${subject}!`,text: `${body}`};mailgun.messages().send(data, function (error, body) {if (error) {console.log(error)}console.log(body);});});

After writing A function, you have to deploy to your firebase project, it becomes accessible and this can be achieve with the following steps

1 . go back to your terminal go back to the root folder if you are In the functions directory

cd ../

To deploy only the functions we we run the command below:

firebase deploy –functions

When this is done You can see your function in your project console click on functions to see the functions you just uploaded.

Setting up Front-end

Bootstrap will be used for the styling here. Following the following instructions

  1. In the root of the folder create an index.html file from your text editor
  2. Paste the code below inside index.html
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Sending Emails</title><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"></head><body><div class="container"><h1>Sending Emails With Firebase Cloud Functions</h1><form class="" id="form"><div class="form-group"><label for="name">Name</label><input type="text" class="form-control" id="name" placeholder="Full name"></div><div class="form-group "><label for="email">Email</label><input type="email" class="form-control" id="email" placeholder="example@email.com"></div><div class="form-group "><label for="subject">Subject</label><input type="Text" class="form-control" id="subject" placeholder="Subject ....."></div><div class="form-group"><label for="body">Body</label><textarea class="form-control" id="body" rows="3"></textarea></div><button type="submit" class="btn btn-primary ">Send Mail</button></form></div></body></html>
  1. go to your Firebase console for the project overview in your browser click on the the code icon a modal with your project configuration details copy it, paste is jut before the closing of body
  1. Initialize a the Function package into a variable called functions after firebase.initializeApp(config);
const functions = firebase.functions();
  1. Inside the script tag we Listen to an on submit event of our form and assign all our parameters gotten to an input form :
let form = document.querySelector("#form")form.addEventListener("submit", (e) => {e.preventDefault();const name = document.querySelector("#name");const email = document.querySelector("#email");const body = document.querySelector("#body");const subject = document.querySelector("#subject");});
  1. Inside our eventlisterner, we then call our function we have written and deployed using the Firebase functions.httpsCallable and passing in the name of the function that was deployed and assign in to a constant identifier
  • Note: The name passed into the httpscallable function must correspond with the function name that was deployed and must be passed in as a string
const firebaseEmail = functions.httpsCallable('firebaseEmail');

Next we call the variable of our function just like calling a JavaScript function and pass in the our form parameters

firebaseEmail({name,email,body,subject}).then((result) => {console.log(result)})

Your index.html should be smiliar to this

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Sending Emails</title><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"></head><body><div class="container"><h1>Sending Emails With Firebase Cloud Functions</h1><form class="" id="form"><div class="form-group"><label for="name">Name</label><input type="text" class="form-control" id="name" placeholder="Full name"></div><div class="form-group "><label for="email">Email</label><input type="email" class="form-control" id="email" placeholder="example@email.com"></div><div class="form-group "><label for="subject">Subject</label><input type="Text" class="form-control" id="subject" placeholder="Subject ....."></div><div class="form-group"><label for="body">Body</label><textarea class="form-control" id="body" rows="3"></textarea></div><button type="submit" class="btn btn-primary ">Send Mail</button></form></div><script src="https://www.gstatic.com/firebasejs/5.10.1/firebase.js"></script><script>// Initialize Firebasevar config = {apiKey: "AIzaSyBy1q_OH02mSx6fWY3yuXHSd52DRRYvbx8",authDomain: "fir-email-e97f6.firebaseapp.com",databaseURL: "https://fir-email-e97f6.firebaseio.com",projectId: "fir-email-e97f6",storageBucket: "fir-email-e97f6.appspot.com",messagingSenderId: "540758752905"};firebase.initializeApp(config);const functions = firebase.functions();let form = document.querySelector("#form")form.addEventListener("submit", (e) => {e.preventDefault();const name = document.querySelector("#name");const email = document.querySelector("#email");const body = document.querySelector("#body");const subject = document.querySelector("#subject");const firebaseEmail = functions.httpsCallable('firebaseEmail');firebaseEmail({name,email,body,subject}).then((result) => {console.log(result)})})</script></body></html>

Our front-end Should Be similar to this:

Conclusions

During this article we’ve learnt that we can send mails with input gotton from a form using firebase cloud functions which has similar syntax with NodeJS, deploy this function and acess it with our web application.

--

--