Sending Emails with Firebase Cloud Functions and SendGrid

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

  1. Go to Firebase Console
    Visit https://console.firebase.google.com and create a new project (e.g., webstaremailsystem).

  2. 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 plan and switch from Spark to Blaze.


πŸ’» Step 2: Install Firebase CLI and Initialize Functions

  1. Install Firebase CLI

     npm install -g firebase-tools
    
  2. Login to Firebase

     firebase login
    
  3. Initialize Functions

     mkdir jetwave-functions
     cd jetwave-functions
     firebase init functions
    
    • Select: Use an existing project β†’ choose webstaremailsystem

    • Language: JavaScript

    • Linting: No

    • Install dependencies: Yes


πŸ” Step 3: Set Up SendGrid

  1. Sign Up at https://app.sendgrid.com

  2. Generate API Key

    • Go to Settings > API Keys > Create API Key

    • Label it something like webstar-firebase

    • Copy and save the API key securely

  3. Authenticate Your Domain

    • Go to Sender Authentication β†’ Domain Authentication

    • Select 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

  1. Navigate to your functions folder:

     cd functions
     npm install @sendgrid/mail
    
  2. Edit 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" });
  }
});
  1. 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

  1. Deploy only functions:

     firebase deploy --only functions
    
  2. Get 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() or axios in 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 DMARC record 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.


0
Subscribe to my newsletter

Read articles from Ogunuyo Ogheneruemu B directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Ogunuyo Ogheneruemu B
Ogunuyo Ogheneruemu B

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.