> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mailofly.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Send Automated Emails with Supabase Database Triggers

> Learn how to dispatch transactional emails automatically when new rows are inserted or updated in your Supabase PostgreSQL database.

# Automated Emails with Supabase Database Triggers

Learn how to connect your Supabase database to Mailofly and send personalized transactional emails instantly whenever a new record is inserted or modified—without writing background workers or managing queue servers.

***

## The Problem It Solves

In standard web architectures, sending transactional emails when something happens in your database (like a user registering, subscribing to a plan, or placing an order) typically requires:

* Setting up a queue system like BullMQ, Celery, or AWS SQS.
* Running separate worker processes or Docker containers.
* Deploying serverless Edge Functions and managing webhooks.
* Handling connection retries and dead-letter queues.

### How Mailofly Helps

With Mailofly's native Supabase integration:

* **Zero infrastructure**: Dispatches emails straight from PostgreSQL using the native `pg_net` extension.
* **Instant, sub-second delivery**: Triggers fire the millisecond your database transaction commits.
* **Non-blocking execution**: Uses asynchronous HTTP requests so your database queries and application response times are never slowed down.
* **Automatic column mapping**: All row columns (`name`, `plan`, `amount`, etc.) are automatically passed into your template's merge variables.
* **Built-in HMAC security**: Payloads are cryptographically signed using `pgcrypto` to prevent tampering.

***

## How It Works

```mermaid theme={null}
sequenceDiagram
    autonumber
    actor User as App User
    participant App as Your Web / Mobile App
    participant DB as Supabase PostgreSQL
    participant MF as Mailofly Engine
    actor Inbox as Customer Inbox

    User->>App: Submits signup or checkout form
    App->>DB: INSERT INTO subscribers (name, email, plan)
    Note over DB: Transaction commits
    DB-->>App: 201 Created (Instant response)
    DB-)MF: net.http_post() with HMAC-SHA256 signature
    Note over MF: Verify HMAC signature & render template
    MF->>Inbox: Delivers branded email to recipient
    MF-->>DB: Increments delivery count in Mailofly dashboard
```

1. **Application Event**: A user interacts with your app, triggering an `INSERT` or `UPDATE` into your Supabase database table.
2. **PostgreSQL Trigger**: An `AFTER INSERT OR UPDATE` trigger installed by Mailofly packages the row data into JSON.
3. **Async HTTP Request**: The `pg_net` extension sends an asynchronous HTTP POST request to Mailofly's webhook endpoint.
4. **Signature Verification & Rendering**: Mailofly validates the HMAC-SHA256 signature, extracts the recipient's email address from your designated column, populates template variables (`{{name}}`, `{{plan}}`), and delivers the message.

***

## Step-by-Step Tutorial

### Step 1: Create Your Supabase Table

If you don't already have a table, create one in your Supabase SQL Editor. Here is an example `subscribers` table:

```sql theme={null}
CREATE TABLE public.subscribers (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  name text NOT NULL,
  email text NOT NULL,
  plan text NOT NULL DEFAULT 'Free',
  created_at timestamptz DEFAULT now()
);
```

Make sure row-level security (RLS) or public policies suit your app's access patterns.

***

### Step 2: Prepare Your Email Template in Mailofly

1. In the Mailofly dashboard, go to **[Templates](https://www.mailofly.com/user/templates)** and click **Create Template**.
2. Give your template a name (e.g. `Welcome Subscriber`).
3. Add subject line: `Welcome to our platform, {{name}}!`
4. Write your HTML content using merge tags that correspond to your table's columns:

```html theme={null}
<div style="font-family: sans-serif; max-width: 600px; margin: 0 auto;">
  <h2>Welcome to the team, {{name}}! 👋</h2>
  <p>Thank you for subscribing to our <strong>{{plan}}</strong> plan.</p>
  <p>We're thrilled to have you on board. If you have any questions, simply reply directly to this email.</p>
  <br />
  <p>Cheers,<br />The Mailofly Team</p>
</div>
```

5. Click **Save Template**.

***

### Step 3: Connect Supabase in Mailofly

1. In Mailofly, navigate to **[Integrations](https://www.mailofly.com/user/integrations)**.
2. Select the **Supabase** card.
3. Click **Connect with Supabase**.
4. In the Supabase OAuth authorization window, select your organization and project, then click **Authorize**.

***

### Step 4: Create the Database Trigger

1. In the Supabase integration view in Mailofly, click **Add Trigger**.
2. Configure the trigger parameters:
   * **Project**: Select your connected Supabase project.
   * **Table**: Select `public.subscribers`.
   * **Event**: Choose `INSERT` (to fire on new signups) or `UPDATE` (for status updates).
   * **Recipient Column**: Select `email`.
   * **Email Template**: Select the `Welcome Subscriber` template you created in Step 2.
3. Click **Create Trigger**.

Mailofly immediately deploys the trigger function and database hook into your Supabase database schema.

***

### Step 5: Test the Integration

Test the trigger by inserting a test record directly in the Supabase SQL Editor:

```sql theme={null}
INSERT INTO public.subscribers (name, email, plan)
VALUES ('Alex Rivers', 'you@example.com', 'Enterprise Pro');
```

Within 1-3 seconds:

1. Check `you@example.com`—your personalized welcome email will arrive with `Alex Rivers` and `Enterprise Pro` populated.
2. In Mailofly, view the **Integrations** page to see the trigger's **Emails sent** count increment.
3. Inspect detailed delivery status, open rates, and click tracking in the **[Logs](https://www.mailofly.com/user/logs)** tab.

***

## Verifying in PostgreSQL

To inspect the background HTTP request made by Supabase, run this query in your Supabase SQL Editor:

```sql theme={null}
SELECT id, status_code, url, error_msg, created
FROM net._http_response
ORDER BY id DESC
LIMIT 5;
```

A `status_code` of `200` confirms that Mailofly accepted and queued the email for immediate delivery.

***

## Pro Tips & Best Practices

<Tip>
  **Matching Column Names:**
  Column names in your Supabase table map 1:1 to template tags. If your table column is `company_name`, use `{{company_name}}` in your email template.
</Tip>

<Info>
  **Non-Blocking Reliability:**
  Because `pg_net` executes outside the main PostgreSQL transaction worker, even if an email network timeout occurs, your user's database insert will never fail or roll back.
</Info>

***

## Next Steps

* [Supabase Integration Reference](../../integrations/supabase) — Technical specifications, cryptographic signing details, and extension requirements.
* [Template Variables & Personalization](../../templates/template-variables) — Learn about formatting dates, fallback values, and conditionals.
* [Custom Domains Setup](../../domains/introduction) — Connect your own sending domain for maximum inbox deliverability.


## Related topics

- [Supabase Database Triggers](/integrations/supabase.md)
- [Integrations](/integrations/index.md)
- [Supabase](/smtp/supabase.md)
- [Supabase Quickstart](/guides/tutorials/supabase-quickstart.md)
- [Introduction](/sending/introduction.md)
