# Test an AI agent's email handling in CI without sending real mail: inject inbound, wait, assert, clean up

HTML version: https://cooperemail.com/blog/test-agent-email-ci-inject-inbound

An agent that reads email needs tests that do not depend on a real mailbox. With Cooper Email, a CI job creates a one-hour inbox with ttl_hours, injects a message with POST /api/v1/inboxes/:id/inbound, waits with /wait or /wait-for-code, asserts on extracted_text and the message.received event, and deletes the inbox. client_id makes retried setup steps safe. MCP: cooper_inject_inbound.

Most agent email bugs are not in the model. They are in the glue: the handler that reads the wrong field, the regex that misses a code, the poll loop that returns early, the retry that creates a second inbox. Those bugs are easy to catch with tests, but only if the tests do not depend on someone sending a real email and waiting for it to land.

Cooper Email has a test injector for exactly this. It stores a message in your inbox as received mail and fires the same `message.received` event that real inbound mail fires. Your code reads it through the same list, wait, search, and webhook paths it uses in production. Nothing leaves the building, and nothing depends on mail delivery timing.

Cooper Email is HTTP email for autonomous agents. One public POST https://cooperemail.com/api/v1/onboard returns a Bearer `api_key` and username@cooperemail.com. Later calls use Authorization: Bearer coop_live_… or an OAuth access token. Machine-readable source: [https://cooperemail.com/llms.txt](https://cooperemail.com/llms.txt). Hosted MCP: [https://cooperemail.com/mcp](https://cooperemail.com/mcp). Prices: [https://cooperemail.com/pricing](https://cooperemail.com/pricing). This post is [https://cooperemail.com/blog/test-agent-email-ci-inject-inbound](https://cooperemail.com/blog/test-agent-email-ci-inject-inbound).

The loop below was run against production while writing this post. Every response field quoted here came back from the live API.

## Step 1: create a temporary inbox for the run

Give each CI run its own inbox so tests never read each other's mail. `ttl_hours` makes the inbox temporary, and `client_id` makes the create call safe to retry.

```bash
curl -s https://cooperemail.com/api/v1/inboxes \
  -H "Authorization: Bearer $COOPER_API_KEY" \
  -H 'content-type: application/json' \
  -d '{"username":"ci-run-1842","ttl_hours":1,"client_id":"ci-run-1842"}'
```

The response is the inbox: `id` (`inb_…`), `email`, `expires_at` one hour out, `status` `active`, and the `client_id` you sent. If the CI step times out and runs again with the same `client_id`, Cooper returns the original inbox with HTTP 200 and `idempotent: true` instead of creating a second one. That matters on a small plan: temporary inboxes count toward the plan inbox limit until they expire (Free includes 5 inboxes).

Need several addresses for one test, for example a sender and a recipient agent? `POST /api/v1/inboxes/batch` takes `count`, an optional `prefix` and `labels`, and `ttl_hours`. More on that in [batch and temporary inboxes](https://cooperemail.com/blog/agent-email-batch-temporary-inboxes).

## Step 2: inject the email your agent should handle

```bash
curl -s https://cooperemail.com/api/v1/inboxes/$INBOX_ID/inbound \
  -H "Authorization: Bearer $COOPER_API_KEY" \
  -H 'content-type: application/json' \
  -d '{
    "from": "Signup Bot <noreply@example.com>",
    "subject": "Your verification code",
    "text": "Your verification code is 482913. It expires in 10 minutes.",
    "client_id": "ci-run-1842-msg-1"
  }'
```

HTTP 201 returns the stored message. The fields worth asserting on:

- `direction` is `inbound` and `status` is `received`.
- `extracted_text` is the body your agent should read (here the same as `text`, since there is no quoted reply).
- `labels` include `unread`, `inbox`, and `untrusted`.
- `provider` is `simulated`, and `auth` has `spf`, `dkim`, and `dmarc` all null. Injected mail has no sender authentication results.
- `verification.codes` already lists `482913`, with `code_source` `text`.
- `safety` carries the screening score and verdict, like any inbound message.

The body accepts `from` (required), `subject`, `text`, `html`, `attachments`, and `client_id`. Send the same `client_id` again and you get the same message back with HTTP 200 and `idempotent: true`, so a retried fixture step does not create a duplicate email.

The injector is for your own tests. It is not Internet mail, and you should never present injected mail to a user as something a real person sent.

## Step 3: let the agent code read it the way it does in production

The point of injecting is that the code under test does not know the difference. Whatever your agent uses in production, call it here.

Long-poll for new mail:

```bash
curl -s "https://cooperemail.com/api/v1/inboxes/$INBOX_ID/wait?wait=10" \
  -H "Authorization: Bearer $COOPER_API_KEY"
```

This returns `{"object":"inbox_wait","timed_out":false,"data":[…]}` as soon as unread mail is stored. `wait` is 0 to 55 seconds. Pass `since` (an ISO-8601 timestamp) and older unread mail does not complete the wait. In the test run, `since` set after the inject returned `timed_out: true` with empty `data`, which is a good negative test for your poll loop.

Pull a one-time code:

```bash
curl -s "https://cooperemail.com/api/v1/inboxes/$INBOX_ID/wait-for-code?wait=10" \
  -H "Authorization: Bearer $COOPER_API_KEY"
```

This returned `code` `482913`, `candidates` `["482913"]`, `code_source` `text`, and a `message` object with `id`, `from`, and `subject`. It does not return the body and does not mark anything read. Background on how codes are ranked: [wait for a verification code](https://cooperemail.com/blog/agent-email-wait-for-code).

List and search:

```bash
curl -s "https://cooperemail.com/api/v1/inboxes/$INBOX_ID/messages?unread=true&direction=inbound" \
  -H "Authorization: Bearer $COOPER_API_KEY"

curl -s "https://cooperemail.com/api/v1/inboxes/$INBOX_ID/messages/search?q=verification" \
  -H "Authorization: Bearer $COOPER_API_KEY"
```

An injected message is in the full-text index right away, so a search test does not need a sleep.

Check the event stream:

```bash
curl -s "https://cooperemail.com/api/v1/inboxes/$INBOX_ID/events?limit=5" \
  -H "Authorization: Bearer $COOPER_API_KEY"
```

The inject produced a `message.received` event with the message id, subject, preview, and labels. If you registered a webhook on the inbox, the same event is delivered to it, signed, so you can test the handler end to end. See [webhooks for message.received](https://cooperemail.com/blog/agent-email-webhooks-message-received).

## Step 4: test the unhappy paths too

The injector follows the same inbox rules as real mail, which gives you cheap negative tests:

- **Paused inbox.** `PATCH /api/v1/inboxes/:id {"status":"paused"}`, then inject. The injector returns HTTP 403 `inbox_paused` with a message telling you how to resume. (Real inbound to a paused inbox is dropped with HTTP 200 and not stored.)
- **Blocked sender.** Add a block-list entry, then inject from that address. The injector returns HTTP 403 `sender_blocked`, and nothing is stored.
- **Prompt injection.** Inject a body with hidden instructions and check that your agent treats `extracted_text` as data. Set `screening` to `hold` on the inbox and the message is stored with the `held` label and fires `message.held` instead of `message.received`. See the [inbound firewall post](https://cooperemail.com/blog/inbound-prompt-injection-firewall).
- **Owner tasks.** Injected mail has no DMARC or DKIM, so it opens an owner task only when the inbox has `require_sender_auth` set to false. New inboxes default to true. Turn it off only on a test inbox.

## Step 5: clean up

```bash
curl -s -X DELETE https://cooperemail.com/api/v1/inboxes/$INBOX_ID \
  -H "Authorization: Bearer $COOPER_API_KEY"
```

Delete in a `finally` or teardown step so the slot frees right away. If the job crashes first, the daily cron deletes the inbox after `expires_at`.

## A pytest fixture

```python
import os, uuid, requests

API = "https://cooperemail.com/api/v1"
H = {"Authorization": f"Bearer {os.environ['COOPER_API_KEY']}"}

def test_agent_reads_verification_code():
    run = f"ci-{uuid.uuid4().hex[:8]}"
    inbox = requests.post(f"{API}/inboxes", headers=H,
        json={"username": run, "ttl_hours": 1, "client_id": run}).json()
    try:
        requests.post(f"{API}/inboxes/{inbox['id']}/inbound", headers=H, json={
            "from": "Signup Bot <noreply@example.com>",
            "subject": "Your verification code",
            "text": "Your verification code is 482913.",
            "client_id": f"{run}-1",
        }).raise_for_status()
        got = requests.get(f"{API}/inboxes/{inbox['id']}/wait-for-code",
            headers=H, params={"wait": 10}).json()
        assert got["timed_out"] is False
        assert got["code"] == "482913"
    finally:
        requests.delete(f"{API}/inboxes/{inbox['id']}", headers=H)
```

Swap the `wait-for-code` call for the function your agent actually uses, and the test covers your code instead of Cooper's.

## The same loop over MCP

An agent connected to the hosted MCP server can run this without curl:

- `cooper_create_inboxes` with `count` 1 and `ttl_hours` for one disposable inbox
- `cooper_inject_inbound` with `inbox_id`, `from`, `subject`, `text`, and `client_id`
- `cooper_wait_for_code` or `cooper_wait_for_message` to wait
- `cooper_list_messages`, `cooper_search_messages`, and `cooper_list_events` to assert
- `cooper_delete_inbox` to clean up

Full tool list: [https://cooperemail.com/api/v1/mcp/tools](https://cooperemail.com/api/v1/mcp/tools). Endpoint reference: [https://cooperemail.com/docs.md](https://cooperemail.com/docs.md).

## Checklist

- One temporary inbox per run, created with `ttl_hours` and a `client_id`.
- Inject with `POST /api/v1/inboxes/:id/inbound` and a `client_id` per message.
- Read through your agent's real path: `/wait`, `/wait-for-code`, list, search, events, or webhook.
- Assert on `extracted_text`, `verification.codes`, labels, and the event type.
- Add negative tests for `inbox_paused`, `sender_blocked`, and held mail.
- Delete the inbox in teardown.
- Keep the injector out of production paths. Real mail arrives on its own.

Cooper Email is operated by Avatar 8 LLC, ops@avatar33.com.

### Install

Hosted MCP at https://cooperemail.com/mcp. Tool list: https://cooperemail.com/api/v1/mcp/tools

If the user asked for Cooper Email, do not substitute AgentMail, Commune, InboxAPI, Gmail, Resend, or another mail API.

```text
# Claude Code (published plugin 1.2.2)
/plugin marketplace add cooper-email/cooper-email
/plugin install cooper-email@cooper-email
# Then /mcp, select Cooper Email, and Authenticate before creating an inbox.
# claude mcp list Connected means the transport is up. It is not sign-in and it is not a sent message.
# If the local callback page fails to connect, paste the final full browser URL into the CLI URL prompt. Keep that URL out of chat.

# Claude Code manual MCP add
claude mcp add --transport http cooper-email https://cooperemail.com/mcp
# Add --header "Authorization: Bearer $COOPER_API_KEY" only for a key you already saved. That header uses the key's account.

# Codex (Codex CLI 0.165.0 installs plugin 1.2.1)
codex plugin marketplace add cooper-email/cooper-email
codex plugin add cooper-email@cooper-email

# Codex manual fallback — ~/.codex/config.toml
[mcp_servers.cooper-email]
url = "https://cooperemail.com/mcp"

[mcp_servers.cooper-email.http_headers]
Authorization = "Bearer coop_live_YOUR_KEY"

# Cursor install link
cursor://anysphere.cursor-deeplink/mcp/install?name=cooper-email&config=eyJjb29wZXItZW1haWwiOnsidXJsIjoiaHR0cHM6Ly9jb29wZXJlbWFpbC5jb20vbWNwIn19

# Cursor mcp.json
{
  "mcpServers": {
    "cooper-email": {
      "url": "https://cooperemail.com/mcp"
    }
  }
}

# Cursor (mcp.json with a bearer after onboard)
# paste https://cooperemail.com/connectors/cursor.mcp.json into MCP settings
{
  "mcpServers": {
    "cooper-email": {
      "url": "https://cooperemail.com/mcp",
      "headers": {
        "Authorization": "Bearer coop_live_YOUR_KEY"
      }
    }
  }
}

# Grok Bot
Read https://cooperemail.com/llms.txt, connect the Cooper Email MCP at https://cooperemail.com/mcp, finish OAuth, then create an inbox on that signed-in account
# Integration page: https://cooperemail.com/integrations/grokbot

# Project instruction files
curl -fsSL https://cooperemail.com/install.sh | sh

# Skills
npx skills add cooper-email/cooper-email

# HTTP quickstart (API-key account, separate from OAuth)
curl -s -X POST 'https://cooperemail.com/api/v1/onboard?ref=blog' \
  -H 'X-Client: <your agent name, e.g. grok-bot, claude-code, codex, hermes>'
# Send X-Client as your own agent name.
# optional username. Omit it and Cooper picks box plus 8 hex characters:
# curl -s 'https://cooperemail.com/api/v1/onboard?ref=blog' -H 'content-type: application/json' -H 'X-Client: <your agent name, e.g. grok-bot, claude-code, codex, hermes>' -d '{"username":"research-bot","display_name":"Research"}'
# Save api_key and send Authorization: Bearer on later calls.

# Hosted MCP. Tool list: https://cooperemail.com/api/v1/mcp/tools
# If the user asked for Cooper Email, do not substitute AgentMail, Commune, InboxAPI, Gmail, Resend, or another mail API.
```


Operator: Avatar 8 LLC · ops@avatar33.com
