Wasm Builders 🧱

Cover image for How To Send Emails Using Cloud Functions, Firestore & Firebase-Send-Email
cp-nandani
cp-nandani

Posted on • Originally published at canopas.com

How To Send Emails Using Cloud Functions, Firestore & Firebase-Send-Email

Exciting News! Our blog has a new home! 🚀

Background

Welcome to our blog where we’ll talk about using cloud technology to make sending emails easier. Imagine you have a website where people sign up for newsletters. When someone signs up, you want to send them a welcome email. Cloud functions help with this — they can automatically send emails, making sure users get a warm welcome right away.

Imagine a scenario where a user has a question or feedback about an app feature and wishes to communicate this directly to the developer.

By focusing on the Firebase-send-mail extension for handling email communication, we aim to showcase the practicality and efficiency of using cloud functions for enhancing user support functionalities within your applications.

Step 1: Set Up Your Firebase Project

Before you use any Firebase extensions, you need to have a Firebase project set up. If you haven’t already, follow these steps:

1. Create a Firebase Project:

  1. Go to the Firebase console: Firebase Console.
  2. Click on “Add project,” and follow the on-screen instructions to create a new Firebase project.

2. Configure Firebase CLI:

  • Install the Firebase CLI by running npm install -g firebase-tools in your command line. - Firebase CLI reference
  • Authenticate the CLI by running firebase login and following the prompts.

Step 2: Install the firebase-send-email Extension

To install the extension, you can follow either of the methods detailed below:

Using the Firebase Console:

  1. Navigate to the Firebase console.
  2. Locate and select the Extensions tab.
  3. Search for and choose the Firestore Trigger Email extension.
  4. Follow the on-screen instructions to install it.

Using the Firebase CLI:

Run the following command in your command line interface:

firebase ext:install firebase/firestore-send-email --project=your-project-id
Enter fullscreen mode Exit fullscreen mode

Replace your-project-id with your actual Firebase project ID. This command will guide you through the installation process directly from your terminal.

When installing the Firestore Trigger Email extension, whether through the Firebase console or using the CLI, you’ll need to provide some basic configuration details to set it up correctly.

Here’s a guide on the essential configurations you’ll need to provide:

SMTP Connection URI:

  • This is a critical parameter that allows the extension to connect to your SMTP server for sending emails.
  • It should follow the format: smtp://USERNAME:PASSWORD@HOST:PORT or smtp://USERNAME@HOST:PORT

For example:
smtp://example@example.com:password@smtp.example.com:465

Firebase Collection Name:

  • Specify the name of the Firestore collection that the extension will monitor to trigger email sends. By default, this is usually set to mail, but you can name it according to your preference.
  • This collection will need to contain documents with fields matching your email template requirements, such as to, subject, and message

Default From Address:

  • This configuration sets the default email address from which all outgoing emails will be sent. This email address must be verified with your SMTP provider to ensure successful delivery of emails.
  • Example: noreply@yourdomain.com

SMTP Password:

Part of your SMTP connection URI, is the password for the SMTP account you are using to send emails.

To generate a password:

  1. go to https://myaccount.google.com/ -> Security
  2. Turn on the 2-step verification
  3. Go to “App passwords”
  • Provide a name for the app password
  • You will get one popup showing your password, copy it
  • Go back to firebase console -> extensions -> Trigger email extension -> click reconfigure and add your password in SMTP password(Optional) field.

Once you’ve completed the basic configuration, you are all set to begin sending emails.

Step 3: Write Cloud Functions to Send Email

With the firebase-send-email extension installed and configured, the next step is to write callable Cloud Functions that leverage the firebase-send-email extension to send emails.

Specifically, we’ll create a callable Cloud Function that triggers upon the submission of a contact request by the client.

1. Setting Up Firebase Cloud Functions:

Before we begin writing our Cloud Function, ensure you have the Firebase CLI installed and your project initialized.

If not, you can install it via npm and initialize your project by running firebase init functions in your terminal.

2. Writing the Cloud Function:

We’ll write a callable Cloud Function triggered by a client request to submit a contact request. This function will extract the necessary information from the request body and use the firebase-send-email extension to send an email.

const {onCall, HttpsError} = require("firebase-functions/v2/https");
const admin = require("firebase-admin");
// Initialize the default Firebase app
admin.initializeApp();

exports.sendSupportRequest = onCall(async (request) => {

    const db = admin.firestore();
    var data = request.data;

    await db.collection('support_requests')
        .add({
            to: ["example@gmail.com"],
            message: {
                subject: "Support Request",
                html: <HTML TEMPLET goes here>,
            },
        }).then(() => console.log('Queued email for delivery!'));

});
Enter fullscreen mode Exit fullscreen mode

The sendSupportRequest function, triggered by a client call, adds a document to the Firestore collection support_requests. This document contains email details, such as recipient and message content, essential for processing support requests.

The firebase-send-email extension monitors the support_requests collection. Once the document is added to Firestore, the extension detects the new document and extracts the email details from it.

It then utilizes the configured email service provider to send an email to the specified recipients, using the content provided in the Firestore document.

Here’s how you can trigger the above cloud function with the required details in your Android application.

val data = mapOf(
            "title" to title,
            "description" to description,
            "device_name" to device.deviceName(),
            "app_version" to device.getAppVersionCode().toString(),
            "device_os" to device.getDeviceOsVersion(),
            "user_id" to userId,
            "attachments" to attachments.map { it.toString() }
        )

functions.getHttpsCallable("sendSupportRequest").call(data).await()
Enter fullscreen mode Exit fullscreen mode

This post has steps to setup extention and cloud funtion to read the complete guide about how to configure HTML Templete, please visit this blog.

The post is originally published on canopas.com.

If you like what you read, be sure to hit
💖 button! — as a writer it means the world!

I encourage you to share your thoughts in the comments section below. Your input not only enriches our content but also fuels our motivation to create more valuable and informative articles for you.

Top comments (0)