# Supabase custom SMTP with Groundmail

Send Supabase signup, magic link, password reset, and invite emails through Groundmail, from your own domain, to every user. It replaces Supabase's built-in email service, which sends 2 emails an hour (see ["Email rate limit exceeded"](#email-rate-limit-exceeded)). There are three ways, fastest first:

1. **One-click connect** (below): Groundmail writes custom SMTP into your Supabase project for you.
2. **Custom SMTP by hand**: create an SMTP credential in the dashboard and paste host, username `groundmail`, and password into Supabase → Authentication → SMTP. See [SMTP relay](https://docs.groundmail.dev/smtp).
3. **Send Email hook**: an Edge Function that calls the HTTP API (`POST /emails`), for full control over each message. See [the hook steps](#1-create-the-edge-function).

---

## "Email rate limit exceeded"

If sign-up, magic link or password reset fails with `email rate limit exceeded` (error code `over_email_send_rate_limit`) or `Email address not authorized` (`email_address_not_authorized`), your project is still on Supabase's built-in email service. It's meant for testing:

- It sends **2 emails an hour** for the whole project.
- It only delivers to members of your Supabase organization. Everyone else gets `Email address not authorized`.

Waiting an hour only buys two more emails. The fix is custom SMTP: [connect Groundmail in one click](#one-click-connect), or paste the SMTP settings by hand. Then raise Supabase's limit: with custom SMTP on, Supabase caps the project at **30 emails an hour** until you change it in Supabase → Authentication → Rate Limits. If the error comes back after you switch, that cap is why.

Apps built with Lovable or Bolt on your own Supabase project hit the same error, and the same fix applies.

---

## One-click connect

Supabase's built-in email service is for testing: it sends 2 emails an hour, and only to your own team. Connect Groundmail before real users sign up.

1. Verify your sending domain in **Domains**.
2. Open **Integrations → Supabase** and click **Connect Supabase**.
3. On Supabase, choose the organization and approve access.
4. Back in Groundmail, pick the project, a sender address on your verified domain (for example `noreply@yourdomain.com`) and a sender name, then click **Turn on Groundmail SMTP**.

Groundmail creates an SMTP credential named `Supabase: <project name>` and turns on custom SMTP for that project. You never see or copy the password. Trigger a password reset to check it: the email shows up in **Emails** with its delivery status.

Good to know:

- **Rate limit.** With custom SMTP on, Supabase starts the project at 30 auth emails an hour. Raise it in Supabase → Authentication → Rate Limits.
- **Free plan.** Until you add a payment method, Groundmail only delivers to your own account email. Add one in **Settings → Billing** before launch. Free is never charged; you're only billed if you turn on pay as you go.
- **Existing SMTP.** If the project already uses another SMTP provider, Groundmail asks before replacing it.
- **Your templates stay.** Only the SMTP settings change. Email templates, redirect URLs and rate limits are left as they are.
- **Disconnect** removes Groundmail's access to your Supabase account. Projects you set up keep sending; revoke their credential in **SMTP** to stop them.

---

## Send Email hook

Use the hook instead of SMTP when you want to build each message yourself, for example with [React Email](https://docs.groundmail.dev/guides/react-email). Your Edge Function calls the HTTP API (`POST /emails`), the same pattern Supabase documents for other ESPs.

---

## When to use this

- You built on **Supabase Auth** (often via Lovable, Vite, or Next.js) and want branded mail on your domain
- You outgrew Supabase’s built-in SMTP limits or need delivery visibility in Groundmail
- You want one transactional provider for auth mail **and** product mail (receipts, alerts)

---

## Architecture

1. User triggers auth (signup, reset, magic link, etc.)
2. Supabase Auth calls your **Send Email** hook (HTTPS Edge Function)
3. The function verifies the webhook signature, builds the message, and calls `POST https://api.groundmail.dev/emails`
4. Return `200` with `{}` so Supabase knows the email was handled

Reference: [Supabase Send Email Hook](https://supabase.com/docs/guides/auth/auth-hooks/send-email-hook).

---

## Prerequisites

1. Groundmail account + `gm_…` API key
2. Verified sending domain (or Sandbox for self-tests only — see [Quickstart](https://docs.groundmail.dev/quickstart))
3. Supabase project with the [Supabase CLI](https://supabase.com/docs/guides/cli) installed

---

## 1. Create the Edge Function

```bash
supabase functions new send-email
```

`supabase/functions/send-email/index.ts`:

```ts
import { Webhook } from 'https://esm.sh/standardwebhooks@1.0.0'

const hookSecret = (Deno.env.get('SEND_EMAIL_HOOK_SECRET') ?? '').replace(/^v1,whsec_/, '')
const apiKey = Deno.env.get('GROUNDMAIL_API_KEY')
const fromEmail = Deno.env.get('GROUNDMAIL_FROM_EMAIL') ?? 'noreply@yourdomain.com'
const projectRef = Deno.env.get('SUPABASE_PROJECT_REF')

const subjects: Record<string, string> = {
  signup: 'Confirm your email',
  recovery: 'Reset your password',
  invite: 'You have been invited',
  magiclink: 'Your sign-in link',
  email_change: 'Confirm your new email',
  email_change_new: 'Confirm your new email',
  reauthentication: 'Your verification code',
}

function confirmationUrl(emailData: {
  token_hash: string
  email_action_type: string
  redirect_to: string
}) {
  const base = `https://${projectRef}.supabase.co/auth/v1/verify`
  const params = new URLSearchParams({
    token: emailData.token_hash,
    type: emailData.email_action_type,
    redirect_to: emailData.redirect_to,
  })
  return `${base}?${params.toString()}`
}

Deno.serve(async (req) => {
  if (req.method !== 'POST') {
    return new Response('method not allowed', { status: 405 })
  }
  if (!apiKey || !hookSecret || !projectRef) {
    return new Response('server misconfigured', { status: 500 })
  }

  const payload = await req.text()
  const headers = Object.fromEntries(req.headers)

  try {
    const wh = new Webhook(hookSecret)
    const { user, email_data } = wh.verify(payload, headers) as {
      user: { email: string }
      email_data: {
        token: string
        token_hash: string
        redirect_to: string
        email_action_type: string
      }
    }

    const action = email_data.email_action_type
    const subject = subjects[action] ?? 'Notification'
    const link = confirmationUrl(email_data)

    const html =
      action === 'reauthentication'
        ? `<p>Your verification code is <strong>${email_data.token}</strong></p>`
        : `<p><a href="${link}">${subject}</a></p>`

    const text =
      action === 'reauthentication'
        ? `Your verification code is ${email_data.token}`
        : `${subject}: ${link}`

    const res = await fetch('https://api.groundmail.dev/emails', {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${apiKey}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        from: fromEmail,
        to: user.email,
        subject,
        html,
        text,
      }),
    })

    if (!res.ok) {
      const body = await res.text()
      throw new Error(`Groundmail ${res.status}: ${body}`)
    }
  } catch (error) {
    console.error(error)
    return new Response(JSON.stringify({ error: String(error) }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' },
    })
  }

  return new Response(JSON.stringify({}), {
    status: 200,
    headers: { 'Content-Type': 'application/json' },
  })
})
```

Customize subjects and HTML (or render [React Email](https://docs.groundmail.dev/guides/react-email) in the function) for production.

---

## 2. Set secrets and deploy

`supabase/functions/.env` (local) — do not commit:

```bash
GROUNDMAIL_API_KEY=gm_your_key_here
GROUNDMAIL_FROM_EMAIL=noreply@yourdomain.com
SUPABASE_PROJECT_REF=your-project-ref
SEND_EMAIL_HOOK_SECRET=v1,whsec_...   # from Supabase dashboard after step 3
```

```bash
supabase secrets set --env-file supabase/functions/.env
supabase functions deploy send-email --no-verify-jwt
```

Note the deployed function URL (e.g. `https://<project-ref>.supabase.co/functions/v1/send-email`).

---

## 3. Enable the Send Email hook

**Alternative:** If you prefer Supabase’s built-in SMTP settings UI, create an SMTP credential in Groundmail (**SMTP** in the dashboard) and configure [custom SMTP in Supabase](https://supabase.com/docs/guides/auth/auth-smtp) with host `smtp.groundmail.dev`, port `587`, username `groundmail`, and your credential password. Skip the hook steps below.

In [Supabase Dashboard → Authentication → Hooks](https://supabase.com/dashboard/project/_/auth/hooks):

1. Add **Send Email** hook
2. Type: **HTTPS**
3. URL: your Edge Function URL
4. **Generate secret** — copy the `v1,whsec_…` value into `SEND_EMAIL_HOOK_SECRET`
5. Save

Redeploy or update secrets if you generated the secret after the first deploy.

While the hook is enabled, Supabase does **not** send auth mail itself — your function must succeed and return `200` + `{}`.

---

## 4. Auth email types

Handle every `email_action_type` your app uses:

| `email_action_type` | Typical use |
|---------------------|-------------|
| `signup` | Email confirmation |
| `recovery` | Password reset |
| `magiclink` | Passwordless sign-in |
| `invite` | User invite |
| `email_change` | Confirm email change |
| `email_change_new` | Confirm new address (secure email change) |
| `reauthentication` | Step-up OTP |

If the hook is on and a type is missing from your templates, that mail can fail silently.

---

## 5. Sandbox vs production

| Stage | `from` | `to` |
|-------|--------|------|
| Sandbox (no domain verified) | `noreply@mail.groundmail.dev` (or your sandbox domain) | Your Groundmail account email only |
| Verified domain (no payment method) | `noreply@yourdomain.com` | Account email only |
| Free production / paid | `noreply@yourdomain.com` | Any recipient |

Verify your domain in Groundmail, then add a payment method to unlock Free production before switching `GROUNDMAIL_FROM_EMAIL` to real users.

---

## 6. Webhooks (optional)

Subscribe to `email.delivered`, `email.bounced`, and `email.complained` in Groundmail to monitor auth mail health. See [Webhooks](https://docs.groundmail.dev/webhooks).

---

## Lovable / AI builders

If you generated the app in Lovable, store `GROUNDMAIL_API_KEY` in project secrets and ask the agent to wire this hook — see [Lovable + Groundmail](https://docs.groundmail.dev/builders/lovable).

---

## Related

- [Auth providers (Clerk, Auth.js)](https://docs.groundmail.dev/guides/password-reset-emails#auth-providers)
- [Password reset emails](https://docs.groundmail.dev/guides/password-reset-emails)
- [React Email](https://docs.groundmail.dev/guides/react-email)
- [Password reset emails going to spam?](https://groundmail.dev/guides/password-reset-emails-going-to-spam/) (Learn)
