# Receive email in your app (/docs/guides/receive-email)

Every coss.com environment can receive email. Each message is stored as a **received email** and
announced by an `email.received` [webhook](/docs/webhooks); your handler fetches it and can reply.

## Get an inbound email address [#get-an-inbound-email-address]

Each environment has its own domain under coss.com's inbound domain, such as
`k3j9x2m7qp4l.inbound.coss.com`. Mail to **any** address at it (`support@…`, `orders+42@…`) is
received, with no DNS setup. Use the part before the `@` to route messages in your app.

```ts twoslash
import { Coss } from "coss";
const coss = new Coss();
// ---cut---
const { data: address } = await coss.email.received.address();
console.log(`Send a test email to hello@${address?.domain}`);
```

## Receive email at your own domain with an MX record [#receive-email-at-your-own-domain-with-an-mx-record]

To receive at `inbound.acme.com`, set up receiving on one of your [domains](/docs/email/domains)
and publish the `MX` record it lists:

```ts twoslash
import { Coss } from "coss";
const coss = new Coss();
declare const domainId: string;
// ---cut---
const { data: domain } = await coss.domains.receiving.create(domainId, {
  hostname: "inbound.acme.com",
});

const record = domain?.receiving?.record;
console.log(record?.type, record?.priority, record?.value);
```

- Use a subdomain. Pointing `acme.com` itself at coss.com moves **all** of its mail here, your
  team's mailboxes included.
- The environment of the API key that sets it up receives the mail. Mail to an address nobody
  receives at is dropped without a bounce.

## Handle the email.received webhook in Next.js [#handle-the-emailreceived-webhook-in-nextjs]

Subscribe a [webhook endpoint](/docs/webhooks) to `email.received`. The event says who sent what
to whom, never the content, so fetch the email for its bodies:

```ts twoslash title="app/webhooks/coss/route.ts"
declare function handleSupportEmail(input: { from: string; subject: string; text: string }): Promise<void>;
// ---cut---
import { Coss, verifyWebhook, WebhookVerificationError } from "coss";

const coss = new Coss();

export async function POST(request: Request) {
  try {
    const event = await verifyWebhook(await request.text(), request.headers, process.env.COSS_WEBHOOK_SECRET!);
    if (event.type !== "email.received" || event.data.spam) return new Response("ok");

    const { data: email, error } = await coss.email.received.get(event.data.received_email_id);
    if (error) return new Response("try again", { status: 500 }); // coss.com retries the event

    await handleSupportEmail({
      from: email.from ?? email.mail_from,
      subject: email.subject ?? "(no subject)",
      text: email.text ?? "",
    });
    return new Response("ok");
  } catch (error) {
    if (error instanceof WebhookVerificationError) {
      return new Response("invalid signature", { status: 400 });
    }
    throw error;
  }
}
```

- `recipients` are the envelope addresses your environment received the message for, Bcc'd ones
  included: use them to tell `support@` from `orders@`.
- `html` comes from whoever sent the email. Sanitize it before you show it to anyone.
- Webhooks can arrive twice: skip an `event.id` you already handled.

## Download attachments [#download-attachments]

The email lists its attachments' metadata; download each one's bytes:

```ts twoslash
import { Coss, type ReceivedEmail } from "coss";
const coss = new Coss();
declare const email: ReceivedEmail;
// ---cut---
for (const attachment of email.attachments) {
  const { data: bytes } = await coss.email.received.getAttachment(email.id, attachment.id);
  console.log(attachment.filename, attachment.content_type, bytes?.byteLength);
}
```

Attachments are served as `application/octet-stream`, whatever they claim to be. Long bodies and
headers are cut (`truncated: true`); `getRaw()` returns the whole message as received.

## Reply to a received email [#reply-to-a-received-email]

Send a normal email with `In-Reply-To` and `References` set, so mail clients show the reply in the
same thread. With a live key, `from` must be on one of your verified domains.

```ts twoslash
import { Coss, type ReceivedEmail } from "coss";
const coss = new Coss();
declare const email: ReceivedEmail;
// ---cut---
if (email.message_id) {
  await coss.email.send({
    from: "Acme Support <support@acme.com>",
    to: email.reply_to.length > 0 ? email.reply_to : (email.from ?? email.mail_from),
    subject: `Re: ${email.subject ?? ""}`,
    text: "Thanks, we're on it.",
    headers: {
      "In-Reply-To": email.message_id,
      References: [...email.references, email.message_id].join(" "),
    },
  });
}
```

## Spam, viruses and limits [#spam-viruses-and-limits]

Every message is scanned on arrival. `verdicts` holds the spam and virus scans and the SPF, DKIM
and DMARC checks (`pass`, `fail`, `gray` or `processing_failed`).

- Spam (`spam: true`) and mail that fails authentication is still received: decide in your handler.
- A message with a virus is `blocked`: its content is never stored and no webhook is sent.
- Organizations have daily [limits](/docs/email/receiving#limits-and-retention) on received messages
  and data, and a maximum message size. Mail over a limit is dropped and counted in the dashboard.
- Received emails are kept for 30 days.

## Test receiving in a sandbox [#test-receiving-in-a-sandbox]

In a sandbox environment, **Send a test email** on the **Received emails** page receives a message
without sending one. Put `[coss-test:spam]`, `[coss-test:virus]`, `[coss-test:spf-fail]`,
`[coss-test:dkim-fail]` or `[coss-test:dmarc-fail]` in its subject to try each verdict. Real mail to
your inbound address works too.

Forward events to your local server with `coss listen`, and follow what arrives with `coss inbox`:

```sh
coss listen --forward-to localhost:3000/webhooks/coss
coss inbox   # prints the inbound domain, then each email as it arrives
```

Building an AI agent that answers email? [Inboxes](/docs/inboxes) give each agent its own address,
keep received mail as threads and reply from the same address.

## Next steps [#next-steps]

- [Receiving email](/docs/email/receiving): every field, verdict and limit.
- [Verify webhook signatures in Node.js](/docs/guides/verify-webhook-signatures).
- [Give an AI agent its own email address](/docs/guides/ai-agent-email).
