How to Receive Email with a Webhook: Inbound Email to Your HTTP Endpoint

Receive email with a webhook: get inbound email events at your HTTPS endpoint, verify the signature, fetch and parse the message, dedupe and retry safely.

By · · 17 min read

TypeScript code from this guide, in webhook.ts, sending or reading email with Mailcycle

You want to receive email with a webhook: when someone writes to your support address, your orders address or an agent’s inbox, your server should hear about it at once, as an HTTP request, instead of logging in to a mailbox every minute to check. An inbound email webhook does exactly that: it turns each incoming message into a signed POST to an endpoint you own.

This tutorial builds an email to webhook pipeline with Mailcycle, end to end, in TypeScript (Express and Next.js) and Python (FastAPI). You’ll add the webhook, verify its signature, fetch and parse the incoming email with the SDK, deduplicate retries, answer fast and process in the background, and test it all on your laptop. At the end there’s a comparison of webhooks, polling, the event stream and IMAP, so you can pick the right one for each job.

The code is type-checked against the SDK sources, and both endpoints were run against a fake API with signed sample deliveries, so the method names and arguments are the real ones.

Quick answer: how to receive email with a webhook

Add a webhook for the message.received event with an HTTPS URL. When mail arrives, Mailcycle sends a signed JSON POST with the message id. Your endpoint checks the Mailcycle-Signature header against the raw body, records the event id, answers 204 within 10 seconds, then fetches the message by id with the SDK, which decrypts and parses it.

const valid = await verifyWebhookSignature(secret, rawBody, req.get('Mailcycle-Signature'));
if (!valid) { res.status(401).end(); return; }

const event = JSON.parse(rawBody);           // { id, type, createdAt, payload: { messageId, inboxId } }
res.status(204).end();                        // answer first
const message = await mc.messages.get(event.payload.messageId); // then fetch and open it
console.log(message.from, message.subject, message.text);

The rest of this guide turns those lines into a handler you can run in production.

How an inbound email webhook works

Some inbound email services parse each message and post the whole thing, headers, body and attachments, to your URL. Mailcycle works differently, because mail is encrypted when it arrives and only your recovery phrase opens it (see Encryption). The flow is:

  1. Mail reaches one of your addresses. Mailcycle seals it to that address’s public key and stores it.
  2. Mailcycle sends your webhook a small event: message.received, with the messageId and inboxId. No subject, no sender, no body.
  3. Your endpoint verifies the signature, stores the event and answers 2xx.
  4. Your code calls the API for that message. The SDK opens it on your machine and hands you the parsed fields: sender, subject, text, safe HTML and attachments.

Because events carry ids, never content, a webhook log, a load balancer’s request log or a tunnel’s inspector never holds anyone’s email. The event says no more than the account’s activity log already does.

Flow: a sender writes to your address, Mailcycle encrypts the mail on arrival, posts a signed webhook to your HTTPS endpoint, and your code verifies the signature and fetches the message
New mail is encrypted on arrival, then Mailcycle posts a signed event to your endpoint, which fetches the message.

Prerequisites

  • A Mailcycle account on Operator or above. Webhooks start at Operator, and so do API keys. The free 7-day Scale trial includes both, with no card: start it under Plans & Billing in the web app. Replying from your handler with an API key needs Scale.
  • An address that receives mail. Create one in the app, or with the SDK as in the email addresses guide.
  • An API key and your recovery phrase on the server. The key (mak_…) authenticates; the phrase lets the SDK decrypt what arrives. Keep both in your secret store.
  • A public HTTPS URL, or a tunnel to your laptop while you develop (covered below).
  • Node.js 22+ with npm install mailcycle-sdk express, or Python 3.10+ with pip install mailcycle fastapi uvicorn.

Step 1: Add a webhook for incoming email

The quickest way is the app: open API, choose the Webhooks tab, add your URL and pick message.received. The response shows the signing secret, which starts whsec_, once. Copy it into your environment as MAILCYCLE_WEBHOOK_SECRET.

You can also do it in code. Adding, changing and removing a webhook needs a signed-in session rather than an API key (an API key can’t add a URL that would outlive the key), so a setup script signs in with the phrase:

import { Mailcycle } from 'mailcycle-sdk';

// Adding a webhook needs a signed-in session, so sign in with the phrase.
const mc = await Mailcycle.signIn({ phrase: process.env.MAILCYCLE_PHRASE! });

const { webhook, secret } = await mc.webhooks.create({
  url: 'https://hooks.example.com/webhooks/mailcycle',
  events: ['message.received'],
  name: 'Inbound mail',
});
console.log(webhook.id);
console.log(secret); // whsec_…, shown once: store it now

await mc.webhooks.test(webhook.id); // sends a webhook.test event

The same in Python:

import os

from mailcycle import Mailcycle

# Adding a webhook needs a signed-in session, so sign in with the phrase.
mc = Mailcycle.sign_in(os.environ["MAILCYCLE_PHRASE"])

created = mc.webhooks.create(
    "https://hooks.example.com/webhooks/mailcycle",
    ["message.received"],
    "Inbound mail",
)
print(created.webhook.id)
print(created.secret)  # whsec_..., shown once: store it now

mc.webhooks.test(created.webhook.id)  # sends a webhook.test event

Under the hood that’s POST /webhook-endpoints; the webhooks reference lists every endpoint. A few rules worth knowing up front:

  • The URL must be HTTPS with a hostname. IP addresses, localhost, *.local and Mailcycle’s own domains are refused, and redirects are not followed.
  • An account can hold 10 webhooks. Use ["*"] as events to get every event type.
  • The webhook’s name is sealed on your machine like everything else private. The URL can’t be, because Mailcycle has to call it.

Step 2: Know what the incoming email webhook sends

Every delivery is a POST with Content-Type: application/json and a body like this:

{
  "id": "evt_4k2m9x7q1b8c3v6n0z5a",
  "type": "message.received",
  "createdAt": "2026-09-19T09:14:03.000Z",
  "payload": { "messageId": "msg_91be02c4a7d1", "inboxId": "ibx_k3v9x2mq7a" }
}

With these headers:

Header Value
Mailcycle-Signature t=<unix seconds>,v1=<hex HMAC-SHA256>
Mailcycle-Event-Id The event id. The same on every attempt and redelivery.
Mailcycle-Event-Type The event type.
Mailcycle-Delivery-Id This delivery, whd_….
User-Agent Mailcycle-Webhooks/1

For receiving email, message.received is the one you need. The others are useful if you subscribe to more:

Event Fires when Payload
message.received Mail arrives at an address messageId, inboxId
message.sent Mail is sent from an address messageId (the Sent copy, or null), inboxId, via
inbox.created / inbox.deleted An address is created or deleted inboxId
webhook.test You send a test webhookId

The full list, including device events and subscription.updated, is in the webhooks guide. Whatever you subscribe to, handle unknown types by answering 2xx and ignoring them, so a new event type never turns into a retry storm.

Step 3: Verify the webhook signature

Anyone can POST to a public URL, so the first thing your handler does is prove the request came from Mailcycle. The signature is an HMAC-SHA256, in hex, of the timestamp, a full stop and the raw body, keyed with your whsec_ secret. Every Mailcycle SDK has a helper that checks it in constant time and refuses a timestamp more than five minutes old, which stops an old delivery being replayed.

The one rule that catches people out: verify the raw bytes, before any JSON parsing. A body that has been parsed and serialised again is a different string, and it won’t verify.

TypeScript: an Express webhook endpoint

First, a client the whole process shares, and a small helper for spotting repeat deliveries:

// lib/mailcycle.ts
import { Mailcycle } from 'mailcycle-sdk';

let client: Promise<Mailcycle> | undefined;

/** One client per process. The phrase lets it open (decrypt) mail on this machine. */
export function mailcycle(): Promise<Mailcycle> {
  client ??= Mailcycle.withApiKey({
    apiKey: process.env.MAILCYCLE_API_KEY!,
    phrase: process.env.MAILCYCLE_PHRASE!,
  }).catch((error: unknown) => {
    client = undefined; // let the next call try again
    throw error;
  });
  return client;
}
// lib/events.ts
/** The body of every Mailcycle webhook delivery. */
export interface MailcycleEvent {
  id: string; // evt_…, the same on every retry
  type: string; // message.received, inbox.created, webhook.test, …
  createdAt: string;
  payload: Record<string, unknown>;
}

const seen = new Map<string, number>();
const DAY_MS = 24 * 60 * 60 * 1000;

/**
 * True the first time an event id is seen. In-memory, for one process:
 * in production, use a unique key in your database or queue instead.
 */
export function firstDelivery(eventId: string): boolean {
  const now = Date.now();
  for (const [id, at] of seen) if (now - at > 3 * DAY_MS) seen.delete(id);
  if (seen.has(eventId)) return false;
  seen.set(eventId, now);
  return true;
}

Then the endpoint. express.text({ type: 'application/json' }) on this one route keeps the body as the exact string Mailcycle signed:

// server.ts
import express from 'express';
import { verifyWebhookSignature } from 'mailcycle-sdk';
import { firstDelivery, type MailcycleEvent } from './lib/events';
import { handleEvent } from './lib/handle-mail';

const app = express();

app.post('/webhooks/mailcycle', express.text({ type: 'application/json' }), async (req, res) => {
  const rawBody = typeof req.body === 'string' ? req.body : ''; // the exact text, not parsed JSON

  const valid = await verifyWebhookSignature(
    process.env.MAILCYCLE_WEBHOOK_SECRET!,
    rawBody,
    req.get('Mailcycle-Signature'),
  );
  if (!valid) {
    res.status(401).send('Bad signature');
    return;
  }

  const event = JSON.parse(rawBody) as MailcycleEvent;
  if (firstDelivery(event.id)) {
    // Answer first, work after: Mailcycle waits 10 seconds at most.
    setImmediate(() => handleEvent(event).catch((error) => console.error(event.id, error)));
  }
  res.status(204).end();
});

app.listen(3000, () => console.log('Listening on http://localhost:3000'));

A repeat delivery still gets a 204: it was handled the first time, and answering with an error would only make Mailcycle try again.

TypeScript: a Next.js route handler

In the App Router, request.text() gives you the raw body, and after() runs work once the response has gone:

// app/api/webhooks/mailcycle/route.ts
import { after } from 'next/server';
import { verifyWebhookSignature } from 'mailcycle-sdk';
import { firstDelivery, type MailcycleEvent } from '@/lib/events';
import { handleEvent } from '@/lib/handle-mail';

export const runtime = 'nodejs';

export async function POST(request: Request) {
  const rawBody = await request.text(); // read it once, as text
  const valid = await verifyWebhookSignature(
    process.env.MAILCYCLE_WEBHOOK_SECRET!,
    rawBody,
    request.headers.get('Mailcycle-Signature'),
  );
  if (!valid) return new Response('Bad signature', { status: 401 });

  const event = JSON.parse(rawBody) as MailcycleEvent;
  if (firstDelivery(event.id)) after(() => handleEvent(event));
  return new Response(null, { status: 204 });
}

On serverless hosting, an in-memory set doesn’t survive between invocations, so swap firstDelivery for a database check as described in step 5.

Python: a FastAPI webhook endpoint

The Python version stores each event in a table keyed on its id. That one insert does two jobs: it deduplicates, and it keeps the event safe if the process dies before it’s processed. SQLite keeps the example self-contained; the same statement works in Postgres with ON CONFLICT DO NOTHING.

# inbound/store.py
import os
import sqlite3

DB_PATH = os.environ.get("WEBHOOK_DB", "webhooks.db")


def connect() -> sqlite3.Connection:
    conn = sqlite3.connect(DB_PATH)
    conn.execute(
        """CREATE TABLE IF NOT EXISTS webhook_events (
             id TEXT PRIMARY KEY,            -- Mailcycle-Event-Id: the same on every retry
             type TEXT NOT NULL,
             body TEXT NOT NULL,
             processed_at TEXT
           )"""
    )
    return conn


def save_event(event_id: str, event_type: str, raw_body: str) -> bool:
    """Stores the event once. False if this event id was seen before."""
    with connect() as conn:
        cursor = conn.execute(
            "INSERT OR IGNORE INTO webhook_events (id, type, body) VALUES (?, ?, ?)",
            (event_id, event_type, raw_body),
        )
        return cursor.rowcount == 1


def pending_body(event_id: str) -> str | None:
    with connect() as conn:
        row = conn.execute(
            "SELECT body FROM webhook_events WHERE id = ? AND processed_at IS NULL", (event_id,)
        ).fetchone()
    return row[0] if row else None


def pending_ids() -> list[str]:
    with connect() as conn:
        return [row[0] for row in conn.execute("SELECT id FROM webhook_events WHERE processed_at IS NULL")]


def mark_processed(event_id: str) -> None:
    with connect() as conn:
        conn.execute("UPDATE webhook_events SET processed_at = datetime('now') WHERE id = ?", (event_id,))
# inbound/app.py
import json
import os

from fastapi import BackgroundTasks, FastAPI, HTTPException, Request, Response
from mailcycle import verify_webhook_signature

from .store import save_event
from .worker import process_event

WEBHOOK_SECRET = os.environ["MAILCYCLE_WEBHOOK_SECRET"]  # whsec_...

app = FastAPI()


@app.post("/webhooks/mailcycle", status_code=204)
async def mailcycle_webhook(request: Request, background: BackgroundTasks) -> Response:
    raw_body = await request.body()  # the exact bytes, before any parsing

    if not verify_webhook_signature(WEBHOOK_SECRET, raw_body, request.headers.get("Mailcycle-Signature")):
        raise HTTPException(status_code=401, detail="Bad signature")

    event = json.loads(raw_body)
    is_new = save_event(event["id"], event["type"], raw_body.decode("utf-8"))
    if is_new:
        background.add_task(process_event, event["id"])  # runs after the response is sent

    return Response(status_code=204)

Run it with uvicorn inbound.app:app --port 3000. verify_webhook_signature takes bytes or str, so you can hand it await request.body() directly. In Flask, use request.get_data(); in Django, request.body.

The verify helper in every SDK

Language Helper Docs
TypeScript verifyWebhookSignature(secret, rawBody, header) TypeScript SDK
Python verify_webhook_signature(secret, raw_body, header) Python SDK
Go mailcycle.VerifyWebhookSignature(secret, rawBody, header) Go SDK
Rust verify_webhook_signature_now(secret, raw_body, header) Rust SDK
Java WebhookSignature.verifyNow(secret, rawBody, header) Java SDK
C# / .NET WebhookSignature.VerifyNow(secret, rawBody, header) .NET SDK
PHP WebhookSignature::verifyNow($secret, $rawBody, $header) PHP SDK
Ruby Mailcycle.verify_webhook_signature(secret, raw_body, header) Ruby SDK
Swift verifyWebhookSignature(secret:rawBody:header:) Swift SDK

No SDK in your stack? The check is a dozen lines with any HMAC library: split the header on commas into t and v1, refuse a t more than 300 seconds from now, compute HMAC-SHA256(secret, t + "." + rawBody) as hex, and compare it to v1 in constant time. The webhooks guide has a reference version using node:crypto.

Step 4: Fetch and parse the incoming email

The event gave you an id; now fetch the message. This is where the SDK earns its place: messages.get downloads the sealed message, opens it with keys derived from your phrase, and returns it already parsed. There’s no MIME to pick apart, no character sets to decode and no multipart boundaries to find.

// lib/handle-mail.ts
import { mkdir, writeFile } from 'node:fs/promises';
import { mailcycle } from './mailcycle';
import type { MailcycleEvent } from './events';

export async function handleEvent(event: MailcycleEvent): Promise<void> {
  if (event.type !== 'message.received') return;

  const mc = await mailcycle();
  const message = await mc.messages.get(String(event.payload.messageId));
  if (!message.opened) throw new Error(`${message.id} did not open: check MAILCYCLE_PHRASE`);

  console.log(`From ${message.fromName} <${message.from}>: ${message.subject}`);
  console.log(message.text.slice(0, 500));

  await mkdir('inbox-files', { recursive: true });
  for (const file of message.attachments) {
    if (!file.stored) continue; // the part had no body
    const bytes = await mc.messages.attachment(message, file.index); // decrypted here
    await writeFile(`inbox-files/${message.id}-${file.index}-${file.filename.replace(/[\\/]/g, '_')}`, bytes);
  }

  await mc.messages.markRead(message.id);
}

And the Python worker that the FastAPI route hands events to:

# inbound/worker.py
import json
import os
from functools import cache
from pathlib import Path

from mailcycle import Mailcycle

from .store import mark_processed, pending_body, pending_ids


@cache
def client() -> Mailcycle:
    """One client per process. The phrase lets it open (decrypt) the mail."""
    return Mailcycle.with_api_key(
        os.environ["MAILCYCLE_API_KEY"],
        phrase=os.environ["MAILCYCLE_PHRASE"],
    )


def process_event(event_id: str) -> None:
    body = pending_body(event_id)
    if body is None:
        return  # already processed, or never stored
    event = json.loads(body)

    if event["type"] == "message.received":
        handle_new_mail(event["payload"]["messageId"])

    mark_processed(event_id)


def handle_new_mail(message_id: str) -> None:
    mc = client()
    message = mc.messages.get(message_id)
    if not message.opened:
        raise RuntimeError(f"{message_id} did not open: check MAILCYCLE_PHRASE")

    print(f"From {message.from_name} <{message.from_address}>: {message.subject}")
    print(message.text[:500])

    for attachment in message.attachments:
        if not attachment.stored:
            continue  # the part had no body
        data = mc.messages.attachment(message, attachment.index)  # decrypted here
        safe_name = attachment.filename.replace("/", "_").replace("\\", "_")
        Path("inbox-files").mkdir(exist_ok=True)
        Path("inbox-files", f"{message.id}-{attachment.index}-{safe_name}").write_bytes(data)

    mc.messages.mark_read(message.id)


def process_pending() -> None:
    """Run on start-up and on a timer: picks up anything a crash left behind."""
    for event_id in pending_ids():
        try:
            process_event(event_id)
        except Exception as error:  # keep going; the row stays pending for next time
            print(f"{event_id} failed: {error}")

FastAPI runs a plain def background task in its threadpool, so the synchronous client doesn’t block the event loop. For heavier work, hand the event id to Celery, RQ or whatever queue you already run; the pattern is the same.

What a parsed message gives you

Field (TypeScript / Python) What it is
from / from_address, fromName / from_name The sender’s address and display name
replyTo / reply_to Where a reply should go: Reply-To if set, otherwise From
to, subject, receivedAt / received_at As you’d expect
text The plain-text body
html The HTML exactly as sent, remote images and all
safeHtml / safe_html The HTML with remote images, stylesheets and embeds removed. Render this one.
messageId / message_id The sender’s Message-ID header, for threading
attachments Each with index, filename, mimeType / mime_type, size, stored and, for inline images, contentId / content_id

Treat everything in an email as untrusted input: it was written by whoever sent it. Escape it before you show it, never render html directly, and be careful passing it to tools. If an AI agent reads the mail your webhook receives, see AI agent email security for how to keep a hostile message in its lane.

Reply from the handler

If your handler should answer, send from the address that received the mail and pass the original as replyTo, which threads the reply. Sending with an API key needs the Scale plan or the trial:

import type { Message } from 'mailcycle-sdk';
import { mailcycle } from './lib/mailcycle';

export async function acknowledge(message: Message) {
  const mc = await mailcycle();
  const address = (await mc.addresses.list()).find((a) => a.id === message.inboxId);
  if (!address) return;
  await mc.messages.send({
    from: address.emailAddress,
    to: message.replyTo,
    subject: `Re: ${message.subject}`,
    text: 'Thanks, we have your message and will reply shortly.',
    replyTo: message, // threads it under the original
  });
}

Mailcycle is for mail people expect, such as this reply, from addresses you own. The TypeScript and Python sending tutorials cover HTML, attachments and errors in depth.

Step 5: Make your webhook handler idempotent

Webhooks are delivered at least once. A slow response, a network blip between your server’s 204 and Mailcycle hearing it, or a redelivery from the log can all bring the same event back. Events can also arrive out of order. Build for both:

  1. Deduplicate on the event id. It’s in the body as id and in the Mailcycle-Event-Id header, and it’s the same on every attempt and redelivery. A primary key or unique index on it, as in the Python store above, makes the check atomic even with several workers.
  2. Make the work itself idempotent. Key what you create on the messageId: an upsert into your tickets table, a job id in your queue. Then even a duplicate that slips past step 1 does no harm.
  3. Order by createdAt, not arrival. If you track state, such as which addresses exist from inbox.created and inbox.deleted, compare createdAt before applying an older event over a newer one.
  4. Keep event ids for longer than the retry window. Retries run for about a day and a half, and you can redeliver from the 30-day log by hand, so keep ids for at least a few days, or for good if your table is small.

The in-memory firstDelivery helper in the TypeScript example is fine for a single long-running process. Behind a load balancer, or on serverless, use the database.

Step 6: Respond fast, then process

Mailcycle waits 10 seconds for a 2xx. Anything else, a redirect included, is a failure, and so is a timeout. Fetching a message, saving attachments, calling a model and replying can easily take longer than that, so the handler’s only jobs are: verify, record, answer. Everything else happens afterwards.

How “afterwards” works depends on what you run:

Setup Hand-off
A long-running Node server setImmediate, or push to BullMQ, a jobs table or SQS
Next.js after() for light work; a queue for anything that must not be lost
FastAPI BackgroundTasks for light work; Celery, RQ or a jobs table otherwise
Serverless functions Write the event to a queue or table, and let a separate consumer process it

One subtlety: once you’ve answered 204, Mailcycle considers the event delivered and won’t retry it. If your process crashes between the answer and the work, an in-memory hand-off loses the event. That’s why the Python example writes the event to a table before answering, and why process_pending() exists: run it on start-up and on a timer, and nothing is lost. Use a durable queue for anything you can’t afford to miss.

When delivery does fail, Mailcycle retries:

Attempt After the previous one
1 As the event happens
2 to 8 1 minute, 5 minutes, 30 minutes, 2 hours, 6 hours, 12 hours, 12 hours

That’s eight attempts over about a day and a half. Each delivery stays in the log for 30 days with its status, attempts and last response code, and a finished delivery can be sent again. If every attempt has failed for three days, the webhook is switched off, and the account gets a push notification if the Webhooks notification is on. Switch it back on in the app or with PATCH /webhook-endpoints/:id; events from while it was off are not sent, so catch up by listing recent mail.

An API key can read the delivery log and redeliver, which makes a handy script after an outage:

import { mailcycle } from './lib/mailcycle';

const mc = await mailcycle();
const webhookId = process.env.MAILCYCLE_WEBHOOK_ID!;

const { deliveries } = await mc.webhooks.deliveries(webhookId, { status: 'failed' });
for (const d of deliveries) console.log(d.id, d.eventType, d.attempts, d.responseStatus, d.error);

if (deliveries[0]) await mc.webhooks.redeliver(webhookId, deliveries[0].id);

A redelivery carries the same event id, so your deduplication treats it correctly. Tests and redeliveries together are limited to 60 an hour.

How to test an email webhook locally

Mailcycle won’t call localhost, so while you develop you have three good options.

1. Use a tunnel. A tunnel gives your local port a public HTTPS hostname. For example, a Cloudflare quick tunnel with cloudflared tunnel --url http://localhost:3000, or ngrok with ngrok http 3000. Either prints an https:// URL; add it as a webhook with /webhooks/mailcycle on the end, then:

  1. Choose Send test on the webhook in the app, or call mc.webhooks.test(id). A webhook.test event should reach your handler and get a 204.
  2. Send a real email to your address from your normal mail account. A message.received event follows, and your worker prints the subject.
  3. Check the delivery log in the app if nothing shows up: it records the response code your endpoint gave.

Free tunnel URLs usually change each time you start them, so update the webhook’s URL, or keep a separate development webhook and switch it off when you’re done.

2. Sign your own deliveries in tests. You don’t need Mailcycle at all to test the handler. The Python SDK ships webhook_signature_header to build a believable header:

import json
import time

from fastapi.testclient import TestClient
from mailcycle import webhook_signature_header

from inbound.app import app

client = TestClient(app)
body = json.dumps({
    "id": "evt_test_1",
    "type": "webhook.test",
    "createdAt": "2026-11-15T09:00:00.000Z",
    "payload": {"webhookId": "whk_test"},
})
header = webhook_signature_header("whsec_test_secret", body, int(time.time()))

response = client.post(
    "/webhooks/mailcycle",
    content=body,
    headers={"Content-Type": "application/json", "Mailcycle-Signature": header},
)
assert response.status_code == 204

Set MAILCYCLE_WEBHOOK_SECRET=whsec_test_secret for the test run. In TypeScript, build the same header from node:crypto: t=${t},v1= followed by createHmac('sha256', secret).update(`${t}.${body}`).digest('hex'). Test the failures too: a wrong secret, a timestamp ten minutes old and a body changed after signing should all get 401.

3. Skip the webhook and use the event stream, below. It needs no public URL, which makes it the simplest way to watch events arrive on a laptop.

The event stream: inbound email without a public URL

The event stream is a WebSocket that carries the same events, in the same shape, as webhooks, the moment they happen. Your code connects out, so there’s no URL to expose, no signature to check and no tunnel. It suits long-running workers, desktop tools, agents and anything behind a firewall.

import { mailcycle } from './lib/mailcycle';

const mc = await mailcycle();

async function catchUp() {
  // Events are not replayed after a drop, so look at what is unread.
  for (const address of await mc.addresses.list()) {
    const { messages } = await mc.messages.list(address.id, { limit: 50 });
    for (const message of messages) if (!message.read) console.log('missed while disconnected:', message.subject);
  }
}

mc.events.stream(
  (event) => {
    if (event.type !== 'message.received') return;
    mc.messages
      .get(String(event.payload.messageId))
      .then((message) => console.log(message.from, message.subject))
      .catch((error) => console.error(event.id, error));
  },
  {
    onReconnect: () => void catchUp().catch(console.error),
    onError: (error) => console.error(error.code, error.message),
  },
);

In Python, install the extra with pip install 'mailcycle[events]':

import os

from mailcycle import Mailcycle

mc = Mailcycle.with_api_key(os.environ["MAILCYCLE_API_KEY"], phrase=os.environ["MAILCYCLE_PHRASE"])


def catch_up() -> None:
    # Events are not replayed after a drop, so look at what is unread.
    for address in mc.addresses.list():
        for message in mc.messages.list(address.id, limit=50):
            if not message.read:
                print("missed while disconnected:", message.subject)


with mc.events.stream(on_reconnect=catch_up) as events:
    for event in events:
        if event.type == "message.received":
            message = mc.messages.get(event.payload["messageId"])
            print(message.from_address, message.subject)

The SDKs reconnect after a drop and call your reconnect hook. The stream is live, so both examples catch up on reconnect. If you need every event even while your code is down, use webhooks, which retry for about a day and a half. Many apps use both: a webhook for the record, and the stream for an instant update in a running process.

A signed-in session can open the stream on every plan; an API key can on Operator and above. And if you only need to wait for one message, such as a verification email in a test, mc.messages.waitFor() in TypeScript or mc.messages.wait_for() in Python uses the stream for you. Test email verification with Playwright shows that pattern, and Receive email in Python covers reading and waiting in more depth.

Webhooks vs polling vs event stream vs IMAP

Webhooks Event stream Polling the API IMAP (a traditional mailbox)
How mail reaches you Mailcycle POSTs an event to your URL Your code holds a WebSocket open Your code lists the inbox on a timer Your code keeps an IMAP connection open (IDLE) or checks on a timer
Needs a public URL Yes, HTTPS No No No
If your code is down Retried for about 1.5 days, logged for 30 Missed; catch up on reconnect Picked up on the next poll Waiting in the mailbox
Delay Seconds Instant Up to your interval Near-instant with IDLE
What you get An id; the SDK fetches, decrypts and parses An id; the same Parsed messages Raw MIME you parse yourself
Credentials on your server Webhook secret, API key, phrase API key or session, phrase API key or session, phrase Mailbox username and password or OAuth token
Best for Web apps, APIs, serverless Long-running workers, agents, local development Scripts, cron jobs, tests Mail you already host in a mailbox

A few notes on choosing:

  • Webhooks are the default for a production service. They push, they retry and they leave a log you can replay from.
  • The event stream is the lowest-latency option and needs nothing exposed, but you own the reconnect and catch-up.
  • Polling is the simplest to reason about and fine for low volumes. Reads are metered per message fetched, so polling a busy inbox every few seconds spends your allowance on nothing new; see rate limits.
  • IMAP is the long-standing standard for reading a mailbox. Mailcycle needs no IMAP server: the SDK is the client, and messages come back parsed rather than as raw MIME.

Troubleshooting

Every delivery fails with 401 from your endpoint. Almost always the body was parsed before you verified it. In Express, a global app.use(express.json()) registered before the webhook route consumes the body; mount the webhook route first, or skip the JSON parser for that path. In FastAPI, use await request.body(), not a Pydantic model parameter. Also check you’re using the whsec_ secret for this webhook, and that it wasn’t rotated: a new secret replaces the old one at once.

401 only on some deliveries. Check your server’s clock. Signatures more than five minutes from your clock are refused, so a drifting clock fails intermittently. Run NTP.

invalid_url when adding the webhook. The URL must be HTTPS with a hostname. http://, IP addresses, localhost and *.local are refused. Use a tunnel while developing.

plan_required when adding the webhook. Webhooks start at Operator. Start the Scale trial or upgrade under Plans & Billing.

session_required from your setup script. You’re using an API key to add or change a webhook. Those need a signed-in session: use Mailcycle.signIn or Mailcycle.sign_in with the phrase, or the app.

Deliveries time out. Your handler is doing the work before answering. Move it after the response as in step 6, and check the delivery log’s responseStatus and error.

The message comes back with opened: false. The client has no phrase, or the phrase is for a different account. With an API key and a phrase from another account, the SDK fails up front with phrase_mismatch.

Nothing arrives at all. Check the webhook’s status in the app: it may have been switched off after three days of failures. Confirm it’s subscribed to message.received (or *), send a test, and look at the delivery log.

Webhook deliveries stopped after a plan change. On a plan without webhooks nothing is sent and pending deliveries are marked failed. They start again when the plan includes webhooks.

Next steps

You now have an inbound email webhook that verifies every delivery, fetches and parses the message by id, survives retries and duplicates, answers fast and processes in the background. From here:

FAQ

How do I receive email with a webhook?

Give your mail provider an HTTPS URL and subscribe it to the event for new mail. With Mailcycle you add a webhook under **API** > **Webhooks** for message.received; when mail arrives, Mailcycle sends a signed POST with the message id, your endpoint verifies the Mailcycle-Signature header and answers 2xx, and your code fetches the message by id with an SDK.

What is an inbound email webhook?

It is an HTTP request your email provider makes to your server when a message arrives at one of your addresses. It turns incoming email into an event your app can react to straight away, without polling a mailbox. Mailcycle's webhook carries ids rather than the message itself, and your code opens the message on its own machine.

Does the Mailcycle webhook include the email body?

No. Events carry ids, never content: a message.received payload has the messageId and the inboxId. Your handler calls mc.messages.get(messageId) in TypeScript or mc.messages.get(message_id) in Python, and the SDK decrypts and parses the message with your recovery phrase. The body never sits in a webhook log or a proxy along the way.

How do I verify a Mailcycle webhook signature?

Pass the webhook's whsec_ secret, the raw request body and the Mailcycle-Signature header to the SDK helper: verifyWebhookSignature in TypeScript, verify_webhook_signature in Python, and an equivalent in every other SDK. It checks an HMAC-SHA256 of the timestamp, a full stop and the body, and refuses a timestamp more than five minutes old. Verify the raw bytes before you parse the JSON.

What happens if my webhook endpoint is down?

A failed delivery is retried after 1 minute, 5 minutes, 30 minutes, 2 hours, 6 hours, 12 hours and 12 hours: eight attempts over about a day and a half. Each delivery stays in the log for 30 days and can be sent again. A webhook whose every attempt has failed for three days is switched off until you switch it back on.

Can the same webhook event arrive twice?

Yes. Events can arrive more than once and out of order, for example after a timeout or a redelivery. Deduplicate on the Mailcycle-Event-Id header, which is the same on every attempt, and order events by createdAt. A unique key on the event id in your database is the simplest way to do it.

How do I test an email webhook on localhost?

Webhook URLs must be HTTPS with a hostname, so localhost is refused. Run a tunnel such as Cloudflare Tunnel or ngrok to get a public HTTPS URL for your local port, add that as the webhook, and use **Send test** to fire a webhook.test event. For unit tests, sign your own sample bodies with the secret instead.

Should I use webhooks or polling to receive email?

Use webhooks for a web app or service with a public URL: mail is pushed to you as it lands and retried if you are down. Polling suits short scripts and tests, and the event stream suits long-running workers with no public URL. Polling a busy inbox spends your read allowance for nothing.

Which Mailcycle plan includes webhooks?

Webhooks start at the Operator plan, and API keys do too, so Operator is enough to receive and read mail with webhooks. Sending replies with an API key needs Scale. The free 7-day Scale trial includes both, with no card. See pricing.

Receive email in code