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.
We are what we repeatedly do. Excellence, then, is not an act, but a habit. Try out Justly and start building your habits today!
Before you use any Firebase extensions, you need to have a Firebase project set up. If you haven't already, follow these steps:
npm install -g firebase-tools
in your command line. - Firebase CLI referencefirebase login
and following the prompts.To install the extension, you can follow either of the methods detailed below:
Run the following command in your command line interface:
firebase ext:install firebase/firestore-send-email --project=your-project-id
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:
1. SMTP Connection URI:
smtp://USERNAME:PASSWORD@HOST:PORT or smtp://USERNAME@HOST:PORT
For example: smtp://example@example.com:password@smtp.example.com:465
2. Firebase Collection Name:
mail
, but you can name it according to your preference.to
, subject
, and message
3. Default From Address:
noreply@yourdomain.com
4. 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:
https://myaccount.google.com/
-> Security SMTP password(Optional)
field.Once you've completed the basic configuration, you are all set to begin sending emails.
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.
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.
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!'));
});
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-emai
l 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()
When sending emails through Cloud Functions, there are two methods to include templates:
We can easily specify the email template within our Cloud Function. Here's how to showcase requested data in a table:
await db.collection('support_requests')
.add({
to: ["example@gmail.com"],
message: {
subject: "Support Request",
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,chrome=1">
<meta name="HandheldFriendly" content="true">
<style>
table {
width: 80%;
border-collapse: collapse;
}
table, th, td {
border: 1px solid black;
}
th {
font-weight: bold;
}
th, td {
height: 30px;
text-align: center;
}
</style>
</head>
<body>
<br>
<table>
<tbody>
<tr>
${Object.entries(data).map((entry, index) => {
const key = entry[0];
const value = Array.isArray(entry[1]) ? entry[1].join("</p><p>") : entry[1]; // Handle arrays specially
return `<tr><td>${key}</td><td>${value}</td></tr>`;
}).join('')}
</tr>
</tbody>
</table>
</body>
</html>
`,
},
}).then(() => console.log('Queued email for delivery!'));
Here's how you can set up your templates:
firebase-send-email
extension.Create one collection called email_templates
(use the same name that is specified in the extension)and add one doc with the id support_request
in Firestore.
The HTML content will look like 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,chrome=1">
<meta name="HandheldFriendly" content="true">
<style>
table {
width: 80%;
border-collapse: collapse;
}
table, th, td {
border: 1px solid black;
}
th {
font-weight: bold;
}
th, td {
height: 30px;
text-align: center;
}
</style>
</head>
<body>
<br>
<table>
<tbody>
{{#each request}}
<tr>
<td>{{@key}}</td>
<td>{{this}}</td>
</tr>
{{/each}}
</tbody>
</table>
</body>
</html>
Here, our support request has dynamic data, so to add dynamic content to a template we have used HandlerBar.
With these steps, you'll have your templates set up and ready to be utilized by the Firebase-Send-Email
extension.
Now, let's modify our cloud function to use the above-predefined template.
exports.sendSupportRequest = onCall(async (request) => {
const db = admin.firestore();
var data = request.data;
await db.collection('support_requests')
.add({
to: ["example@gmail.com"],
template: {
name: "support_request",
data: {
request: data
},
},
}).then(() => console.log('Queued email for delivery!'));
});
Run this command to deploy your functions:
firebase deploy --only functions:sendSupportRequest
We're ready to send our first email. 🍻
Thanks for joining us as we explore the simplicity and effectiveness of utilizing cloud functions for email automation. With the Firebase-send-mail extension seamlessly integrated into your app, providing prompt user support and communication becomes a breeze.
Stay tuned for more insights on optimizing your application's functionalities with cloud technology.