You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firebase Cloud Functions能否通过Auth内置服务触发自定义邮件?

Answer

Great question! All the scenarios you're asking about are absolutely supported with Firebase Cloud Functions and the Admin JavaScript SDK—let's break this down step by step:

1. Triggering Auth-based emails with custom sender & OOB codes

Yes, you can trigger authentication-related emails (like verification links, password resets) via Cloud Functions, and customize the sender address to noreply@my-domain.com—but there are a couple key setup steps:

  • First, verify your custom domain my-domain.com in the Firebase Console (under Project Settings > Domains) to confirm you have permission to send emails from it.
  • Set up a reliable SMTP service (like SendGrid, Mailgun, or Gmail for testing) to handle sending emails from your custom address. Firebase's default auth emails don't support custom senders, so you'll need to handle the email delivery yourself.

To generate and send a custom OOB (OutOfBand) link (like an email verification code), use the Admin SDK's generateEmailVerificationLink() method (or similar methods for password resets) to create a valid action link, then use nodemailer to send the email from your custom address. Here's a quick example:

const functions = require("firebase-functions");
const admin = require("firebase-admin");
const nodemailer = require("nodemailer");

admin.initializeApp();

// Configure your SMTP transporter
const transporter = nodemailer.createTransport({
  host: "smtp.your-provider.com", // e.g., smtp.sendgrid.net
  port: 587,
  secure: false,
  auth: {
    user: "noreply@my-domain.com",
    pass: "your-smtp-password-or-api-key"
  }
});

async function sendCustomVerificationEmail(userEmail, uid) {
  // Define where the user lands after clicking the link
  const actionCodeSettings = {
    url: `https://your-app.com/verify-email?uid=${uid}`,
    handleCodeInApp: true, // Enable in-app code handling if needed
    expirationTime: Date.now() + 3600000 // Link expires in 1 hour (optional)
  };

  // Generate the OOB verification link
  const verificationLink = await admin.auth().generateEmailVerificationLink(userEmail, actionCodeSettings);

  // Send the email
  return transporter.sendMail({
    from: '"Your App Name" <noreply@my-domain.com>',
    to: userEmail,
    subject: "Verify Your Email Address",
    html: `<p>Click <a href="${verificationLink}">here</a> to verify your email and access your account.</p>`
  });
}

2. Sending order submission notifications

Your specific business scenario—triggering an email when an orders/{uid} document's stage field updates to submitted—is perfectly achievable with a Firestore Cloud Function trigger. Here's how to implement it:

// Trigger on updates to the orders collection
exports.sendOrderSubmittedAlert = functions.firestore
  .document("orders/{uid}")
  .onUpdate(async (change, context) => {
    const previousStage = change.before.data().stage;
    const newStage = change.after.data().stage;
    const uid = context.params.uid;

    // Only trigger if stage changed to "submitted"
    if (previousStage !== "submitted" && newStage === "submitted") {
      // Get the user's email from Firebase Auth
      const user = await admin.auth().getUser(uid);
      const userEmail = user.email;

      if (!userEmail) {
        functions.logger.warn(`User ${uid} has no email on file—skipping notification.`);
        return;
      }

      // Send the order confirmation email
      return transporter.sendMail({
        from: '"Your App Support" <noreply@my-domain.com>',
        to: userEmail,
        subject: "Your Order Has Been Submitted!",
        html: `
          <p>Hi there,</p>
          <p>Great news—your order has been successfully submitted and is now in our processing queue.</p>
          <p>You can track its status anytime in your account dashboard.</p>
          <p>Thanks for shopping with us!</p>
        `
      });
    }

    // No action needed if stage didn't change to submitted
    return null;
  });

Key Notes

  • Email Deliverability: For production, use a dedicated email service (like SendGrid or Mailgun) instead of Gmail—they offer better deliverability tools and avoid spam filters.
  • Permissions: Ensure your Cloud Functions service account has the necessary permissions to read Firestore documents and access Firebase Auth user data (this is enabled by default for most projects).
  • OOB Link Security: Action codes in OOB links expire after 1 hour by default—you can adjust this via the expirationTime parameter in actionCodeSettings.

内容的提问来源于stack exchange,提问作者Ronnie Smith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:08:26