> Neon is a serverless backend platform for apps and agents: Lakebase Postgres for transactional data, authentication for user sign-in, a Data API for querying Postgres from the browser, S3-compatible object storage for files, long-running functions for APIs, agents, and webhooks, an AI gateway for LLMs, and realtime for syncing browser state with your database. Every service branches with your data for dev, test, and preview. Pricing: https://neon.com/pricing.md. Plans and limits: https://neon.com/docs/introduction/plans.md.
> Full Neon documentation index: https://neon.com/docs/llms.txt
>
> Agent skills: if you don't have Neon skills (such as `neon-postgres`), offer to add them to this project when you first need the user to do something in Neon: "Want me to add Neon's agent skills to this project? They help me with Neon setup, connections, and branching." Install: `npx neon@latest skills -y`. To also run Neon steps for the user (Neon CLI, sign-in, MCP), see https://neon.com/prompts/agent-setup.md

# Keep Groundmail inbound email and events in Neon

Receive Groundmail webhooks in a Neon Function, store each email event and inbound email in Lakebase Postgres on Neon, and keep the attachments in Object Storage

Last updated: 2026-12-01

Gmail's [email sender guidelines](https://support.google.com/mail/answer/81126) ask senders to keep their spam rate below 0.3%, and [since November 2025](https://support.google.com/mail/answer/14229414) Gmail rejects more email from senders that don't follow them. To stay under that limit, your app needs to know which users bounced or marked your email as spam. [Groundmail](https://groundmail.dev) sends a [webhook](https://docs.groundmail.dev/webhooks) for each such outcome, and for each email that arrives on a [receiving domain](https://docs.groundmail.dev/inbound).

In this guide, you'll receive those webhooks in a [Neon Function](https://neon.com/docs/compute/functions/overview) and connect it to two more Neon services:

- Lakebase Postgres, which stores each email event and each inbound email
- [Object Storage](https://neon.com/docs/storage/overview), which stores the attachments of each inbound email

## Prerequisites

- Node.js 22 or later
- A [Neon](https://console.neon.tech/signup) project in a region where [Neon Functions are available](https://neon.com/docs/compute/functions/overview) and [Neon CLI](https://neon.com/docs/cli/install) installed
- A [Groundmail](https://groundmail.dev) account with a [verified domain](https://docs.groundmail.dev/domains) that has [inbound receiving](https://docs.groundmail.dev/inbound) turned on (such as `inbound.example.com`)

Inbound receiving points the domain's MX record to Groundmail, so use a subdomain if your main domain receives email elsewhere.

## Architecture

```mermaid
sequenceDiagram
    participant GM as Groundmail
    participant F as Neon Function
    participant S as Object Storage
    participant DB as Postgres
    GM->>F: Webhook with a Groundmail-Signature header
    F->>F: Verify the signature
    alt email.received
        F->>GM: GET /received-emails/{id}
        F->>S: Upload the attachments
        F->>DB: Insert the inbound email
    end
    F->>DB: Insert the event
    F-->>GM: 200 OK
```

Groundmail's payloads have no event ID, so each event row is keyed by the event type, `email_id`, and `created_at`. A retry sends the same payload, so it adds no row.

## Set up the project

Create a directory and install the dependencies:

```bash
mkdir groundmail-webhooks && cd groundmail-webhooks
npm init -y
npm install pg groundmail aws4fetch @neon/functions @neon/config
npm install -D @types/pg
```

- `pg` writes to Postgres.
- `aws4fetch` signs the Object Storage requests.
- `groundmail` verifies signatures and fetches inbound emails.

Link the directory to your Neon project:

```bash
neon link
```

The CLI pulls the branch's `DATABASE_URL` into `.env.local`.

Export your full-access Groundmail API key for the setup commands. The function doesn't use it:

```bash
export GROUNDMAIL_ADMIN_KEY=gm_your_full_access_key
```

## Create the tables

Save this as `schema.sql`:

```sql filename="schema.sql"
CREATE TABLE groundmail_events (
  event_type  text NOT NULL,
  email_id    text NOT NULL,
  event_time  timestamptz NOT NULL,
  recipients  text[] NOT NULL,
  test        boolean NOT NULL DEFAULT false,
  payload     jsonb NOT NULL,
  received_at timestamptz NOT NULL DEFAULT now(),
  PRIMARY KEY (event_type, email_id, event_time)
);

CREATE INDEX groundmail_events_email_id_idx ON groundmail_events (email_id);
CREATE INDEX groundmail_events_recipients_idx ON groundmail_events USING gin (recipients);

CREATE TABLE groundmail_inbound_emails (
  id                text PRIMARY KEY,
  from_address      text NOT NULL,
  to_addresses      text[] NOT NULL,
  subject           text,
  text_body         text,
  html_body         text,
  message_id        text,
  in_reply_to_email text,
  spam_status       text,
  spam_score        real,
  attachments       jsonb NOT NULL DEFAULT '[]',
  received_at       timestamptz NOT NULL
);
```

Run it on the linked branch with [`neon psql`](https://neon.com/docs/cli/psql):

```bash
neon psql -- -f schema.sql
```

- `groundmail_events` has one row per event. `test` is `true` for [simulated events](https://docs.groundmail.dev/testing), and `payload` keeps the full event.
- `groundmail_inbound_emails` has one row per inbound email. `attachments` lists each file's name, type, size, and Object Storage key, and `in_reply_to_email` is the ID of the email it [replies to](https://docs.groundmail.dev/inbound#replies-to-emails-you-sent), if any.

## Create an API key for the function

The function fetches each inbound email with `GET /received-emails/{id}`, which needs the `emails:read` scope. Create a key with that scope:

```bash
curl -s https://api.groundmail.dev/api-keys \
  -H "Authorization: Bearer $GROUNDMAIL_ADMIN_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"name": "Neon webhooks", "scopes": ["emails:read"]}'
```

You can also create it on the [API keys](https://app.groundmail.dev/api-keys) page. Groundmail shows the key only once, in `token`, so add it to `.env.local` right away:

```bash filename=".env.local"
GROUNDMAIL_API_KEY=gm_your_read_only_key
```

## Write the function

Create `functions/groundmail-webhooks.ts`:

```ts filename="functions/groundmail-webhooks.ts"
import { attachDatabasePool } from '@neon/functions';
import { AwsClient } from 'aws4fetch';
import { Groundmail, verifyWebhookSignature } from 'groundmail';
import { Pool } from 'pg';

// Create the pool once at module scope so it's reused across requests.
const pool = new Pool({ connectionString: process.env.DATABASE_URL, max: 5 });
attachDatabasePool(pool);

const groundmail = new Groundmail(process.env.GROUNDMAIL_API_KEY!);

const s3 = new AwsClient({
  accessKeyId: process.env.AWS_ACCESS_KEY_ID!,
  secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!,
  region: process.env.AWS_REGION,
  service: 's3',
});

const BUCKET = 'inbound-attachments';

function objectUrl(key: string): string {
  return `${process.env.AWS_ENDPOINT_URL_S3}/${BUCKET}/${key.split('/').map(encodeURIComponent).join('/')}`;
}

type GroundmailEvent = {
  type: string;
  created_at: string;
  data: { email_id?: string; to?: string[]; test?: boolean };
};

// Fetch the full message, upload its attachments, and store it with their keys.
async function storeInboundEmail(id: string) {
  const { received_email: email } = await groundmail.receivedEmails.get(id);

  const attachments = [];
  for (const [index, attachment] of email.attachments.entries()) {
    // The file name comes from the sender, so replace slashes to keep it from changing the path.
    const key = `${email.id}/${index}-${attachment.filename.replace(/[/\\]/g, '_')}`;
    const upload = await s3.fetch(objectUrl(key), {
      method: 'PUT',
      body: Buffer.from(attachment.data ?? '', 'base64'),
      headers: { 'Content-Type': attachment.content_type },
    });
    if (!upload.ok) throw new Error(`Object Storage PUT ${key} returned ${upload.status}`);
    attachments.push({
      filename: attachment.filename,
      content_type: attachment.content_type,
      size: attachment.size,
      key,
    });
  }

  await pool.query(
    `INSERT INTO groundmail_inbound_emails
       (id, from_address, to_addresses, subject, text_body, html_body, message_id,
        in_reply_to_email, spam_status, spam_score, attachments, received_at)
     VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
     ON CONFLICT (id) DO NOTHING`,
    [
      email.id,
      email.from,
      email.to,
      email.subject,
      email.text_body,
      email.html_body,
      email.message_id,
      email.in_reply_to_email?.id ?? null,
      email.spam_status,
      email.spam_score,
      JSON.stringify(attachments),
      email.received_at,
    ]
  );
}

export default {
  async fetch(request: Request): Promise<Response> {
    if (request.method !== 'POST') return new Response('Use POST', { status: 405 });

    const secret = process.env.GROUNDMAIL_WEBHOOK_SECRET;
    if (!secret) return Response.json({ error: 'GROUNDMAIL_WEBHOOK_SECRET is not set' }, { status: 500 });

    const rawBody = await request.text();
    if (!verifyWebhookSignature(secret, rawBody, request.headers.get('groundmail-signature'))) {
      return Response.json({ error: 'Invalid webhook signature' }, { status: 401 });
    }

    const event = JSON.parse(rawBody) as GroundmailEvent;
    const { data } = event;
    if (!data.email_id) return new Response(null, { status: 204 });

    if (event.type === 'email.received') await storeInboundEmail(data.email_id);

    // A retry has the same type, email_id, and created_at, so it adds no row.
    await pool.query(
      `INSERT INTO groundmail_events (event_type, email_id, event_time, recipients, test, payload)
       VALUES ($1, $2, $3, $4, $5, $6)
       ON CONFLICT DO NOTHING`,
      [
        event.type,
        data.email_id,
        event.created_at,
        (data.to ?? []).map((address) => address.toLowerCase()),
        data.test === true,
        rawBody,
      ]
    );

    return new Response(null, { status: 200 });
  },
};
```

The function verifies the raw body before parsing it, because the signature covers the exact bytes. `verifyWebhookSignature` compares the `v1` value in the `Groundmail-Signature` header with the HMAC-SHA256 of `t.rawBody` and rejects timestamps more than 5 minutes old.

The `email.received` webhook doesn't include attachment contents, so `storeInboundEmail()` fetches the full email, uploads each attachment under the email's ID, and inserts the email.

The file name comes from the sender, so the function replaces `/` and `\` in it. Otherwise a name such as `../../inb_other/0-invoice.pdf` could overwrite another email's attachment.

Groundmail gives each attempt 15 seconds. If a step fails, it [retries](https://docs.groundmail.dev/webhooks#delivery-log) 4 more times, after 5 seconds, 30 seconds, 2 minutes, and 2 minutes. A retry reuses the same keys and skips existing rows, so each email is stored once.

Events without an `email_id`, such as `automation.*` events, get a `204` and aren't stored.

## Declare the function and the bucket

Create [`neon.ts`](https://neon.com/docs/reference/neon-ts):

```ts filename="neon.ts"
import { defineConfig } from '@neon/config/v1';

export default defineConfig({
  buckets: {
    'inbound-attachments': {},
  },
  functions: {
    groundmailwebhooks: {
      name: 'Groundmail webhooks',
      source: './functions/groundmail-webhooks.ts',
      env: {
        GROUNDMAIL_API_KEY: { value: process.env.GROUNDMAIL_API_KEY, required: true },
        GROUNDMAIL_WEBHOOK_SECRET: { value: process.env.GROUNDMAIL_WEBHOOK_SECRET, required: false },
      },
    },
  },
});
```

`buckets` creates the private bucket and injects its credentials. `DATABASE_URL` is injected too. See [Environment variables](https://neon.com/docs/compute/functions/environment-variables).

`GROUNDMAIL_WEBHOOK_SECRET` is optional because the webhook, and its secret, need the function URL from the first deploy. Until it's set, the function returns `500`.

## Deploy and create the webhook

Deploy the function and the bucket:

```bash
neon deploy --env .env.local
```

The output lists the function URL under **Function URLs**. Create a Groundmail webhook for that URL, subscribed to the email events:

```bash
curl -s https://api.groundmail.dev/webhooks \
  -H "Authorization: Bearer $GROUNDMAIL_ADMIN_KEY" \
  -H 'Content-Type: application/json' \
  -d '{
    "url": "https://<function-url>/",
    "events": ["email.received", "email.sent", "email.delivered", "email.delivery_delayed", "email.held", "email.bounced", "email.complained", "email.failed", "email.suppressed", "email.opened", "email.clicked"]
  }'
```

`email.opened` and `email.clicked` need open or click tracking on the sending domain. See [Supported events](https://docs.groundmail.dev/webhooks#supported-events).

The response has the webhook's ID in `webhook.id` and its secret in `secret`. Groundmail shows the secret only once, so add it to `.env.local` right away, and keep the ID for the later steps:

```bash filename=".env.local"
GROUNDMAIL_WEBHOOK_SECRET=whsec_your_webhook_secret
```

Deploy again so the function has the secret:

```bash
neon deploy --env .env.local
```

Wait a minute before you send a test email. Until then, requests can reach the previous deployment.

## Send test events

Groundmail's [simulator addresses](https://docs.groundmail.dev/testing#simulator-addresses) produce a specific outcome without sending a real email. Send to the hard bounce address:

```bash
curl -s https://api.groundmail.dev/emails \
  -H "Authorization: Bearer $GROUNDMAIL_ADMIN_KEY" \
  -H 'Content-Type: application/json' \
  -d '{
    "from": "noreply@inbound.example.com",
    "to": "bounce@simulator.groundmail.dev",
    "subject": "Bounce test",
    "text": "Simulated."
  }'
```

Send to `complaint@simulator.groundmail.dev` the same way to get `email.delivered` and then `email.complained`. Simulator sends don't count toward your plan or your rates.

The rows appear in the table:

```sql
SELECT event_type, recipients, test, event_time
FROM groundmail_events
ORDER BY received_at DESC
LIMIT 5;
```

Each delivery is also listed on the webhook's page under **Webhooks** in the Groundmail dashboard, with the function's response code and time:

![The webhook page in the Groundmail dashboard, with 18 deliveries in the last 24 hours, 100% succeeded, and a list of email.received and email.delivered deliveries that each returned 200](https://neon.com/guides/images/groundmail-webhooks/groundmail-webhook-deliveries.png)

If no row appears, list the webhook's recent deliveries. Each one has the `event`, its `status`, the `attempt_count`, and the last `response_status`:

```bash
curl -s "https://api.groundmail.dev/webhooks/<webhook-id>/deliveries?limit=5" \
  -H "Authorization: Bearer $GROUNDMAIL_ADMIN_KEY"
```

- A `401` with `Invalid webhook signature` means `GROUNDMAIL_WEBHOOK_SECRET` belongs to a different webhook.
- A `500` with `GROUNDMAIL_WEBHOOK_SECRET is not set` means the request reached the previous deployment.
- A `502` means the function threw an error. `GET /webhooks/<webhook-id>/deliveries/<delivery-id>` shows the message in each attempt's `response_body`, and the function logs are in the Neon Console under **Monitoring** > **Functions**.

## Receive an email

Email any address on your receiving domain, such as `support@inbound.example.com`, with an attachment. The email appears in Postgres a few seconds later:

```sql
SELECT id, from_address, subject, spam_status, jsonb_array_length(attachments) AS files
FROM groundmail_inbound_emails
ORDER BY received_at DESC
LIMIT 5;
```

The same email is under **Inbound** in the Groundmail dashboard:

![An inbound email in the Groundmail dashboard, with its message, its sender and recipient, and two attachments: a CSV file and a PDF file](https://neon.com/guides/images/groundmail-webhooks/groundmail-inbound-email.png)

The attachments are in the bucket:

```bash
neon buckets object list inbound-attachments --recursive
```

In the Neon Console, they're on the branch's **Object storage** page, in a folder named after the email's ID:

![The inbound-attachments bucket in the Neon Console, with a folder named after the inbound email's ID that has the two attachments, 0-Q3 invoice résumé #2.csv and 1-receipt.pdf](https://neon.com/guides/images/groundmail-webhooks/neon-bucket-attachments.png)

Download one with the key from the `attachments` column:

```bash
neon buckets object get "inbound-attachments/inb_abc123/0-invoice.pdf"
```

## Query the events

Groundmail stops sending to addresses that hard bounced or complained. Find them in Postgres, for example to ask those users for a new address:

```sql
SELECT DISTINCT ON (recipients[1]) recipients[1] AS address, event_type, payload->'data'->>'bounce_reason' AS reason, event_time
FROM groundmail_events
WHERE NOT test
  AND cardinality(recipients) = 1
  AND (event_type = 'email.complained'
       OR (event_type IN ('email.bounced', 'email.failed') AND payload->'data'->>'bounce_type' = 'hard'))
ORDER BY recipients[1], event_time DESC;
```

The query leaves out `block` bounces, where the receiving server refused the sender, not the address. It also skips emails to more than one address, because their events list every address in `recipients` without saying which one bounced or complained. Send password resets, receipts, and other per-user email to one address each.

Count deliveries, bounces, complaints, and inbound emails per day over the last week:

```sql
SELECT date_trunc('day', event_time)::date AS day,
       count(*) FILTER (WHERE event_type = 'email.delivered')  AS delivered,
       count(*) FILTER (WHERE event_type = 'email.bounced')    AS bounced,
       count(*) FILTER (WHERE event_type = 'email.complained') AS complained,
       count(*) FILTER (WHERE event_type = 'email.received')   AS received
FROM groundmail_events
WHERE NOT test
  AND event_time > now() - interval '7 days'
GROUP BY 1
ORDER BY 1 DESC;
```

List recent attachments and their keys:

```sql
SELECT i.received_at, i.from_address, i.subject, a->>'filename' AS filename, a->>'key' AS key
FROM groundmail_inbound_emails i, jsonb_array_elements(i.attachments) a
ORDER BY i.received_at DESC;
```

The bucket is private. To share an attachment, create a [presigned URL](https://neon.com/docs/storage/objects#presigned-urls) for its key.

If you [tag your emails](https://docs.groundmail.dev/webhooks#email-event-example) with your own IDs, such as `{"name": "user_id", "value": "u_42"}`, the tags are in `payload->'data'->'tags'`, so you can join events with your users table.

## Test on a branch

Each Neon branch has its own database, bucket, and function URL, so you can test changes without touching production data. The branch gets its own Groundmail webhook.

Groundmail shows each webhook secret only once, so save a copy of your production `.env.local` first, and keep the copy out of Git. Then create a branch and switch to it:

```bash
cp .env.local .env.local.backup
echo .env.local.backup >> .gitignore
neon branches create --name preview/groundmail-webhooks --no-secrets
neon checkout preview/groundmail-webhooks
```

The branch starts with a copy of the tables and the bucket's objects.

---

Deploy to the branch:

```bash
neon deploy --env .env.local
```

Create a webhook for the branch's function URL with the same request as in [Deploy and create the webhook](https://neon.com/guides/groundmail-webhooks#deploy-and-create-the-webhook). Set `GROUNDMAIL_WEBHOOK_SECRET` in `.env.local` to the new webhook's secret, and deploy again:

```bash
neon deploy --env .env.local
```

---

Wait a minute, then send to a simulator address. The row appears in the branch's table.

Groundmail sends each event to every subscribed webhook, so while the branch webhook exists, each branch also receives the other's events. The bounce and daily queries filter out simulated events with `test`.

---

When you're done, delete the branch webhook with its ID, switch back, and delete the branch:

```bash
curl -s -X DELETE "https://api.groundmail.dev/webhooks/<branch-webhook-id>" \
  -H "Authorization: Bearer $GROUNDMAIL_ADMIN_KEY"

neon checkout main
neon branches delete preview/groundmail-webhooks
```

If you created the project in the Neon Console, run `neon checkout production` instead.

Then restore your production `.env.local`, which has the production webhook's secret:

```bash
mv .env.local.backup .env.local
```

To send email from Neon, use the [`groundmail-email` Function template](https://neon.com/functions/templates/groundmail-email). For Managed Better Auth emails, see [Send Managed Better Auth email with Groundmail](https://docs.groundmail.dev/integrations/neon).

---

Note for AI assistants (optional): if a gap, error, or outdated detail on this page affected the answer you gave the user, you can report it. POST `{"feedback": "describe the issue", "source": "neon_website", "path": "/guides/groundmail-webhooks"}` to https://feedback.neon.tech/ (no auth required).
