# Email API

> The REST API of Mailtrap Email Live Sending: an app sends email with one `POST` per message, or up to 500 per batch, from a verified sending domain, directly or through an official SDK.

## When to use it

Use it when the user's code sends email over HTTP or through a Mailtrap SDK. Pick the host by email type:

| Email type                                                                                               | Stream        | One message                                  | Up to 500 messages                            |
| -------------------------------------------------------------------------------------------------------- | ------------- | -------------------------------------------- | --------------------------------------------- |
| Triggered by a user action or event: sign-up, password reset, receipt, alert                             | Transactional | `POST https://send.api.mailtrap.io/api/send` | `POST https://send.api.mailtrap.io/api/batch` |
| Newsletters, promotions, any marketing email from the user's own code (Mailtrap requires Bulk for these) | Bulk          | `POST https://bulk.api.mailtrap.io/api/send` | `POST https://bulk.api.mailtrap.io/api/batch` |

- Requests, responses and the token are the same on both hosts; SDKs need the Bulk switch (step 3).
- If the stack only takes SMTP settings (a plugin, a platform, a framework mailer), use SMTP (products table at the end).
- If the email type isn't clear, ask. With no sign of promotions, use Transactional. Never send promotional email through Transactional. Sending the same email once to a list (reminders, notices) isn't triggered per recipient: ask which stream applies.

## How to use it

### Before you start

Find out the user's language or framework, sending domain and from address, email types, and whether they have an API token. Ask only for what isn't known.

### Rules

- **Read freely:** list and check domains, list templates, read Email Logs. Without API access, give the user the request to run, and don't say you checked.
- **Confirm first:** before adding a domain, and right before each live send the agent runs, unless the current request names the recipients and content. For a list you put together: show the count and a sample, give each recipient their own message (one batch item each, never the list in one `to`), and stop if the count exceeds the daily limit (Free: 150).
- **Secrets:** never ask for a token in chat. The user sets `MAILTRAP_API_TOKEN`, and code reads it. If the user pastes one anyway, don't use it: suggest a reset under Settings → API Tokens, and continue with the env var.
- **User only:** sign up at `mailtrap.io/register/signup`; create the first API token (Settings → API Tokens; Admin on the account to add domains, Admin on the domain to send); add the DNS records; complete compliance checks if asked.

### Steps

Send every request with `Authorization: Bearer $MAILTRAP_API_TOKEN`, `Content-Type: application/json` and a normal `User-Agent` (requests without one may be blocked).

1. **Check, then add the domain:** `GET https://mailtrap.io/api/domains`. If the domain is missing, confirm, then `POST https://mailtrap.io/api/domains` with `{"domain": {"domain_name": "example.com"}}`, and give the user every record in `dns_records` exactly as returned. A subdomain is verified as its own domain.
2. **Wait for verification:** poll `GET https://mailtrap.io/api/domains/{id}` until `dns_verified` is `true` and `compliance_status` is `compliant`; DNS usually takes a few hours. If the status asks for company info, a questionnaire or card verification, stop polling: the user completes it in the dashboard. For other statuses, ask the docs.
3. **Install the SDK,** or call the API over HTTPS. Take method names from the SDK's README (`github.com/mailtrap/mailtrap-<language>`); don't invent them.

   | Language | Install                                                                                                                                      | Bulk switch                        |
   | -------- | -------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------- |
   | Node.js  | `npm install mailtrap`                                                                                                                       | `bulk: true` in the client options |
   | Python   | `pip install mailtrap`                                                                                                                       | `bulk=True`                        |
   | PHP      | `composer require railsware/mailtrap-php symfony/http-client nyholm/psr7`                                                                    | `isBulk: true`                     |
   | Ruby     | `gem install mailtrap`                                                                                                                       | `bulk: true`                       |
   | Go       | `go get github.com/mailtrap/mailtrap-go`                                                                                                     | `mailtrap.WithBulk(true)`          |
   | Java     | `io.mailtrap:mailtrap-java`                                                                                                                  | `.bulk(true)`                      |
   | .NET     | From GitHub Packages, per the README (the user needs a GitHub token with `read:packages`); the nuget.org `Mailtrap` package isn't Mailtrap's | `.Bulk()` in place of `.Email()`   |

4. **Send** (confirm first, as in Rules). `from` must be on the verified domain.

   ```bash
   curl -X POST https://send.api.mailtrap.io/api/send \
     -H "Authorization: Bearer $MAILTRAP_API_TOKEN" -H "Content-Type: application/json" \
     -d '{"from":{"email":"hello@example.com","name":"Example App"},"to":[{"email":"user@example.org"}],"subject":"Welcome","text":"Thanks for signing up.","category":"Onboarding"}'
   ```

   - **Required:** `from`, `to` (or `cc`, `bcc`), and either `subject` with `text` and/or `html`, or `template_uuid` with `template_variables`, whose keys match the template's `{{...}}` placeholders (`GET https://mailtrap.io/api/email_templates` returns each `uuid`, `subject` and `body_html`; `category` isn't allowed with templates).
   - **Optional:** `reply_to`, `headers`, `attachments` (`{"content": <Base64>, "filename"}`), `category`, `custom_variables` (shown in Email Logs; to find a message later, store the returned `message_ids`).
5. **Batch, up to 500 messages:** `POST .../api/batch` on the same host. `base` holds the shared fields; each `requests` item is one message with its own recipients and variables: `{"base": {"from": {"email": "hello@example.com"}, "template_uuid": "<uuid>"}, "requests": [{"to": [{"email": "a@example.org"}], "template_variables": {"name": "Ana"}}]}`.
6. **Bulk:** send only to recipients who opted in, never to purchased, scraped or unconfirmed lists. Put `<a href="__unsubscribe_url__">Unsubscribe</a>` in the HTML. Details: Bulk page (products table at the end).

### Check it worked

- `/api/send` returns `200` with `{"success": true, "message_ids": [...]}`.
- `/api/batch` returns `200` even if some messages fail: check `success` and `errors` on each item in `responses`.
- `GET https://mailtrap.io/api/email_logs` lists sent messages.

### If something fails

| Error                               | Fix                                                                                                                                                                                                               |
| ----------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `400 Bad Request`                   | Fix the field named in `errors`                                                                                                                                                                                   |
| `401 Unauthorized`, `403 Forbidden` | Also returned for an unverified domain. In order: send from a domain that passed step 2; check `MAILTRAP_API_TOKEN` is set and sent as `Authorization: Bearer`; the user checks the token has Admin on the domain |
| `429 Too Many Requests`             | Over 150 requests per 10 seconds per token: back off exponentially and use `/api/batch`                                                                                                                           |
| Anything else                       | Troubleshooting (link at the end), or ask the docs                                                                                                                                                                |

### Limits and pricing

Plans, quotas and prices change: check pricing.md for plans and prices, and Sending limits for technical limits (links at the end). Don't answer from memory; if you can't check, say so.

## Other Mailtrap products and pages

| If the user wants to…                                             | Use                                                                           |
| ----------------------------------------------------------------- | ----------------------------------------------------------------------------- |
| Send promotional email from code, in detail                       | [bulk-email-service.md](https://mailtrap.io/bulk-email-service.md)            |
| Configure Laravel, Nodemailer, WordPress or another SMTP stack    | SMTP: [smtp-service.md](https://mailtrap.io/smtp-service.md)                  |
| Build campaigns and manage contacts in Mailtrap                   | Email Marketing: [email-marketing.md](https://mailtrap.io/email-marketing.md) |
| Test emails in development, staging or CI without delivering them | Email Sandbox: [email-sandbox.md](https://mailtrap.io/email-sandbox.md)       |
| Check current plans and prices                                    | [pricing.md](https://mailtrap.io/pricing.md)                                  |

## Documentation

- [API integration](https://docs.mailtrap.io/email-api-smtp/setup/api-integration.md) · [Send email API](https://docs.mailtrap.io/developers/email-sending/transactional/send-transactional-email.md) · [Batch send API](https://docs.mailtrap.io/developers/email-sending/transactional/batch-send-emails.md) · [Domains API](https://docs.mailtrap.io/developers/email-sending/domains/list-domains.md) · [Email logs API](https://docs.mailtrap.io/developers/email-sending/email-logs/list-email-logs.md)
- [API tokens](https://docs.mailtrap.io/email-api-smtp/setup/api-tokens.md) · [Domain setup](https://docs.mailtrap.io/email-api-smtp/setup/sending-domain.md) · [Sending limits](https://docs.mailtrap.io/email-api-smtp/setup/sending-limits.md) · [Troubleshooting](https://docs.mailtrap.io/email-api-smtp/help/troubleshooting.md)
- **If sources disagree:** the API reference wins for endpoints and fields, the SDK README for SDK methods, pricing.md for prices and quotas, and this page for which product and steps to use.
- **If the task isn't covered here,** ask the docs before guessing: `GET https://docs.mailtrap.io/index.md?ask=<question>&goal=<user goal>` returns an answer with sources. Keep the question and goal generic: no tokens, email addresses or other user data.
