Sending Emails with Firebase Cloud Functions and SendGrid

I'm Ogunuyo Ogheneruemu Brown, a senior software developer. I specialize in DApp apps, fintech solutions, nursing web apps, fitness platforms, and e-commerce systems. Throughout my career, I've delivered successful projects, showcasing strong technical skills and problem-solving abilities. I create secure and user-friendly fintech innovations. Outside work, I enjoy coding, swimming, and playing football. I'm an avid reader and fitness enthusiast. Music inspires me. I'm committed to continuous growth and creating impactful software solutions. Let's connect and collaborate to make a lasting impact in software development.
How We Set Up https://us-central1-webstaremailsystem.cloudfunctions.net/sendOtpEmail for [company name]
When building apps that require sending verification emails, OTPs, or notifications, using a reliable and scalable cloud function is a game changer. In this guide, weβll walk through the entire process of setting up a Firebase Cloud Function that sends email using SendGrid, including domain authentication to avoid the spam folder.
π§± Step 1: Set Up Firebase Project
Go to Firebase Console
Visit https://console.firebase.google.com and create a new project (e.g.,webstaremailsystem).Enable Blaze Plan
Firebase Cloud Functions that use external APIs (like SendGrid) require the Blaze (pay-as-you-go) plan.Navigate to
Settings > Usage and billing.Click
Modify planand switch from Spark to Blaze.
π» Step 2: Install Firebase CLI and Initialize Functions
Install Firebase CLI
npm install -g firebase-toolsLogin to Firebase
firebase loginInitialize Functions
mkdir jetwave-functions cd jetwave-functions firebase init functionsSelect:
Use an existing projectβ choosewebstaremailsystemLanguage:
JavaScriptLinting:
NoInstall dependencies:
Yes
π Step 3: Set Up SendGrid
Sign Up at https://app.sendgrid.com
Generate API Key
Go to
Settings > API Keys > Create API KeyLabel it something like
webstar-firebaseCopy and save the API key securely
Authenticate Your Domain
Go to
Sender AuthenticationβDomain AuthenticationSelect DNS provider (e.g., Namecheap or manual cPanel entry)
Add the CNAME and TXT records in your domainβs cPanel
Wait for SendGrid to verify (can take minutes to hours)
π¦ Step 4: Add SendGrid to Firebase Function
Navigate to your functions folder:
cd functions npm install @sendgrid/mailEdit
functions/index.js:
const functions = require("firebase-functions");
const sgMail = require("@sendgrid/mail");
// Replace with your actual SendGrid API key
sgMail.setApiKey("YOUR_SENDGRID_API_KEY");
exports.sendOtpEmail = functions.https.onRequest(async (req, res) => {
const { email, name, subject, body } = req.body;
if (!email || !subject || !body) {
return res.status(400).json({ status: "error", message: "Missing required fields" });
}
const msg = {
to: email,
from: "info@domain.com", // Must be verified on SendGrid
subject,
html: body,
};
try {
await sgMail.send(msg);
res.status(200).json({ status: "success", message: "Email sent" });
} catch (error) {
console.error("SendGrid Error:", error);
res.status(500).json({ status: "error", message: "Failed to send email" });
}
});
- Replace
"YOUR_SENDGRID_API_KEY"with your actual key. You can use Firebase environment variables to keep this secret.
π Step 5: Deploy Function to Firebase
Deploy only functions:
firebase deploy --only functionsGet your function URL:
Firebase will return a URL like:
https://us-central1-webstaremailsystem.cloudfunctions.net/sendOtpEmail
π¬ Step 6: Test Email Function
Send a POST request to the endpoint with a body like:
{
"email": "recipient@example.com",
"name": "User",
"subject": "Your Webstar OTP",
"body": "<p>Hello <strong>User</strong>, your OTP is <strong>9021</strong></p>"
}
You can test using tools like:
Postman
cURL
JavaScript
fetch()oraxiosin your frontend
π Bonus Tips for Deliverability
β Make sure you verify your sending domain on SendGrid
π₯ Ask your users to whitelist your sender email (
info@domain.com)π Add a valid
DMARCrecord to improve sender trustπ Emails might land in spam on first test β once verified, they should hit inbox
β Conclusion
You now have a production-ready cloud function that sends emails using Firebase and SendGrid. This setup is scalable, serverless, and reliable β perfect for OTPs, password resets, and transactional emails in modern web/mobile apps.



