Frameworks

How to send email with Firebase Cloud Functions

Short answer

Firebase has no general email sending service, so you send email from a Cloud Function. Store your email API key with defineSecret, then call the API with fetch from an HTTPS function or a Firestore trigger such as onDocumentCreated. For Firebase Auth emails, either configure custom SMTP in the console or generate action links with the Admin SDK and send them yourself. Verify your sending domain first.

Last checked 16 November 2026

Firebase does not have a general-purpose email service, so the usual way to send email is from a Cloud Function: keep your email API key in Secret Manager, and call the API with fetch when an HTTPS request comes in or when a Firestore document is created. This guide shows both, plus how to handle Firebase Auth emails.

Cloud Functions require the Blaze (pay as you go) plan, which also allows outbound requests to services outside Google.

Store the API key as a secret

Do not put keys in source code or in functions.config(), which is deprecated and stops working for new deployments after March 2027, according to Firebase’s configuration docs. Use a secret instead:

firebase functions:secrets:set MAILCANDOR_KEY

The CLI prompts for the value and stores it in Cloud Secret Manager. In code, declare it with defineSecret and bind it to each function that needs it. Only bound functions can read it, and only at runtime through .value().

Option 1: an HTTPS function that sends email

The examples use TypeScript, the 2nd gen function APIs and Node 22, where fetch is built in. They send through Mailcandor; other email APIs follow the same pattern.

// functions/src/index.ts
import { onRequest } from "firebase-functions/v2/https";
import { defineSecret } from "firebase-functions/params";
import { logger } from "firebase-functions";

const mailcandorKey = defineSecret("MAILCANDOR_KEY");

async function sendEmail(key: string, email: object, idempotencyKey: string) {
  const res = await fetch("https://api.mailcandor.com/v1/emails", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${key}`,
      "Content-Type": "application/json",
      "Idempotency-Key": idempotencyKey,
    },
    body: JSON.stringify(email),
  });
  const data = await res.json();
  if (!res.ok) throw new Error(`${data.error.type}: ${data.error.message}`);
  return data.id as string;
}

export const contact = onRequest(
  { secrets: [mailcandorKey], cors: ["https://acme.com"] },
  async (req, res) => {
    if (req.method !== "POST") {
      res.status(405).send("Method not allowed");
      return;
    }
    const { email, message } = req.body ?? {};
    if (typeof email !== "string" || typeof message !== "string") {
      res.status(400).send("Missing fields");
      return;
    }

    const id = await sendEmail(
      mailcandorKey.value(),
      {
        from: "Acme website <hello@acme.com>",
        to: "team@acme.com",
        reply_to: email,
        subject: "New contact form message",
        text: message,
      },
      crypto.randomUUID(),
    );
    logger.info("contact email queued", { id });
    res.json({ ok: true });
  },
);

Sending to your own team and putting the visitor in reply_to means you can answer with one click, and nobody can use the form to send mail to arbitrary addresses. Add a CAPTCHA or App Check before going live; a public form is a spam target.

Option 2: send email when a Firestore document is created

Triggers are the Firebase-native way to send transactional email. Write an order or user document, and a function sends the email in the background:

import { onDocumentCreated } from "firebase-functions/v2/firestore";

export const orderReceipt = onDocumentCreated(
  { document: "orders/{orderId}", secrets: [mailcandorKey] },
  async (event) => {
    const order = event.data?.data();
    if (!order) return;

    await sendEmail(
      mailcandorKey.value(),
      {
        from: "Acme <orders@acme.com>",
        to: order.customerEmail,
        subject: `Order ${event.params.orderId} confirmed`,
        html: `<p>Thanks for your order. Total: ${order.total}</p>`,
        tags: [{ name: "type", value: "receipt" }],
      },
      `order-${event.params.orderId}-receipt`,
    );
  },
);

Event-triggered functions can run more than once for the same event. The Idempotency-Key built from the order id turns a duplicate run into a no-op: the API returns the first response instead of sending a second receipt. That is why the key here is fixed per order and not random.

If you turn on retries for the function, the same key also protects you when a send fails halfway and the event is delivered again.

What about SMTP from Cloud Functions?

Cloud Functions run Node.js, so Nodemailer works with an SMTP relay on port 465 or 587. The Node.js email guide has the code. An API call is usually the better fit for functions: it is one HTTPS request with no SMTP handshake on each cold start, and the response gives you an id to match against delivery webhooks.

Firebase also offers a “Trigger Email from Firestore” extension, which watches a collection and sends each new document through an SMTP server you configure by connection URI. It is a reasonable no-code option if you already have an SMTP relay.

Firebase Auth emails

Verification, password reset and email change messages come from Firebase Authentication, not from your functions. You have two choices:

  1. Keep Firebase’s sender, with your domain. Edit the templates under Authentication, Templates in the console, and set up a custom domain so they come from your address. The templates page also has SMTP settings for sending these emails through your own SMTP server.
  2. Send them yourself. Generate the link with the Admin SDK, then send it with your own template:
import { getAuth } from "firebase-admin/auth";

const link = await getAuth().generatePasswordResetLink(userEmail);
await sendEmail(mailcandorKey.value(), {
  from: "Acme <security@acme.com>",
  to: userEmail,
  subject: "Reset your Acme password",
  html: `<p><a href="${link}">Choose a new password</a>. The link expires soon.</p>`,
}, crypto.randomUUID());

generateEmailVerificationLink and generateSignInWithEmailLink work the same way. This gives you full control of the design and lets you track delivery like any other email.

Before you send: verify your domain

Whether the email comes from a function or from Auth, the sending domain needs SPF, DKIM and DMARC records, or it will often land in spam. Add the domain in your provider’s dashboard and publish its records. The SPF, DKIM and DMARC setup guide walks through it.

Sending with Mailcandor

Mailcandor works from Cloud Functions with plain fetch and the email API; there is no SDK to install. The same key works with the SMTP relay if you use the Firestore extension or Firebase Auth’s SMTP settings. Access is by request through the pricing page.

Questions

Can Firebase send emails by itself?

Only Firebase Authentication emails such as verification and password reset. For anything else, send email from a Cloud Function using an email API or SMTP.

How do I store an email API key in Firebase Functions?

Use defineSecret from firebase-functions/params, set the value with firebase functions:secrets:set, and list the secret in the function's options. functions.config() is deprecated.

Can Firebase Auth use a custom SMTP server?

The Authentication templates page in the Firebase console has SMTP settings for sending Auth emails through your own server. For full control, generate the action link with the Admin SDK and send the email yourself.

Do I need the Blaze plan to send email from Cloud Functions?

Deploying Cloud Functions requires the pay-as-you-go Blaze plan, and calls to external services such as an email API need it too.

Related

Send with someone on your side.

Unlimited domains on every plan, a person before any block, and 3,000 emails a month free. Tell us what you send and we set you up within one business day.