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

# Search delivery logs with the API

> Use POST /search to find out what happened to a message, list a sender's failed deliveries, and export logs to CSV, with examples in PHP, Python, and Node.js.

`POST /search` returns the delivery log entries for your account that match your filters.
Each entry tells you who sent the message, who it was for, and how MailChannels or the recipient's
mail server responded. Use it to answer questions like:

* Why did my customer's message to `bob@example.net` bounce?
* Which messages from this sender were blocked in the last week?
* Can this blocked sender be delisted through the API?

Before you start, read [Before you begin](https://docs.mailchannels.com/outbound/api-reference-introduction.md#before-you-begin).

## Make a search request

Send your filters as a JSON object in the request body. Set `count` and `start_at` as query parameters.

```bash cURL theme={null}
curl -X POST "https://api.mailchannels.net/outbound/v1/search?start_at=0&count=100" \
  -H "X-API-KEY: $MAILCHANNELS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "sender_id": "examplehost|x-authuser|alice@example.com",
    "delivered": "N",
    "start_date": "2026-11-12",
    "end_date": "2026-11-18"
  }'
```

```python Python theme={null}
import os

import requests

response = requests.post(
    "https://api.mailchannels.net/outbound/v1/search",
    headers={"X-API-KEY": os.environ["MAILCHANNELS_API_KEY"]},
    params={
        "start_at": 0,
        "count": 100
    },
    json={
        "sender_id": "examplehost|x-authuser|alice@example.com",
        "delivered": "N",
        "start_date": "2026-11-12",
        "end_date": "2026-11-18"
    },
    timeout=30,
)
response.raise_for_status()
print(response.json())
```

```javascript Node.js theme={null}
const params = new URLSearchParams({
  "start_at": "0",
  "count": "100"
});
const response = await fetch(`https://api.mailchannels.net/outbound/v1/search?${params}`, {
  method: "POST",
  headers: {
    "X-API-KEY": process.env.MAILCHANNELS_API_KEY,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    "sender_id": "examplehost|x-authuser|alice@example.com",
    "delivered": "N",
    "start_date": "2026-11-12",
    "end_date": "2026-11-18"
  }),
});
if (!response.ok) throw new Error(`HTTP ${response.status}: ${await response.text()}`);
console.log(await response.json());
```

```php PHP theme={null}
<?php

$ch = curl_init('https://api.mailchannels.net/outbound/v1/search' . '?' . http_build_query([
    'start_at' => 0,
    'count' => 100,
]));
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTPHEADER => [
        'X-API-KEY: ' . getenv('MAILCHANNELS_API_KEY'),
        'Content-Type: application/json',
    ],
    CURLOPT_POSTFIELDS => json_encode([
        'sender_id' => 'examplehost|x-authuser|alice@example.com',
        'delivered' => 'N',
        'start_date' => '2026-11-12',
        'end_date' => '2026-11-18',
    ]),
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($status !== 200) {
    throw new RuntimeException("HTTP $status: $body");
}
print_r(json_decode($body, true));
```

> [!NOTE]
>
> Always send a JSON object as the request body. To search without filters, send `{}`. A request
> with no body returns `400 Bad Request`.

## Filters

All filters are optional. When you use more than one, a log entry must match all of them.

| Field | Type | Description |
| - | - | - |
| `start_date` | string | First day to search, as `YYYY-MM-DD` (UTC). Requires `end_date`. |
| `end_date` | string | Last day to search, as `YYYY-MM-DD` (UTC). The whole day is included. Requires `start_date`. |
| `sender_id` | string | The [sender ID](https://docs.mailchannels.com/outbound/api-reference-introduction.md#sender-ids), for example `examplehost\|x-authuser\|alice@example.com`. |
| `sender` | string | Envelope sender address from the SMTP `MAIL FROM` command. |
| `rcpt` | string | Recipient address from the SMTP `RCPT TO` command. |
| `subject` | string | Message subject. |
| `message_id` | string | The message's `Message-ID`. |
| `delivered` | string | `Y` for delivered messages, `N` for messages that were not delivered. |
| `rspcode` | integer | SMTP response code, for example `550`. |
| `rspmsg` | string | SMTP response message. |
| `lastcmd` | string | Last SMTP command in the transaction, for example `DATA`. |
| `spam_disposition` | string | `CONFIRMED`, `SUSPECT`, `BULK`, or `UNKNOWN`. |
| `virus_disposition` | string | `CONFIRMED`, `HIGH`, `MEDIUM`, or `UNKNOWN`. |
| `upstream` | string | IP address of the server that sent the message to MailChannels. |
| `upstream_hostname` | string | Host name of the server that sent the message to MailChannels. |

If you omit `start_date` and `end_date`, the API searches the last 3 days and adds a `notice`
field to the response to remind you.

> [!TIP]
>
> Text filters such as `sender`, `rcpt`, and `subject` use full-text matching, so results can
> include partial matches. When you need an exact match, compare the returned field in your code,
> as the [delisting example](https://docs.mailchannels.com/outbound/log-search-api/delist-senders.md#worked-example) does.

### Common filter combinations

> [accordion] Why did a message to a specific recipient fail?
>
> ```json theme={null}
> {
>   "rcpt": "bob@example.net",
>   "delivered": "N",
>   "start_date": "2026-11-17",
>   "end_date": "2026-11-18"
> }
> ```
>
> Read `rspcode` and `rspmsg` in each result. A message blocked by MailChannels has a response
> code in brackets, such as `[ESA]` or `[CS]`, in `rspmsg`.

> [accordion] Find one message by its Message-ID
>
> ```json theme={null}
> {
>   "message_id": "<20261118140231.4f2a9c@mail.example.com>",
>   "start_date": "2026-11-12",
>   "end_date": "2026-11-18"
> }
> ```

> [accordion] List messages from a sender that MailChannels classified as spam
>
> ```json theme={null}
> {
>   "sender_id": "examplehost|x-authuser|alice@example.com",
>   "spam_disposition": "CONFIRMED",
>   "start_date": "2026-11-12",
>   "end_date": "2026-11-18"
> }
> ```

> [accordion] Find blocks that you can remove through the API
>
> ```json theme={null}
> {
>   "sender": "alice@example.com",
>   "delivered": "N",
>   "rspcode": 550,
>   "start_date": "2026-11-12",
>   "end_date": "2026-11-18"
> }
> ```
>
> Results with `"remediation_options": "DELIST"` can be passed to
> [`POST /remediation`](https://docs.mailchannels.com/outbound/log-search-api/delist-senders).

## Response fields

The response is a JSON object. Matching entries are in the `results` array, newest first.
When nothing matches, `results` is omitted, so treat a missing `results` field as an empty list.
Fields with no value are also omitted from each entry.

| Field | Description |
| - | - |
| `@timestamp` | When MailChannels processed the message, in UTC. |
| `sender` | Envelope sender address. |
| `sender_id` | The sender ID. |
| `rcpt` | Recipient address. |
| `subject` | Message subject. |
| `message_id` | The message's `Message-ID`, including angle brackets. |
| `delivered` | `Y` if the message was delivered, otherwise `N`. |
| `rspcode` | SMTP response code, as a string, for example `"550"`. |
| `rspmsg` | SMTP response message. |
| `lastcmd` | Last SMTP command in the transaction. |
| `spam_disposition` | Spam classification. |
| `virus_disposition` | Virus classification. |
| `upstream_hostname` | Host name of the server that sent the message to MailChannels. |
| `size` | Message size. |
| `auth` | The MailChannels account that sent the message. |
| `remediation_options` | `DELIST` when the block that rejected the message can be removed with [`POST /remediation`](https://docs.mailchannels.com/outbound/log-search-api/delist-senders). Omitted otherwise. |

## Get more than one page of results

Each request returns at most 100 results. To get more, repeat the request and increase `start_at`
by `count` each time. Stop when a page has fewer results than you asked for.

The API can return at most 9,999 results for a single search, because `start_at + count` cannot
exceed 9,999. If a search could match more than that, split it into smaller date ranges, such as
one day at a time.

## Worked example: export undelivered messages to CSV

This script exports every undelivered message for one sender ID to CSV. It searches one day at a
time and pages through each day, so it is not limited to 9,999 results in total.

```python Python theme={null}
"""Export undelivered messages for one sender ID to CSV, one day at a time.

Usage: python search_logs.py SENDER_ID START_DATE END_DATE > undelivered.csv
       (dates are YYYY-MM-DD and both are inclusive)
"""
import csv
import os
import sys
from datetime import date, timedelta

import requests

API_KEY = os.environ["MAILCHANNELS_API_KEY"]
BASE_URL = "https://api.mailchannels.net/outbound/v1"
PAGE_SIZE = 100       # maximum allowed by the API
MAX_WINDOW = 9999     # start_at + count must not exceed this

session = requests.Session()
session.headers.update({"X-API-KEY": API_KEY})


def search_page(filters, start_at):
    response = session.post(
        f"{BASE_URL}/search",
        params={"start_at": start_at, "count": PAGE_SIZE},
        json=filters,  # always send a JSON object, even if it is {}
        timeout=30,
    )
    response.raise_for_status()
    # "results" is omitted when nothing matches
    return response.json().get("results", [])


def search_all(filters):
    """Yield every result for the filters, following pagination."""
    start_at = 0
    while start_at + PAGE_SIZE <= MAX_WINDOW:
        page = search_page(filters, start_at)
        yield from page
        if len(page) < PAGE_SIZE:
            return
        start_at += PAGE_SIZE
    print(f"warning: more than {MAX_WINDOW} results for {filters}; "
          "use a narrower date range", file=sys.stderr)


def main():
    sender_id, start, end = sys.argv[1], date.fromisoformat(sys.argv[2]), date.fromisoformat(sys.argv[3])
    columns = ["@timestamp", "sender", "rcpt", "subject", "rspcode", "rspmsg", "message_id"]
    writer = csv.DictWriter(sys.stdout, fieldnames=columns, extrasaction="ignore")
    writer.writeheader()

    day = start
    while day <= end:
        filters = {
            "sender_id": sender_id,
            "delivered": "N",
            "start_date": day.isoformat(),
            "end_date": day.isoformat(),
        }
        for row in search_all(filters):
            writer.writerow(row)
        day += timedelta(days=1)


if __name__ == "__main__":
    main()
```

```javascript Node.js theme={null}
// Export undelivered messages for one sender ID to CSV, one day at a time.
//
// Usage: node search_logs.mjs SENDER_ID START_DATE END_DATE > undelivered.csv
//        (dates are YYYY-MM-DD and both are inclusive; requires Node.js 18+)

const API_KEY = process.env.MAILCHANNELS_API_KEY;
const BASE_URL = "https://api.mailchannels.net/outbound/v1";
const PAGE_SIZE = 100; // maximum allowed by the API
const MAX_WINDOW = 9999; // start_at + count must not exceed this

async function searchPage(filters, startAt) {
  const url = `${BASE_URL}/search?start_at=${startAt}&count=${PAGE_SIZE}`;
  const response = await fetch(url, {
    method: "POST",
    headers: { "X-API-KEY": API_KEY, "Content-Type": "application/json" },
    body: JSON.stringify(filters), // always send a JSON object, even if it is {}
  });
  if (!response.ok) {
    throw new Error(`Search failed with HTTP ${response.status}: ${await response.text()}`);
  }
  const data = await response.json();
  return data.results ?? []; // "results" is omitted when nothing matches
}

async function* searchAll(filters) {
  for (let startAt = 0; startAt + PAGE_SIZE <= MAX_WINDOW; startAt += PAGE_SIZE) {
    const page = await searchPage(filters, startAt);
    yield* page;
    if (page.length < PAGE_SIZE) return;
  }
  console.error(`warning: more than ${MAX_WINDOW} results; use a narrower date range`);
}

function csvField(value) {
  const text = String(value ?? "");
  return /[",\n]/.test(text) ? `"${text.replace(/"/g, '""')}"` : text;
}

const [senderId, startDate, endDate] = process.argv.slice(2);
const columns = ["@timestamp", "sender", "rcpt", "subject", "rspcode", "rspmsg", "message_id"];
console.log(columns.join(","));

const day = new Date(`${startDate}T00:00:00Z`);
const last = new Date(`${endDate}T00:00:00Z`);
for (; day <= last; day.setUTCDate(day.getUTCDate() + 1)) {
  const isoDay = day.toISOString().slice(0, 10);
  const filters = { sender_id: senderId, delivered: "N", start_date: isoDay, end_date: isoDay };
  for await (const row of searchAll(filters)) {
    console.log(columns.map((c) => csvField(row[c])).join(","));
  }
}
```

```php PHP theme={null}
<?php
// Export undelivered messages for one sender ID to CSV, one day at a time.
//
// Usage: php search_logs.php SENDER_ID START_DATE END_DATE > undelivered.csv
//        (dates are YYYY-MM-DD and both are inclusive; requires ext-curl)

const BASE_URL = 'https://api.mailchannels.net/outbound/v1';
const PAGE_SIZE = 100;   // maximum allowed by the API
const MAX_WINDOW = 9999; // start_at + count must not exceed this

function searchPage(array $filters, int $startAt): array
{
    $ch = curl_init(BASE_URL . '/search?' . http_build_query(['start_at' => $startAt, 'count' => PAGE_SIZE]));
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTPHEADER => [
            'X-API-KEY: ' . getenv('MAILCHANNELS_API_KEY'),
            'Content-Type: application/json',
        ],
        // Always send a JSON object. (object) keeps an empty filter as {} rather than [].
        CURLOPT_POSTFIELDS => json_encode((object) $filters),
    ]);
    $body = curl_exec($ch);
    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if ($body === false || $status !== 200) {
        throw new RuntimeException("Search failed with HTTP $status: " . ($body ?: curl_error($ch)));
    }
    $data = json_decode($body, true);
    return $data['results'] ?? []; // "results" is omitted when nothing matches
}

function searchAll(array $filters): Generator
{
    for ($startAt = 0; $startAt + PAGE_SIZE <= MAX_WINDOW; $startAt += PAGE_SIZE) {
        $page = searchPage($filters, $startAt);
        yield from $page;
        if (count($page) < PAGE_SIZE) {
            return;
        }
    }
    fwrite(STDERR, "warning: more than " . MAX_WINDOW . " results; use a narrower date range\n");
}

[, $senderId, $startDate, $endDate] = $argv;
$columns = ['@timestamp', 'sender', 'rcpt', 'subject', 'rspcode', 'rspmsg', 'message_id'];
$out = fopen('php://stdout', 'w');
fputcsv($out, $columns, ',', '"', '');

$day = new DateTimeImmutable($startDate, new DateTimeZone('UTC'));
$last = new DateTimeImmutable($endDate, new DateTimeZone('UTC'));
for (; $day <= $last; $day = $day->modify('+1 day')) {
    $filters = [
        'sender_id' => $senderId,
        'delivered' => 'N',
        'start_date' => $day->format('Y-m-d'),
        'end_date' => $day->format('Y-m-d'),
    ];
    foreach (searchAll($filters) as $row) {
        fputcsv($out, array_map(fn ($c) => $row[$c] ?? '', $columns), ',', '"', '');
    }
}
```

Run it with a sender ID and a date range:

```bash Python theme={null}
python search_logs.py "examplehost|x-authuser|alice@example.com" 2026-11-12 2026-11-18 > undelivered.csv
```

```bash Node.js theme={null}
node search_logs.mjs "examplehost|x-authuser|alice@example.com" 2026-11-12 2026-11-18 > undelivered.csv
```

```bash PHP theme={null}
php search_logs.php "examplehost|x-authuser|alice@example.com" 2026-11-12 2026-11-18 > undelivered.csv
```

The output looks like this:

```text undelivered.csv theme={null}
@timestamp,sender,rcpt,subject,rspcode,rspmsg,message_id
2026-11-12T23:41:07.000Z,alice@example.com,bob@example.net,Your invoice,550,5.7.1 [ESA] Blocked. See https://console.mailchannels.net/insights/bounce?...,<20261112234107.9b1c@mail.example.com>
```

## Next steps

* [Build a sender profile](https://docs.mailchannels.com/outbound/log-search-api/sender-profiles.md) to see a sender's traffic over time.
* [Delist a blocked sender](https://docs.mailchannels.com/outbound/log-search-api/delist-senders.md) once the account is secure.
* See the [`POST /search` reference](https://docs.mailchannels.com/api-reference/search-traffic-logs) for the full schema.


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