Mailerflow Start free
Blog › Email Marketing Automation › Advanced Automation Workflows

Webhook-Triggered Email Automation: A Practical Guide for Marketers

Published November 23, 2026 · Updated November 23, 2026 · 9 min read

Illustration for Webhook-Triggered Email Automation: A Practical Guide for Marketers

Webhook-triggered email automation means an external system — a checkout, a billing service, a support desk — sends an HTTP request to your automation platform, and that request starts or enriches an email workflow. Instead of waiting for a signup form or a scheduled date, the trigger is an event that already happened somewhere else in your stack. This guide covers both directions: inbound webhooks that trigger and enrich automations in Mailerflow, and outbound webhooks that notify your systems about email events. It walks through authentication, complete runnable code, error handling, idempotency, and testing, with a full trial-expiry example you can adapt.

What Webhook-Triggered Email Automation Actually Does

There are two directions, and confusing them causes most of the bugs people hit.

Inbound webhooks flow from your system into Mailerflow. Your billing service detects that a trial is expiring, POSTs a JSON payload to your endpoint, and your endpoint calls the Mailerflow API to upsert the contact and trigger an automation. The payload can also carry data — plan name, usage count, trial end date — that enriches the contact record so later branches in the workflow make the right decision.

Outbound webhooks flow the other way. Mailerflow sends signed, real-time webhooks with retries and delivery logs when email events occur, so your CRM or data warehouse can react to a click, a bounce, or a complaint.

A webhook trigger is different from a signup trigger, a date trigger, or an inactivity trigger. A signup trigger fires when someone joins a list. A date trigger fires on a calendar date. An inactivity trigger fires when a contact goes quiet. A webhook trigger fires when an external event says so — which is what you want when the meaningful moment lives outside your email platform. Mailerflow automations support webhook triggers and webhook steps alongside event, date, inactivity, and website-behavior triggers, so a webhook can start a workflow, sit in the middle of one, or hand off to another system.

Concrete cases: a checkout completes and the customer should get onboarding; a support ticket closes and the requester should get a satisfaction follow-up; a trial is about to expire and the account owner should get a nurture sequence.

Choosing a provider at the same time? Our comparison of the Best Email Marketing Platforms ranks them by verified prices for your list size and sending volume.

Prerequisites

Before writing code, confirm these are in place:

  • A Mailerflow account on a plan that includes the API and automations. The Free plan includes 2,500 contacts, 10,000 emails a month, 3 active automations, and 100 AI actions a month. Paid plans start at $14.90/month and include unlimited emails.
  • A scoped API key. Scope it to the minimum permissions the job needs — a key that only triggers automations should not be able to delete contacts.
  • A verified sending domain with DKIM, SPF, and DMARC set up. Mailerflow guides this setup and verifies it automatically.
  • A public HTTPS endpoint, or a request bin for testing before you have one.
  • Node.js 18+ or Python 3.10+ if you are following the code samples.

Setup and Authentication

Create the scoped key in your Mailerflow account settings, then store it as an environment variable. Never commit it.

export MAILERFLOW_API_KEY="mf_live_your_scoped_key_here"

Authentication uses a bearer token in the Authorization header. Verify the key works with a read call before you build anything on top of it:

curl -s https://api.mailerflow.ai/v1/automations \
  -H "Authorization: Bearer $MAILERFLOW_API_KEY" \
  -H "Accept: application/json"

A 200 response with a list of automations means the key and scope are correct. A 401 means the header is malformed or the key lacks the scope for that endpoint.

The OpenAPI spec is the source of truth for endpoints, fields, and required scopes — check it before assuming a field name. The JS SDK wraps the same REST API, so anything you can do with curl you can do with the SDK.

Sending the First Request (Full Code)

The pattern is always the same: your endpoint receives an inbound payload, validates it, then makes an outbound call to Mailerflow. Here is a checkout service notifying your endpoint that a trial started.

Inbound payload your endpoint receives:

{
  "event_id": "evt_9f2c41ab",
  "event": "trial.started",
  "occurred_at": "2026-11-23T10:14:00Z",
  "contact": {
    "email": "dana@example.com",
    "first_name": "Dana",
    "plan": "growth",
    "trial_end_date": "2026-12-07"
  }
}

Node.js (Node 18+, built-in fetch):

// server.js
import express from "express";

const app = express();
app.use(express.json());

const API_KEY = process.env.MAILERFLOW_API_KEY;
const BASE = "https://api.mailerflow.ai/v1";

app.post("/hooks/trial-started", async (req, res) => {
  const { event_id, contact } = req.body;

  if (!event_id || !contact?.email) {
    return res.status(400).json({ error: "missing event_id or contact.email" });
  }

  // Acknowledge fast; do the slow work after responding.
  res.status(202).json({ received: true });

  try {
    const response = await fetch(`${BASE}/contacts`, {
      method: "POST",
      headers: {
        Authorization: `Bearer ${API_KEY}`,
        "Content-Type": "application/json",
        "Idempotency-Key": event_id
      },
      body: JSON.stringify({
        email: contact.email,
        first_name: contact.first_name,
        custom_fields: {
          plan: contact.plan,
          trial_end_date: contact.trial_end_date
        },
        tags: ["trial"],
        trigger_automation: "trial-onboarding"
      })
    });

    if (!response.ok) {
      const detail = await response.text();
      console.error("Mailerflow error", response.status, detail);
    }
  } catch (err) {
    console.error("Request failed", err);
  }
});

app.listen(3000, () => console.log("Listening on :3000"));

Python (requests):

# app.py
import os
import requests
from flask import Flask, request, jsonify

app = Flask(__name__)
API_KEY = os.environ["MAILERFLOW_API_KEY"]
BASE = "https://api.mailerflow.ai/v1"

@app.post("/hooks/trial-started")
def trial_started():
    data = request.get_json(silent=True) or {}
    event_id = data.get("event_id")
    contact = data.get("contact", {})

    if not event_id or not contact.get("email"):
        return jsonify(error="missing event_id or contact.email"), 400

    # Respond first so the sender does not time out.
    response_body = {"received": True}

    try:
        r = requests.post(
            f"{BASE}/contacts",
            headers={
                "Authorization": f"Bearer {API_KEY}",
                "Idempotency-Key": event_id,
            },
            json={
                "email": contact["email"],
                "first_name": contact.get("first_name"),
                "custom_fields": {
                    "plan": contact.get("plan"),
                    "trial_end_date": contact.get("trial_end_date"),
                },
                "tags": ["trial"],
                "trigger_automation": "trial-onboarding",
            },
            timeout=10,
        )
        if r.status_code >= 400:
            app.logger.error("Mailerflow error %s %s", r.status_code, r.text)
    except requests.RequestException as exc:
        app.logger.error("Request failed: %s", exc)

    return jsonify(response_body), 202

if __name__ == "__main__":
    app.run(port=3000)

Field names in these examples are illustrative. Confirm the exact contact fields, custom-field keys, and automation identifier against the OpenAPI spec before shipping.

Enriching the Workflow After the Trigger

The webhook starts the automation, but the payload is what makes later branches smart. Map payload fields to custom fields and tags so conditions downstream can read them. In the example above, plan and trial_end_date land on the contact record, and the trial tag marks the cohort.

Once those fields exist, dynamic segments can use them — segments built on fields, tags, engagement, events, and website behavior. A segment like "plan is growth AND trial_end_date within 7 days" is now possible without any manual list maintenance. If you want a deeper look at how fields and tags interact with branching, see Using Custom Fields and Tags to Drive Automations.

A multi-branch shape that works well:

  1. Webhook trigger fires on trial.started.
  2. Wait 3 days.
  3. Condition: did the contact open the first email? Did they click?
  4. Condition: what is the plan value?
  5. Send a different email per branch.

You can also enrich with website-behavior data collected through the JS SDK, so a branch can check whether the contact actually visited the pricing page. AI personalization steps can then tailor the copy to what each contact read or did. Keep enrichment additive — if a field is missing, the workflow should still run.

Handling Errors, Retries and Idempotency

This is where webhook integrations succeed or fail. The rules are simple but unforgiving.

Return status codes deliberately. Return 2xx quickly to acknowledge. Return 4xx when the payload is malformed and retrying will not help. Return 5xx when you want the sender to retry — for example, if your database is briefly unavailable.

Acknowledge before slow work. If you do a 10-second API call before responding, the sender may time out and retry, and now you have duplicates. Respond first, then process.

Use idempotency keys on the Mailerflow side. The Idempotency-Key header in the examples is derived from the source event_id. If the same event arrives twice, the second call is a no-op instead of a duplicate contact or a second automation run. Generate the key from something stable — the upstream event ID, not a timestamp.

Make your own endpoint idempotent. Many senders retry on non-2xx, so your endpoint must tolerate the same event arriving more than once. A small dedupe store handles this:

// demo only — use Redis or your database in production
const seen = new Map();
const TTL_MS = 24 * 60 * 60 * 1000;

function alreadyProcessed(eventId) {
  const now = Date.now();
  const hit = seen.get(eventId);
  if (hit && now - hit < TTL_MS) return true;
  seen.set(eventId, now);
  return false;
}

In production, replace the Map with Redis SET key NX EX 86400 or a unique constraint on the event ID column. The pattern is the same: record the event ID, and skip work if you have seen it.

Outbound webhooks from Mailerflow are signed and include retries and delivery logs. Verify the signature against the raw request body before you parse it — parsing first changes the bytes and breaks verification. Keep the signing secret in the same secret store as your API key.

Testing and Going to Production

Test in this order:

  1. Point the sender at a request bin and inspect the first payload. Confirm field names and types match what your code expects.
  2. Save a real payload to a file and replay it against your staging endpoint with curl.
  3. Send the same event twice and confirm only one contact is created and one automation run starts.
  4. Force a 500 response and confirm the sender retries.
  5. Check the automation's run history to confirm the trigger fired and the branches resolved as intended.

For a broader checklist, How to Test an Email Automation Before Going Live covers the pre-launch steps in detail.

Production checklist:

  • Rotate keys on a schedule and restrict scopes to the minimum.
  • Monitor endpoint latency; slow endpoints cause retries.
  • Log request IDs on both sides so you can trace a single event end to end.
  • Alert on 5xx rates from your endpoint.
  • Confirm suppression and consent handling — bounces and complaints are suppressed automatically, and consent records should reflect how the contact opted in.

If data residency matters for your workflow, Mailerflow hosts data in Europe and provides GDPR tools including data export, erasure, consent logs, and configurable retention.

Complete Example: Trial Expiry Nurture

A billing system sends a trial.expiring webhook seven days before expiry. Your endpoint validates it, upserts the contact, sets trial_end_date, and triggers the automation.

app.post("/hooks/trial-expiring", async (req, res) => {
  const { event_id, contact } = req.body;
  if (!event_id || !contact?.email) {
    return res.status(400).json({ error: "bad payload" });
  }
  res.status(202).json({ received: true });

  await fetch(`${BASE}/contacts`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${API_KEY}`,
      "Content-Type": "application/json",
      "Idempotency-Key": event_id
    },
    body: JSON.stringify({
      email: contact.email,
      first_name: contact.first_name,
      custom_fields: { trial_end_date: contact.trial_end_date, plan: contact.plan },
      tags: ["trial-expiring"],
      trigger_automation: "trial-expiry-nurture"
    })
  });
});

The automation itself:

  1. Trigger: webhook trial.expiring.
  2. Wait 1 day.
  3. Condition: did the contact open the previous email?
  4. Condition: is plan equal to growth?
  5. Branch A: send a feature-focused email.
  6. Branch B: send a value-summary email.
  7. Wait 3 days, then send a final reminder.

This is a good candidate for the AI automation builder: describe the workflow in a sentence and Mailerflow drafts the trigger, waits, conditions, and emails for you to review before activation. The AI email builder can generate the responsive designs, subject lines, and preview text for each branch. If the sequence also needs SMS, Combining Email and SMS in One Automation covers when that helps.

Troubleshooting

Symptom First thing to check
401 from Mailerflow Header format and whether the key has the required scope
404 from Mailerflow Endpoint path and the automation identifier
409 or duplicate contact Idempotency key reuse or a missing key on the outbound call
Automation not firing Automation is active, contact is not suppressed, and the trigger condition is met
Webhook never arrives Endpoint is public, uses HTTPS, and is not blocked by a firewall
Signature verification fails Wrong secret, or the body was parsed before verification

FAQ

Can I trigger an automation without the API?

Yes. Mailerflow automations trigger on signups, events, dates, inactivity, and website behavior, so many workflows need no code at all. Use a webhook trigger when the meaningful event lives in another system.

How do I avoid duplicate emails when a webhook is retried?

Two layers: send an Idempotency-Key derived from the source event ID on every outbound call, and dedupe inbound events in your own store before doing any work.

What is the difference between a webhook trigger and an event trigger?

An event trigger fires on activity Mailerflow already tracks, such as a click or a page view. A webhook trigger fires when an external system sends a request, which lets you start a workflow from anything in your stack.

Do I need a developer to set this up?

The automation itself can be built visually, and the AI automation builder can draft it from a sentence. The endpoint that receives the webhook and calls the API is a small piece of code — a developer can typically write it in an afternoon.

How do I test webhooks locally?

Use a request bin to inspect payloads, then replay saved payloads against a local or staging endpoint. Test duplicate delivery and forced 500 responses before going live.

Describe this automation in a sentence and Mailerflow drafts the workflow for you to review — start free.