
# Sending email

Your app sends email by posting to Agent Cloud, which sends each message once per key: production sends, while mirrors and rehearsals only capture. Call `POST $AGC_EMAIL_URL` with `Authorization: Bearer $AGC_EMAIL_TOKEN` and `{"to", "subject", "text", "key"}`; both variables are set wherever the app runs.

Success is HTTP 200 with `"status": "sent"` in production, `"captured"` on a mirror or rehearsal, and `"duplicate"` for a key already used.

## Ask your agent

```text
Email parents a booking confirmation after they book. Send it from the background
worker through Agent Cloud, make sure a retry can never email anyone twice, and add
a check that proves it.
```

Nothing is delivered from your mirror; ask to see `agc outbox`.

## Steps

From the [worker](/docs/build/background-work-and-workers.md):

```js
const res = await fetch(process.env.AGC_EMAIL_URL, {
  method: 'POST',
  headers: { authorization: `Bearer ${process.env.AGC_EMAIL_TOKEN}`, 'content-type': 'application/json' },
  body: JSON.stringify({
    to: parent.email,
    subject: `Booking confirmed: ${camp.name}`,
    text: `You're booked for ${camp.name}.`,
    key: `booking-${booking.id}/confirmation`,
  }),
});
if (!res.ok) throw new Error(`email answered ${res.status}`); // the job retries, same key
const { status } = await res.json(); // sent | captured | duplicate | failed
if (status === 'failed') throw new Error('send failed');
```

Prove it in a smoke flow:

```toml
[[check.smoke]]
name  = "each parent gets one confirmation"
steps = [
  "POST /api/camps {name: 'Race {run}', capacity: 20} -> 201 as camp",
  "POST /api/camps/{camp.id}/bookings {email: 'p{i}-{run}@example.test'} -> 201 x20",
  "MAIL p{i}-{run}@example.test -> 1 x20 within 30s",
]
```

```bash
agc check
agc outbox
```

## How it works

**The key is the message's identity.** Agent Cloud keeps one row per `(app, environment, key)`. The first post sends (or captures); a later one answers `duplicate`. So `key` names the message for good, never a fresh value per attempt. The provider gets it as its idempotency key. [Responses](/docs/reference/sign-in-broker-api.md#responses) says which retries send again, and why a changed Reply-To, header or attachment is 409 `email.key_reused`.

**Where mail goes.** Production sends unless held or over a limit. It captures mail to a [reserved domain](/docs/reference/sign-in-broker-api.md#where-mail-goes) like `example.test`, to protect the domain's bounce rate, and an app no person has claimed yet captures its mail until one does. Mirrors and rehearsals capture (`agc outbox`). A token names one app and environment. A rehearsal's works only while it runs, since its mail can hold production data. A deleted app's tokens stop at once.

**The sender** is Agent Cloud's shared app-sending domain, display name `agent.cloud`. An agent chooses an app's name, so no app name becomes a sender identity. Too many bounces or complaints [hold the app's mail](#email-holds-and-resume).

**Rehearsals** of a worker release kill workers mid-job and drop each first send's answer. Only a stable `key` keeps that retry from being a second email ([`MAIL` steps](/docs/checks/smoke-flows.md#mail)).

## Email holds and resume

Agent Cloud holds an app's production mail when its last 7 days have at least 50 sends and spam complaints pass 0.3% or hard bounces pass 4% of them. An owner resumes it in the console. Every app shares one domain, so one app's spam hurts all. Bounces and complaints count against the app that sent them, judged after every production send, bounce or complaint.

| Hold | |
|---|---|
| Recorded | Organization Activity (actor Agent Cloud, `email.held`, with counts); each owner gets one email |
| Production sends | 403 `email.held`, saved as `held`; mirrors, rehearsals, other apps and Agent Cloud's own mail carry on |
| Console | The app's **Observability** > **Email** page: "Production email is held", the time, the counts ("<n> spam complaints and <n> hard bounces in <n> messages sent over 7 days") and, for complaints, the top 10 recipient domains, never addresses |
| **Resume** | Owners only (others see "An owner of the organization can resume it."; a non-owner's post gets 403 "Only organization owners resume email"). Lifts the hold, restarts the count so earlier mail can't put it straight back, records `email.resumed` |
| Held messages | Not sent by **Resume**: the app retries them with their original keys, each counting from when it goes out |

Fix the cause first, or the next hold follows. It's usually mail nobody asked for, or to addresses that don't exist. One company domain among the complaints means a misconfigured internal list; consumer domains mean unwanted mail. Have the builder fix the recipient list or trigger and ship, then resume. It worked when the notice is gone and retries return sent.

## Email authentication

Platform mail (invites, domain codes, owner notices) and app mail go out from two subdomains with separate keys and reputations. Each has its own DKIM key, SPF return path and DMARC policy. A message passes when its headers show aligned SPF, DKIM and DMARC for its subdomain.

| Item | |
|---|---|
| From, production | Platform: `agent.cloud <no-reply@mail.agent.cloud>`; apps: `agent.cloud <apps@apps.agent.cloud>` |
| From, staging | Platform: `agent.cloud <no-reply@mail.staging-agent.cloud>`; apps: `agent.cloud <apps@apps.staging-agent.cloud>` |
| Mailers | One from `EMAIL_FROM` and `RESEND_API_KEY`, one from `APP_EMAIL_FROM` and `APP_RESEND_API_KEY`. Control won't start with only one of the app pair; with neither, apps use the platform sender |
| Key scope | Each Resend key sends only from its own domain, so app mail can't pass as the platform's |
| Tracking | Open and click tracking off |
| Tokens | `agce_` is an HMAC over app id and environment (and a copy's immutable id), so one can't become another's; copies capture |
| Webhooks | `POST /email/v1/events` needs a valid, fresh Resend signature under `RESEND_WEBHOOK_SECRET`, else 401, recording nothing |

| DNS record, per `<sub>` (`mail`, `apps`) and `<domain>` (`agent.cloud`, `staging-agent.cloud`) | Content |
|---|---|
| DKIM TXT `resend._domainkey.<sub>.<domain>`, CNAME `rsend.<sub>.<domain>` | Resend's values |
| MX and SPF TXT `send.<sub>.<domain>` | Return path; `include:amazonses.com` |
| DMARC TXT `_dmarc.<sub>.<domain>` | `v=DMARC1; p=<policy>; adkim=r; aspf=r;`, plus `rua=mailto:dmarc-reports@<domain>;` once reporting is configured |
| `<sub>.<domain>._report._dmarc.<domain>` | `v=DMARC1`, only with reporting |

Production's `mail` and `apps` subdomains publish `p=quarantine`; the apex `_dmarc.agent.cloud` record is left as it is. Staging uses `p=none` and moves to quarantine after a reviewed clean week of reports. Before a From address changes, the runbook requires every record Verified in Resend and `check-mail-dns.mjs` matching authoritative and independent recursive DNS.

## Reference

Request fields: [Email API: Request](/docs/reference/sign-in-broker-api.md#request). The answer is `{"id", "status"}`, with `"first": {"status", "at"}` on a `duplicate` ([Responses](/docs/reference/sign-in-broker-api.md#responses)).

## Errors

Every code, its exit and fix: [Error code catalog](/docs/reference/error-code-catalog.md). The email API's own answers are HTTP, shaped `{"error": {"code", "message", "fix"}}`, with no exit code ([Email errors](/docs/reference/sign-in-broker-api.md#email-errors)).

`agc up` with no manifest exits 1 before anything runs:

```json
{
  "ok": false,
  "product": "agent.cloud",
  "command": "up",
  "error": {
    "retryable": false,
    "code": "app.not_linked",
    "message": "No agentcloud.toml in this directory or above it.",
    "fix": "Run `agc init` in the app repository.",
    "docs": "agc help onboarding"
  },
  "next": [{ "cmd": "agc init", "why": "create the app on agent.cloud and write agentcloud.toml" }]
}
```

## Limits

Send rates and attachment caps: [Email limits](/docs/reference/sign-in-broker-api.md#email-limits) and [Request](/docs/reference/sign-in-broker-api.md#request). Platform mail gets 4 send attempts (now, then about 1, 5 and 30 minutes), and uncertain retries stop at 23 hours. The provider request times out at 15 s.

## Agent notes

- Send one message per recipient: `to` is one address (else 400 `email.bad_to`), and `text` is the plain-text body.
- Never generate a fresh key per attempt (a timestamp, a random id); the crash rehearsal catches it.
- Treat `failed`, 429 and 503 as retryable with the same key, and `duplicate` as success.
- Treat `email.held` as a stop, not a retry loop.
- Use `example.test` addresses in checks and seeds.
- Send through `$AGC_EMAIL_URL` only, and never configure your own sender on the shared domain.

## Related

- [Background work and workers](/docs/build/background-work-and-workers.md)
- [Email API](/docs/reference/sign-in-broker-api.md#email-api)
- [Smoke step grammar](/docs/checks/smoke-flows.md#step-grammar)
- [Production data protection](/docs/security/production-data-protection.md)
- [Activity log](/docs/owners/activity-log.md)

<!-- feedback:start -->
---
Wrong, outdated or unclear? Run `agc feedback docs "build/sending-email: <what is wrong>" --body <file>` with the sentence quoted in the file. No code or app data is sent.
<!-- feedback:end -->
