Add Inbound Email to Your SaaS: Support Intake and Reply-by-Email

Turn mail to support@ into tickets with a signed webhook, answer from the API in the same thread, and file the customer's reply on the same ticket.

By · · 16 min read

TypeScript code from this guide, in intake.ts, turning a message.received event into a support ticket

Customers write to support@ and expect an answer in the same thread. Behind that sits a small loop that almost every product ends up building: mail arrives, the product makes a ticket, a person or a bot answers, and the customer’s next message lands on the same ticket instead of starting a new one. This tutorial builds that loop with Mailcycle in TypeScript. You’ll create the support address, turn each inbound email into a ticket with a signed webhook, reply by email from the API in the customer’s thread, and match the customer’s answer to the ticket it belongs to.

It builds on How to receive email with a webhook, which covers adding the webhook, verifying signatures in depth, deduplicating and retries. Here we reuse that endpoint and add what a product needs on top of it: tickets, a reply path and thread matching. The loop was run end to end on a Scale account, and the output is shown below.

Quick answer: how to add inbound email to your SaaS

Subscribe a webhook to message.received. When a customer writes to your support address, Mailcycle posts a signed event with the message id. Your handler checks the signature, fetches the message with the SDK, and either opens a ticket or adds the message to the ticket named in the subject. Your team answers with one messages.send call that names the message being answered, and the customer’s reply comes back through the same webhook.

const message = await mc.messages.get(event.payload.messageId);   // opened on your machine
const ticketId = ticketIdFromSubject(message.subject) ?? openTicket(message.replyTo, message.subject);

await mc.messages.send({
  from: 'support@yourdomain.com',
  to: message.replyTo,
  subject: `Re: [T-${ticketId}] ${message.subject}`,
  text: 'Thanks for writing. We have resent the code.',
  replyTo: { id: message.id, messageId: message.messageId },       // In-Reply-To and References
});

The rest of this guide turns those lines into code you can run.

How support intake and reply-by-email work

Flow: a customer writes to support@ on your domain, Mailcycle encrypts the mail on arrival and posts a signed webhook, your handler creates a ticket, and a reply from the API goes back in the same thread
Mail to support@ becomes a ticket, and the reply goes back in the same thread.
  1. Mail reaches your support address. Mail is encrypted the moment it arrives.
  2. Mailcycle posts a signed message.received event to your HTTPS endpoint. It carries the message id and the address id, never the text.
  3. Your handler verifies the signature and fetches the message. The SDK opens it on your machine and returns the sender, subject and text already parsed.
  4. The handler files it. A new subject opens a ticket. A subject that names an open ticket, such as Re: [T-1] Cannot log in, is added to that ticket.
  5. Your team answers from the API. The reply goes out from the support address with the ticket number in the subject and the threading headers filled in.
  6. The customer replies, and step 4 files the answer on the same ticket.

There is no inbox to poll and no MIME to parse. Each step is a function you own, so the same loop works whether the answer is typed by a person in your admin screen or written by a model. If your intake runs on Mailgun Routes today, Mailgun inbound Routes alternative shows how each route becomes an address and a branch in this handler.

What you need

  • A Scale account. Scale is $19 a month and includes API keys, webhooks, sending from the API, 10 domains of your own and 1,000 addresses. The free 7-day Scale trial includes all of it, with no card: start it under Plans & Billing in the web app.
  • A support address. Step 1 covers it. The code only needs the address as a string.
  • An API key, your recovery phrase and a webhook secret in the environment: MAILCYCLE_API_KEY, MAILCYCLE_PHRASE and MAILCYCLE_WEBHOOK_SECRET, plus SUPPORT_ADDRESS. The webhook guide explains why the phrase lives on the server: it is what lets the SDK open mail in your process.
  • Node.js 22.5 or later, because the example stores tickets with the built-in node:sqlite, and npm install mailcycle-sdk express.

Step 1: Create support@ on your own domain

On Scale you bring your own domain and choose the whole address, so customers write to support@yourdomain.com instead of a generated name. You add the domain in the app, publish the records it shows, and create the address with the part before the @ you want. The Your own domains guide has the steps, and Role addresses on your own domain shows the same idea for a small team: support@, billing@ and hello@ side by side.

With the address in place, the rest of the tutorial treats it as one environment variable:

export SUPPORT_ADDRESS="support@yourdomain.com"

Sending from an address on your own domain starts once the domain’s sending is on, which usually follows receiving within minutes. Until then a send returns 409 domain_not_sending, so check the domain under Domains before you go live.

You can also create addresses in code, with mc.addresses.create, as in the email addresses guide. That is how the run below made its two test addresses.

Step 2: Add a ticket store

A ticket is a row. Every message on it is another row keyed on the Mailcycle message id, which makes the store idempotent: seeing the same message twice adds nothing. SQLite from node:sqlite keeps the example self-contained, and the same two tables work in Postgres or MySQL.

// lib/tickets.ts
import { DatabaseSync } from 'node:sqlite';

export const db = new DatabaseSync(process.env.TICKETS_DB ?? ':memory:');

db.exec(`
  CREATE TABLE IF NOT EXISTS tickets (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    requester TEXT NOT NULL,
    subject TEXT NOT NULL,
    status TEXT NOT NULL DEFAULT 'open'
  );
  CREATE TABLE IF NOT EXISTS ticket_messages (
    message_id TEXT PRIMARY KEY,          -- Mailcycle message id: a retry adds nothing
    ticket_id INTEGER NOT NULL REFERENCES tickets(id),
    direction TEXT NOT NULL,              -- 'in' from the customer, 'out' from your team
    header_id TEXT,                       -- the Message-ID header, kept for threading a reply
    body TEXT NOT NULL
  );
`);

/** "[T-12]" in a subject names ticket 12. A reply keeps it: "Re: [T-12] Login problem". */
export function ticketIdFromSubject(subject: string): number | null {
  const found = /\[T-(\d+)\]/.exec(subject);
  return found ? Number(found[1]) : null;
}

The helpers that open a ticket, add a message and look one up are a few lines of INSERT and SELECT each. They are in the full code at the end.

Two details are worth a sentence each. The ticket stores requester, the address answers go to, rather than a name. And header_id keeps the Message-ID header of each message, because that is what a reply needs to thread under it.

Your own database is also the right home for the conversation. A Mailcycle address keeps mail for the retention window you choose, 7 days by default and up to 90, so a ticket history that has to last longer than that belongs in your tables, which is where this code puts it.

Step 3: Reuse the webhook endpoint

The endpoint is the one from the webhook guide: read the raw body, verify Mailcycle-Signature with verifyWebhookSignature, answer 204 and work afterwards. Only the last line changes, because the work is now handleEvent:

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

const app = express();

app.post('/webhooks/mailcycle', express.text({ type: 'application/json' }), async (req, res) => {
  const rawBody = typeof req.body === 'string' ? req.body : '';
  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;
  res.status(204).end();
  handleEvent(event).catch((error) => console.error(event.id, error));
});

export default app;

The rule that matters is the one from that guide: verify the raw bytes, before any JSON parsing. A body that has been parsed and serialised again is a different string and will not verify. Keep the Mailcycle-Event-Id check from the guide in front of handleEvent in production; the message-id key in the ticket table is a second guard behind it.

Step 4: Turn a message into a ticket

The handler fetches the message and files it. Three decisions sit in it.

// lib/intake.ts
import { mailcycle } from './mailcycle';
import { addMessage, getTicket, openTicket, ticketIdFromSubject, ticketOfMessage } from './tickets';

const SUPPORT_ADDRESS = process.env.SUPPORT_ADDRESS!;

/** The webhook body: an event id, its type, when it happened and its payload. */
export interface MailcycleEvent {
  id: string;
  type: string;
  createdAt: string;
  payload: Record<string, unknown>;
}

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

  const messageId = String(event.payload.messageId);
  const already = ticketOfMessage(messageId); // a redelivered event changes nothing
  if (already) return already;

  const mc = await mailcycle();
  const message = await mc.messages.get(messageId);
  if (!message.opened) throw new Error(`${message.id} did not open: check MAILCYCLE_PHRASE`);
  if (message.from.toLowerCase() === SUPPORT_ADDRESS.toLowerCase()) return null; // never answer ourselves

  const named = ticketIdFromSubject(message.subject);
  const ticketId = named && getTicket(named) ? named : openTicket(message.replyTo, message.subject);

  addMessage(ticketId, message.id, 'in', message.messageId, message.text);
  await mc.messages.markRead(message.id);
  return ticketId;
}

Idempotency first. Events can arrive more than once. Looking the message up in the ticket table before doing anything means a retry returns the existing ticket and creates nothing.

A guard against answering yourself. If your own support address ever writes to itself, for example through a forwarding rule, the handler stops instead of opening a ticket for its own mail.

One rule for new versus existing. If the subject names a ticket that exists, the message joins it. Anything else opens a new ticket, with message.replyTo as the requester: the sender’s Reply-To if they set one, otherwise their From. message.messageId is the sender’s Message-ID header, which the reply in the next step needs.

The client behind mailcycle() is the one from the webhook guide: Mailcycle.withApiKey with both the key and the phrase, built once per process.

Step 5: Reply from the API in the same thread

Sending with an API key is a Scale feature. One call sends from your support address, and passing the message you are answering as replyTo fills in the threading headers for you.

// lib/reply.ts
export async function replyToTicket(ticketId: number, text: string): Promise<string> {
  const ticket = getTicket(ticketId);
  const parent = lastIncoming(ticketId);
  if (!ticket || !parent) throw new Error(`Ticket ${ticketId} has nothing to reply to`);

  const mc = await mailcycle();
  const subject = ticket.subject.includes(`[T-${ticket.id}]`) ? ticket.subject : `[T-${ticket.id}] ${ticket.subject}`;

  const sent = await mc.messages.send({
    from: process.env.SUPPORT_ADDRESS!,
    fromName: 'Acme Support',
    to: ticket.requester,
    subject: subject.startsWith('Re:') ? subject : `Re: ${subject}`,
    text,
    replyTo: { id: parent.message_id, messageId: parent.header_id }, // In-Reply-To and References
  });

  addMessage(ticketId, sent.sentCopyId ?? sent.messageId, 'out', sent.messageId, text);
  return sent.messageId;
}

What each part does:

  • from must be an address on your account. Any other returns 403 not_your_address.
  • fromName is the display name on the From line, up to 78 characters on one line, so the customer sees “Acme Support” rather than the bare address.
  • to takes one recipient per send. To reach two people, make two calls.
  • replyTo takes the message you are answering. The SDK sends its Mailcycle id as inReplyTo and its Message-ID as inReplyToHeader, and the outgoing mail carries In-Reply-To and References for it, so the customer’s mail client threads your answer under their question.
  • The result has messageId, the Message-ID the mail went out with, and sentCopyId, the copy in the address’s Sent folder. The code stores whichever it has next to the ticket.

The full field list and every error code are in the sending guide. The same call in other languages is in Send email from TypeScript and the pages linked from Send email with an API in any language.

How the customer’s reply finds its ticket

Threading headers make mail clients group the conversation. The ticket needs something it can read in the next incoming message, and the subject is the most reliable place for it: mail clients keep the subject when someone replies, adding Re: in front. So the ticket number goes into the subject of every reply, in square brackets, and ticketIdFromSubject reads it back.

That gives the loop its shape. Your reply is Re: [T-1] Cannot log in. The customer answers with that subject, the webhook fires, the handler finds [T-1] and the message is filed on ticket 1. A message with no tag, such as a customer starting a new topic, opens a new ticket, which is usually what you want.

Keep the tag short and unlikely to appear by accident. A ticket number is enough to start with. If you later want to make it harder to guess, use a short random token instead of the row id and look it up in the same way.

Step 6: Run it

The loop below was run on a Scale account with real mail. A customer address wrote to a support address, a signed message.received event was posted to the endpoint listening on 127.0.0.1, the handler fetched the message and opened ticket 1, replyToTicket answered, the customer replied to that subject, and the second event landed on ticket 1. Both addresses belong to the same test account, so nothing went to an outside address. The events were signed locally with the same HMAC scheme Mailcycle uses, which lets you run the whole thing on a laptop without a public URL.

Terminal output of the run: two signed webhooks return 204, the customer receives the reply with the ticket tag in the subject, and ticket 1 holds the customer message, the team reply and the customer's answer
One ticket, three messages: the customer's question, your reply and the customer's answer.

The output, exactly as printed:

webhook 1: HTTP 204
customer received: Re: [T-1] Cannot log in
webhook 2: HTTP 204
ticket 1  in   Hi, my login code never arrives. Can you help?
ticket 1  out  Thanks for writing. We have resent the code: please check again.
ticket 1  in   Got it, thank you.
tickets: 1

Three messages, one ticket. The second inbound message did not open a second ticket, because its subject named ticket 1.

To try it yourself, put the five values in a file and run the script with npx tsx --env-file=env.local run.ts. The script is the loop above in a short file: it sends as the customer, waits for the mail with messages.waitFor, posts a signed event to the endpoint, calls replyToTicket, and prints the table.

Attachments and HTML replies

Support mail often carries a screenshot, and good replies often need a link or a button. Both are covered by the SDK.

For attachments on incoming mail, message.attachments lists the files and mc.messages.attachment(message, index) returns the decrypted bytes, as in the webhook guide’s handler. Store the bytes in your object storage and keep the key on the ticket row.

For a reply, add html next to text, and pass files in attachments:

await mc.messages.send({
  from: process.env.SUPPORT_ADDRESS!,
  to: ticket.requester,
  subject: `Re: [T-${ticket.id}] ${ticket.subject}`,
  text: 'Your invoice is attached.',
  html: '<p>Your invoice is attached.</p>',
  attachments: [{ filename: 'invoice.pdf', mimeType: 'application/pdf', content: pdfBytes }],
  replyTo: { id: parent.message_id, messageId: parent.header_id },
});

A send takes up to 10 files, 3.5 MB between them, and program and script files are refused with 400 attachment_blocked. Always include text: it is required, and it is what plain-text mail clients show.

Limits and errors to plan for

Replies are ordinary API calls, so they have limits. On Scale you can send 250 messages a day and 60 an hour per account; Fleet runs the hourly limits at three times and the daily limit at 1,000. A support desk with a normal volume sits well inside that, and the rate limits reference lists the rest. GET /usage, or mc.usage(), reports the numbers your account actually runs at.

The errors worth handling in replyToTicket are all stable codes in the errors reference:

Code Meaning What to do
plan_required The plan does not send from an API key. Move the account to Scale.
not_your_address from is not an address on this account. Check SUPPORT_ADDRESS.
domain_not_sending Sending is not yet on for your own domain. Check the domain under Domains and retry in a few minutes.
address_paused The address is paused after a missed payment. Pay, then retry.
rate_limited Too many sends in the hour. Wait for Retry-After seconds.
daily_send_limit The plan’s mail for today is sent. Sending resumes at 00:00 UTC.
send_failed, provider_error A failure on the sending side. Retry with backoff.

A reply that fails should leave the ticket in a state your team can see, such as status = 'reply_failed', and be retried from a queue rather than lost.

Test it without a public URL

Webhook URLs must be HTTPS with a hostname, so a laptop cannot receive them directly. You have three options that need nothing public. Sign your own sample events, as the run above does, which is the right choice for unit tests: you control the body and the clock. Use mc.messages.waitFor to wait for the next message on an address and feed it to handleEvent yourself. Or listen on the event stream, which a long-running worker can hold open with no public URL at all. When you are ready to receive real deliveries, add the webhook in the app under API > Webhooks and use Send test to fire a webhook.test event.

Go live checklist

  • Add the webhook for message.received under API > Webhooks and set MAILCYCLE_WEBHOOK_SECRET from the secret shown once at creation. The webhooks reference lists every endpoint.
  • Keep the Mailcycle-Event-Id check in front of handleEvent, and answer 204 before you do any work. Mailcycle waits 10 seconds at most.
  • Point your own domain at Mailcycle and create support@yourdomain.com, as in Your own domains.
  • Create the API key in the app under API and keep it with your phrase in your secret store, as you would a database password. See API keys.
  • Swap the SQLite stub for your database and put replyToTicket behind your admin screen, queue or model.
  • Teams can pair staff devices to the same address and read support@ in the app next to the API; see Pair many devices.

Where to go next

If you also send transactional mail from the same account, Send email with an API in any language and the per-language guides cover receipts and notifications. For a plain Node.js inbox reader without webhooks, read How to receive email in Node.js. If your intake runs on SendGrid Inbound Parse today, SendGrid Inbound Parse alternative shows the move step by step. To give an AI agent the support inbox instead of your code, see the AI agent email inbox guide. And solutions lists other ways teams use Mailcycle, the TypeScript SDK page has the reference, and pricing has the plans.

The full code

The complete lib/tickets.ts, lib/mailcycle.ts, lib/intake.ts, lib/reply.ts and server.ts are the snippets above plus these helpers. The SDK client is created once per process and reused by the handler and the reply code:

// 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;
    throw error;
  });
  return client;
}

If the first sign-in fails, the cached promise is cleared, so the next webhook tries again rather than failing for the life of the process.

// lib/tickets.ts (continued)
export function openTicket(requester: string, subject: string): number {
  const row = db.prepare('INSERT INTO tickets (requester, subject) VALUES (?, ?)').run(requester, subject);
  return Number(row.lastInsertRowid);
}

export function getTicket(id: number) {
  return db.prepare('SELECT id, requester, subject, status FROM tickets WHERE id = ?').get(id) as
    | { id: number; requester: string; subject: string; status: string }
    | undefined;
}

export function addMessage(ticketId: number, messageId: string, direction: 'in' | 'out', headerId: string, body: string): boolean {
  const row = db
    .prepare('INSERT OR IGNORE INTO ticket_messages (message_id, ticket_id, direction, header_id, body) VALUES (?, ?, ?, ?, ?)')
    .run(messageId, ticketId, direction, headerId, body);
  return row.changes === 1;
}

export function ticketOfMessage(messageId: string): number | null {
  const row = db.prepare('SELECT ticket_id FROM ticket_messages WHERE message_id = ?').get(messageId) as { ticket_id: number } | undefined;
  return row?.ticket_id ?? null;
}

export function lastIncoming(ticketId: number) {
  return db
    .prepare("SELECT message_id, header_id FROM ticket_messages WHERE ticket_id = ? AND direction = 'in' ORDER BY rowid DESC LIMIT 1")
    .get(ticketId) as { message_id: string; header_id: string } | undefined;
}

FAQ

How do I add inbound email to my SaaS product?

Give your product an address on your own domain, subscribe a webhook to message.received, and in the handler verify the signature, fetch the message with the SDK and write a record, such as a support ticket. To answer, send from the API with the original message as replyTo. This guide builds exactly that in TypeScript.

How do I turn incoming email into support tickets?

Each message.received event carries a message id. Your handler fetches the message and either opens a new ticket or adds it to the ticket named in the subject, such as [T-12]. A ticket table plus a message table keyed on the Mailcycle message id is enough to start with, and a redelivered event changes nothing.

How does a customer's reply reach the same ticket?

Your answer goes out with the ticket number in the subject and with the original message passed as replyTo, so the mail carries In-Reply-To and References headers and mail clients thread it. Clients keep the subject when the customer replies, so the incoming message names its ticket and your handler files it there.

Can I use support@ on my own domain?

Yes. On Scale you add your domain in the app and choose the whole part before the @, so support@yourdomain.com is an address you create. Mail to it triggers the same webhook as any other address. The steps are in Your own domains.

Which Mailcycle plan sends replies from the API?

Sending with an API key is part of Scale, which is $19 a month and also includes 10 domains of your own, 1,000 addresses and webhooks. A Free account receives mail only, and an API key on a plan below Scale gets plan_required when it tries to send. See pricing.

How many replies can I send a day?

Scale allows 250 sent messages a day and 60 an hour per account. Fleet raises the daily figure to 1,000 and runs the hourly limits at three times. Past the daily limit a send returns 429 daily_send_limit until 00:00 UTC. The rate limits reference lists every figure.

Does the webhook carry the email body?

No. A message.received event carries the messageId and the inboxId. Your handler fetches the message by id, and the SDK opens it on your machine with your recovery phrase. Request logs along the way never hold the text of a customer's email.

What happens if my endpoint is down when a customer writes?

Mailcycle tries a failed delivery up to eight times over about a day and a half, and keeps each delivery in the log for 30 days so you can send it again. Because your ticket table is keyed on the message id, a retried event never creates a second ticket.

Can I send attachments and HTML in a reply?

Yes. A send takes html next to text and up to 10 attachments, 3.5 MB between them. Files go in as bytes in the SDK. See the sending guide for every field and error code.

Receive email in code