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

# Routing

> Route inbound email from Lettr to different handlers in your own code, based on recipient address, variable addressing, subject, sender, or content.

Lettr has no routing rules to configure. Mail sent to any address at an inbound domain is posted to that domain's one forwarding URL, and your handler decides what to do with each message. This page shows common routing patterns you can build in that handler.

## What Lettr Routes for You

The only routing Lettr does is per domain: each inbound domain has its own forwarding URL. If you want different kinds of mail to reach different services, you can set up separate inbound domains with separate forwarding URLs:

| Inbound domain | Forwarding URL |
| - | - |
| `support.example.com` | `https://helpdesk.example.com/webhooks/inbound` |
| `replies.example.com` | `https://app.example.com/webhooks/replies` |

Everything below that level, such as `support@` versus `billing@` on the same domain, is handled in your code.

## Fields Used for Routing

Your forwarding URL receives a JSON array of events. Each event has a `msys.relay_message` object (see [Email Parsing](https://docs.lettr.com/learn/inbound/parsing.md) for the full payload). These are the fields you usually route on:

| Field | Contains |
| - | - |
| `rcpt_to` | The envelope recipient: the address on your inbound domain that received the message |
| `msg_from` | The envelope sender address |
| `friendly_from` | The `From` header, with display name, for example `John Doe <john@example.com>` |
| `content.subject` | The decoded subject line |
| `content.to` | Addresses from the `To` header |
| `content.headers` | All headers, as an array of single-key objects |
| `content.text` / `content.html` | The message body. Either can be missing. |

The examples on this page share these helpers:

```javascript theme={null}
// Read a header from the headers array (case-insensitive)
function getHeader(headers = [], name) {
  const wanted = name.toLowerCase();
  for (const header of headers) {
    for (const [key, value] of Object.entries(header)) {
      if (key.toLowerCase() === wanted) return value;
    }
  }
  return null;
}

// Extract the bare address from "Name <address>" or a plain address
function extractAddress(value = '') {
  const match = value.match(/<([^>]+)>/);
  return (match ? match[1] : value).trim().toLowerCase();
}

// Collect the relay messages from one delivery
function relayMessages(body) {
  return (Array.isArray(body) ? body : [])
    .map((event) => event.msys?.relay_message)
    .filter(Boolean);
}
```

> [!NOTE]
>
> The raw MIME message in `content.email_rfc822` makes payloads with attachments large. Raise your body parser's size limit (Express defaults to 100kb), as the examples below do.

## Routing by Recipient

The most common pattern is to route on the address that received the message:

```javascript theme={null}
app.post('/webhooks/inbound', express.json({ limit: '50mb' }), async (req, res) => {
  for (const relay of relayMessages(req.body)) {
    const recipient = relay.rcpt_to.toLowerCase();
    const message = {
      from: relay.friendly_from || relay.msg_from,
      subject: relay.content.subject,
      body: relay.content.text || relay.content.html
    };

    if (recipient.startsWith('support@')) {
      await createSupportTicket(message);
    } else if (recipient.startsWith('sales@')) {
      await notifySalesTeam(message);
    } else if (recipient.startsWith('feedback@')) {
      await storeFeedback(message);
    } else if (recipient.startsWith('billing@')) {
      await routeToBilling(message);
    } else {
      await handleUnknownRecipient({ recipient, ...message });
    }
  }

  res.sendStatus(200);
});
```

## Variable Address Routing

Because every address at the domain is forwarded, you can encode data in the address itself (plus addressing) and parse it in your handler:

```javascript theme={null}
app.post('/webhooks/inbound', express.json({ limit: '50mb' }), async (req, res) => {
  for (const relay of relayMessages(req.body)) {
    // Parse variable address: reply+{ticketId}@mail.example.com
    const match = relay.rcpt_to.match(/^reply\+([^@]+)@/i);

    if (match) {
      const ticketId = match[1];
      await addReplyToTicket(ticketId, {
        from: relay.msg_from,
        subject: relay.content.subject,
        body: relay.content.text
      });
    }
  }

  res.sendStatus(200);
});
```

### Common Variable Address Patterns

| Pattern | Use Case | Example |
| - | - | - |
| `reply+{ticketId}@` | Support ticket replies | `reply+TKT-1234@mail.example.com` |
| `unsubscribe+{userId}@` | Email unsubscriptions | `unsubscribe+usr_abc@mail.example.com` |
| `confirm+{token}@` | Email confirmations | `confirm+xyz789@mail.example.com` |
| `order+{orderId}@` | Order communications | `order+ORD-5678@mail.example.com` |
| `notify+{channelId}@` | Channel notifications | `notify+ch_slack@mail.example.com` |

> [!TIP]
>
> Anyone can write to any address at your inbound domain, so treat the encoded value as untrusted input. Look it up in your database rather than trusting it, or sign it so you can detect tampering.

## Routing by Subject

Route on keywords or patterns in the subject line:

```javascript theme={null}
app.post('/webhooks/inbound', express.json({ limit: '50mb' }), async (req, res) => {
  for (const relay of relayMessages(req.body)) {
    const subject = relay.content.subject || '';
    const message = { from: relay.msg_from, subject, body: relay.content.text };
    const ticketMatch = subject.match(/ticket #(\d+)/i);

    if (/\b(urgent|emergency)\b/i.test(subject)) {
      await createHighPriorityTicket(message);
    } else if (/unsubscribe/i.test(subject)) {
      await processUnsubscribeRequest({ from: relay.msg_from });
    } else if (ticketMatch) {
      await addReplyToTicket(ticketMatch[1], message);
    } else {
      await createStandardTicket(message);
    }
  }

  res.sendStatus(200);
});
```

## Routing by Sender Domain

Route on the sender's domain, for example to send mail from known customers to their account manager:

```javascript theme={null}
app.post('/webhooks/inbound', express.json({ limit: '50mb' }), async (req, res) => {
  for (const relay of relayMessages(req.body)) {
    const sender = extractAddress(relay.friendly_from || relay.msg_from);
    const senderDomain = sender.split('@')[1];
    const message = { from: sender, subject: relay.content.subject, body: relay.content.text };

    const customer = await findCustomerByDomain(senderDomain);

    if (customer) {
      await routeToAccountManager(customer.accountManagerId, { ...message, customerId: customer.id });
    } else {
      await routeToGeneralInbox(message);
    }
  }

  res.sendStatus(200);
});
```

> [!NOTE]
>
> `msg_from` is the envelope sender and can differ from the address in the `From` header (`friendly_from`), for example when mail comes through a mailing list or a bulk sender. Neither proves who sent the message. See [Security](https://docs.lettr.com/learn/inbound/security.md) before you grant anything based on the sender.

## Content-Based Routing

Route on what the message says:

```javascript theme={null}
app.post('/webhooks/inbound', express.json({ limit: '50mb' }), async (req, res) => {
  for (const relay of relayMessages(req.body)) {
    const content = relay.content.text || stripHtml(relay.content.html || '');
    const lower = content.toLowerCase();
    const message = { from: relay.msg_from, subject: relay.content.subject, body: content };

    if (lower.includes('cancel') && lower.includes('subscription')) {
      await routeToCancellations(message);
    } else if (lower.includes('refund') || lower.includes('money back')) {
      await routeToRefunds(message);
    } else if (lower.includes('bug') || lower.includes('error')) {
      await routeToTechnicalSupport(message);
    } else {
      await routeToGeneralSupport(message);
    }
  }

  res.sendStatus(200);
});
```

## Multi-Criteria Routing

Combine criteria into an ordered rule list in your code, and run the first rule that matches:

```javascript theme={null}
const rules = [
  {
    name: 'vip',
    matches: (relay) => isVipCustomer(extractAddress(relay.friendly_from || relay.msg_from)),
    handle: (relay, message) => routeToVipSupport(message)
  },
  {
    name: 'ticket-reply',
    matches: (relay) => /^reply\+[^@]+@/i.test(relay.rcpt_to),
    handle: (relay, message) => {
      const ticketId = relay.rcpt_to.match(/^reply\+([^@]+)@/i)[1];
      return addReplyToTicket(ticketId, message);
    }
  },
  {
    name: 'sales',
    matches: (relay) => relay.rcpt_to.toLowerCase().startsWith('sales@'),
    handle: (relay, message) => notifySalesTeam(message)
  },
  {
    name: 'default',
    matches: () => true,
    handle: (relay, message) => createSupportTicket(message)
  }
];

app.post('/webhooks/inbound', express.json({ limit: '50mb' }), async (req, res) => {
  for (const relay of relayMessages(req.body)) {
    const message = {
      from: relay.msg_from,
      subject: relay.content.subject,
      body: relay.content.text || relay.content.html
    };

    const rule = rules.find((r) => r.matches(relay));
    await rule.handle(relay, message);
  }

  res.sendStatus(200);
});
```

## Routing with Priority Queues

For high volumes, push messages onto queues by priority and respond right away:

```javascript theme={null}
import Queue from 'bull';

const highPriorityQueue = new Queue('email-high', redisUrl);
const normalPriorityQueue = new Queue('email-normal', redisUrl);
const lowPriorityQueue = new Queue('email-low', redisUrl);

function pickQueue(relay) {
  const sender = extractAddress(relay.friendly_from || relay.msg_from);
  const subject = (relay.content.subject || '').toLowerCase();
  const headers = relay.content.headers;

  if (isVipCustomer(sender) || subject.includes('urgent')) {
    return highPriorityQueue;
  }
  if (getHeader(headers, 'List-Id') || getHeader(headers, 'Auto-Submitted')) {
    return lowPriorityQueue; // mailing lists and automated mail
  }
  return normalPriorityQueue;
}

app.post('/webhooks/inbound', express.json({ limit: '50mb' }), async (req, res) => {
  for (const relay of relayMessages(req.body)) {
    await pickQueue(relay).add({ relay, receivedAt: new Date().toISOString() });
  }

  res.sendStatus(200);
});

// Process queues with different concurrency
highPriorityQueue.process(10, processEmail);
normalPriorityQueue.process(5, processEmail);
lowPriorityQueue.process(2, processEmail);
```

## Unknown Addresses

Every address at your inbound domain is forwarded, including ones you never planned for. Decide in your handler what happens to addresses you don't recognize:

```javascript theme={null}
const knownAddresses = ['support', 'sales', 'feedback', 'billing'];

app.post('/webhooks/inbound', express.json({ limit: '50mb' }), async (req, res) => {
  for (const relay of relayMessages(req.body)) {
    const localPart = relay.rcpt_to.split('@')[0].toLowerCase();
    const message = { from: relay.msg_from, subject: relay.content.subject, body: relay.content.text };

    if (knownAddresses.includes(localPart)) {
      await routeToKnownHandler(localPart, message);
    } else {
      // Log and optionally notify an admin
      await logUnknownAddress(relay.rcpt_to, message);
    }
  }

  res.sendStatus(200);
});
```

> [!TIP]
>
> Lettr does not filter spam on inbound mail, and unknown addresses tend to attract it. Add your own checks before acting on these messages. See [Spam Filtering](https://docs.lettr.com/learn/inbound/spam-filtering.md).

## Forwarding Emails

To pass a received message on to another mailbox, send it with the Lettr send API. Attachments are only in the raw MIME message (`content.email_rfc822`), so parse that first and re-attach the files as base64:

```javascript theme={null}
import { simpleParser } from 'mailparser';

function escapeHtml(value = '') {
  return value.replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
}

async function forwardToTeam(relay) {
  const raw = relay.content.email_rfc822_is_base64
    ? Buffer.from(relay.content.email_rfc822, 'base64')
    : relay.content.email_rfc822;
  const parsed = await simpleParser(raw);

  const { error } = await lettr.emails.send({
    from: 'forwarded@yourdomain.com', // an address on your verified sending domain
    from_name: 'Inbound Forwarder',
    to: ['team@yourdomain.com'],
    reply_to: extractAddress(relay.friendly_from || relay.msg_from),
    subject: `[Forwarded] ${relay.content.subject || '(no subject)'}`,
    html: `
      <p><strong>Originally from:</strong> ${escapeHtml(relay.friendly_from || relay.msg_from)}</p>
      <hr>
      ${relay.content.html || `<pre>${escapeHtml(relay.content.text || '')}</pre>`}
    `,
    attachments: parsed.attachments
      .filter((att) => !att.related) // skip inline images
      .map((att) => ({
        name: att.filename || 'attachment',
        type: att.contentType,
        data: att.content.toString('base64')
      }))
  });

  if (error) {
    throw new Error(`Forward failed: ${error.message}`);
  }
}
```

> [!WARNING]
>
> Forwarded HTML comes from an external sender. Sanitize it before you show it anywhere other than the recipient's mail client.

## Error Handling

Store the payload before you route it, and answer with a 2xx once it is saved. Handle routing failures from your own store instead of counting on the message being delivered to you again:

```javascript theme={null}
app.post('/webhooks/inbound', express.json({ limit: '50mb' }), async (req, res) => {
  // Persist first, so a routing bug never loses a message
  const deliveryId = await storeInboundPayload(req.body);
  res.sendStatus(200);

  for (const relay of relayMessages(req.body)) {
    try {
      await routeEmail(relay);
    } catch (error) {
      console.error('Routing error:', error);
      // Keep it for manual review or your own retry job
      await markForReview(deliveryId, relay, error.message);
    }
  }
});
```

> [!NOTE]
>
> The same message can occasionally arrive more than once. Make your routing idempotent, for example by skipping messages whose `Message-ID` header you have already handled. See [Best Practices](https://docs.lettr.com/learn/inbound/best-practices.md#implement-idempotency).

## Related Topics

> [card] [Email Parsing](https://docs.lettr.com/learn/inbound/parsing.md)
>
> The full inbound payload

> [card] [Reply Tracking](https://docs.lettr.com/learn/inbound/reply-tracking.md)
>
> Match replies to the emails you sent

> [card] [Spam Filtering](https://docs.lettr.com/learn/inbound/spam-filtering.md)
>
> Handle spam in your own code

> [card] [Best Practices](https://docs.lettr.com/learn/inbound/best-practices.md)
>
> Inbound best practices


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.