Firebase 提供了現成的 Email 驗證機制,能在使用者註冊後寄出一封驗證信,使用者點擊信中的連結後,就能正式啟用帳號。這能有效防止假帳號與垃圾註冊。
Email 驗證的好處:
登入 Firebase Console
→ Authentication → Templates
你會看到「Email verification」範本。
這裡可以自訂信件內容、標題、logo、語系等。
Firebase 寄信使用內建的 mail server,不需額外設定 SMTP!
Firebase SDK 提供了 sendEmailVerification(user) 函式,
可以在使用者註冊成功(sign up)後立即寄信。
import { getAuth, createUserWithEmailAndPassword, sendEmailVerification } from "firebase/auth";
export const signUpAndSendEmail = async (email, password) => {
  const auth = getAuth();
  try {
    // 建立使用者帳號
    const userCredential = await createUserWithEmailAndPassword(auth, email, password);
    const user = userCredential.user;
    // 寄送驗證信
    await sendEmailVerification(user, {
      url: "https://your-app-domain.com/verify", // 驗證後導向頁
      handleCodeInApp: true, // 可選:在 App 內處理驗證
    });
    console.log("✅ 驗證信已寄出,請至信箱確認!");
    return user;
  } catch (error) {
    console.error("❌ 註冊或寄信失敗:", error.message);
    throw error;
  }
};
假設我們在註冊頁(SignUpPage.jsx)呼叫:
import React, { useState } from "react";
import { signUpAndSendEmail } from "../firebase/authService";
export default function SignUpPage() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [message, setMessage] = useState("");
  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      await signUpAndSendEmail(email, password);
      setMessage("註冊成功!驗證信已寄出,請至信箱確認。");
    } catch (err) {
      setMessage(`錯誤:${err.message}`);
    }
  };
  return (
    <div className="p-4 max-w-md mx-auto">
      <h2 className="text-xl font-bold mb-2">建立帳號</h2>
      <form onSubmit={handleSubmit} className="space-y-3">
        <input
          type="email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          placeholder="Email"
          className="w-full p-2 border rounded"
        />
        <input
          type="password"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          placeholder="Password"
          className="w-full p-2 border rounded"
        />
        <button
          type="submit"
          className="w-full bg-blue-500 text-white py-2 rounded"
        >
          註冊並寄送驗證信
        </button>
      </form>
      {message && <p className="mt-3 text-sm text-gray-600">{message}</p>}
    </div>
  );
}
Firebase 會在 user.emailVerified 欄位顯示驗證狀態。
可在登入後檢查:
import { getAuth } from "firebase/auth";
const auth = getAuth();
const user = auth.currentUser;
if (user?.emailVerified) {
  console.log("✅ 已通過 Email 驗證");
} else {
  console.log("⚠️ 尚未驗證 Email");
}
若你想強制未驗證者無法登入,可在後端(或 Redux)中檢查 emailVerified 狀態再允許進入系統。