API guide
Mailtrap email API guide: from first send to production
Follow one transactional email from a Node.js request to delivery-event handling, with sender setup, safe retries, signed webhooks, pricing, and retention.
Contents
Sponsored: Mailtrap sponsored this guide. APIScout retained editorial control.
Choose an email provider around what happens after your application requests a send. A password reset needs a permitted sender, a traceable message ID, and a way to distinguish a temporary failure from a message that should not be sent again. Mailtrap brings production sending, development testing, and delivery diagnostics into its product range. Choose the pieces your application needs, and account for the sending and recovery logic you still have to build.
This guide explains that division, then follows one transactional message from a Node.js request to delivery-event handling. It is intended for developers evaluating Mailtrap or preparing an initial integration, rather than teams looking for a marketing-campaign tutorial.
Quick take
- Best fit: applications sending receipts, account notifications, and password resets that also need a separate environment for email testing.
- API style: HTTPS with JSON and token authentication; SMTP is an alternative for applications already using a mail transport.
- Evaluation path: inspect messages in Email Sandbox, then validate production sending with a permitted sender and a controlled recipient.
- Main constraints: custom-domain verification and compliance checks, plan quotas, limited log retention, and application-owned retry and event processing.
How Mailtrap's email products fit together
Email API/SMTP sends messages to real recipients. Within it, the Transactional Stream serves user-triggered application mail. Mailtrap requires the Bulk Stream for all marketing and promotional emails. Choose the stream before copying credentials or code. This guide uses the transactional HTTP endpoint, not a bulk campaign or an SMTP configuration.
Email Sandbox captures outbound test messages for inspection during development and QA. It is a separate product, not a production mailbox-delivery result. Keep the sandbox configuration separate from production so that a staging password reset cannot accidentally reach a customer. Mailtrap's plan documentation also separates Email Marketing, which provides campaign and contact-list workflows, from API/SMTP and Sandbox billing.
Inbound Email works in the other direction: Mailtrap receives messages and exposes parsed content to your application. It is included in Email API/SMTP plans, with sending and receiving sharing the email allowance. Hosted templates manage message content; MCP and agent skills support assistant-driven workflows. None is a prerequisite for making a plain transactional API request.
Before you send
Start with a Mailtrap account, the Transactional Stream, an API token authorized for your sending domain, a permitted From address, and a recipient you control. API authentication and sender authorization solve different problems: a valid token does not make an arbitrary From domain usable.
Mailtrap's built-in demo domain is restricted to the email address used to register the account. It is useful for an initial connection check, not for customer traffic. To send from your own domain, follow the domain setup guide. Add the domain, copy its supplied DNS records, provide sender information, and wait for verification and the compliance check.
The setup identifies domain-verification, DKIM, tracking, and DMARC records. Use the exact types, names, and values shown for your domain instead of copying generic DNS values from a tutorial. Allow for additional review rather than promising a launch time based only on DNS propagation.
Store the token in your server environment or secret manager. Do not put it in a browser bundle, a committed configuration file, or an unrestricted log. Keep development and production configuration explicit, and restrict who can change sender credentials.
Send a transactional email with Node.js
Use a currently supported Node.js LTS release with global fetch and AbortSignal.timeout. Node.js 22 and 24 are listed as LTS in the release table checked on Sep 29, 2026; install a maintained patch release. The global API reference documents both features. An old release having these APIs does not mean it still receives support.
Code sample MT-SEND-01 uses raw HTTP, so it does not require the Mailtrap SDK. Save it as send.mjs, supply MAILTRAP_API_TOKEN, MAILTRAP_FROM, and MAILTRAP_TO through your server environment, and run node send.mjs only when you intend to send a real message. The demo-domain recipient restriction still applies.
const token = process.env.MAILTRAP_API_TOKEN;
const from = process.env.MAILTRAP_FROM;
const to = process.env.MAILTRAP_TO;
if (!token || !from || !to) {
throw new Error("Set the token, sender, and recipient first");
}
async function sendReceipt() {
const response = await fetch("https://send.api.mailtrap.io/api/send", {
method: "POST",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
signal: AbortSignal.timeout(10000),
body: JSON.stringify({
from: { email: from, name: "Example Store" },
to: [{ email: to }],
subject: "Your example order is confirmed",
text: "This is a sample order confirmation. No purchase was made.",
category: "Order confirmation",
}),
});
const result = await response.json().catch(() => null);
if (!response.ok) {
throw new Error(`Send failed: HTTP ${response.status}`);
}
if (result?.success !== true ||
!Array.isArray(result.message_ids) ||
result.message_ids.length === 0 ||
!result.message_ids.every(id => typeof id === "string" && id)) {
throw new Error("Unexpected response; reconcile before retrying");
}
console.log("Accepted message IDs:", result.message_ids);
}
sendReceipt().catch((error) => {
console.error(error.message);
process.exitCode = 1;
});
The transactional API reference defines the endpoint, bearer authentication, request fields, and response shape. This documentation-based sample makes one attempt, uses a ten-second timeout, checks HTTP status and the response body, and deliberately does not retry. It does not implement a queue, persistent storage, or a webhook receiver.
For a real application, put the send behind a notification job rather than letting a user's repeated page submission create repeated mail. Save the job before sending, and persist the returned message IDs with its outcome. A console line is useful while learning the API, but it is not a durable record for support or recovery.
Treat acceptance and delivery as separate states
The send response contains success and a message_ids array. A successful response tells your application that the send request succeeded; it is not evidence that the message reached the inbox. Keep an accepted state distinct from subsequent delivery or failure events.
Mailtrap defines Delivered as acceptance by the recipient's mailbox provider. Its status documentation explicitly notes that this can include a spam folder. Do not turn a Delivered status into an inbox-placement claim or a promise that the recipient read the message.
Use Email Logs and event history when investigating a specific notification. Preserve the difference between a delivery event and the latest status: later activity can change that status without erasing the earlier event. Your own record should retain enough history to explain what happened, not just overwrite everything with the last label received.
Handle failures without duplicates
Classify a failure before deciding whether to retry. Mailtrap's sending API documents an errors array for failed requests. Inspect diagnostic details in a protected workflow; avoid copying response bodies into public API errors or general-purpose logs.
| Result | Next action |
|---|---|
| HTTP 400 | Correct the request using the returned validation details. |
| HTTP 401 | Check the token and authentication configuration. |
| HTTP 403 | Check domain verification and permissions. |
| HTTP 429 | Back off and schedule a bounded retry; inspect applicable limits. |
| HTTP 5xx | Investigate and retry cautiously; do not assume no message was accepted. |
| Timeout, broken connection, or unexpected success body | Record an uncertain outcome and reconcile before resending. |
Mailtrap recommends exponential backoff for rate-limit responses. Put a ceiling on retry attempts and alert when a job remains unresolved. Request throttling and a daily or monthly email allowance are separate constraints: spacing requests out does not create more plan quota.
The timeout case deserves particular care. Aborting the local request does not recall an email that the provider may already have accepted. Use an application-level notification key to prevent duplicate jobs, and reconcile uncertain attempts against available logs and events. That key alone does not make a second provider request safe. This example does not claim provider-side idempotency or exactly-once delivery.
Track delivery with signed webhooks
Configure an Email Sending webhook for the Transactional Stream and the relevant domain. Select the events your application will handle, and choose a payload format deliberately. In JSON mode, Mailtrap sends an object containing an events array. JSON Lines is a different format; do not feed it into the same whole-body JSON parser.
Follow Mailtrap's signature-verification documentation: read the Mailtrap-Signature header, compute HMAC-SHA256 over the raw request body using that webhook's signing secret, and compare the hexadecimal signature with a constant-time comparison. Preserve the body before JSON parsing. Reject missing, malformed, or mismatched signatures, including incorrect lengths, before processing any event.
Once verified, validate the payload and durably save or enqueue its events before returning HTTP 200. Process them asynchronously. Mailtrap documents 40 retries at five-minute intervals for unsuccessful deliveries, with a 30-second response timeout. If all retries fail, it pauses the webhook and emails a notification; you must check its settings and resume it manually. Enforce deduplication using event_id and correlate message_id with the original notification job. A duplicate callback must not trigger another send.
The documented event spellings matter. Handle delivery, bounce, soft bounce, and reject separately; the space in soft bounce is intentional. A soft bounce is temporary and can lead to provider delivery retries, while a bounce is permanent. Spam complaints use spam, not spam complaint, in the payload. Other documented values are open, click, unsubscribe, and suspension.
Use complaint and suppression-related events to stop inappropriate resend loops. Keep event processing tolerant of repeat or late notifications rather than assuming arrival order is the full history. Signature validation establishes authenticity and integrity; it does not replace event deduplication or your application's authorization rules.
Plan around pricing and retention
The following Email API/SMTP figures were checked against Mailtrap's public pricing and plan documentation on Sep 29, 2026. These are published monthly options, not a negotiated quote or a guarantee of future pricing.
| Plan | Monthly price and allowance | Limits relevant to evaluation |
|---|---|---|
| Free | $0; 4,000 emails/month | 150/day; one user; one domain; three-day email logs |
| Basic entry option | $15; 10,000 emails/month | Three users; five domains; five-day email logs |
Sending and receiving share the allowance. Email Sandbox and Email Marketing have separate plans. Basic has other volume options, so this is an entry-point comparison rather than the complete price list.
Size the plan for busy days as well as average months. Also decide how long support needs to investigate a notification: a short provider log window makes application-side history important. Recheck current allowances, retention, and overage terms before purchase or launch.
Where supporting capabilities fit
Hosted templates are useful when message content changes independently of application code. Mailtrap supports HTML and drag-and-drop editing, Handlebars variables, and API references by template UUID. Treat template edits as production changes: review the content and variables before letting a receipt or password-reset message depend on them.
Inbound Email supports Mailtrap-hosted receiving addresses and custom-domain catch-all inboxes, with parsed messages available through the API and notifications through new-message webhooks. For a custom domain, enable Inbound domain receiving in its Domain Verification settings, add the supplied MX record, and create an inbox using that domain's ID. Sending-domain verification alone does not complete this setup. The inbound overview still labels the UI as coming soon; custom receiving domains are already documented as supported.
Mailtrap's MCP server documents tools for sending, sandbox testing, template management, and inbound email. Inbound tools include list-inbound-messages, get-inbound-message, and reply-to-inbound-message; the reply tool sends real email. Official agent skills supply coding-assistant guidance for Mailtrap workflows. These tools are optional for this integration. Restrict assistant permissions and require a deliberate decision before a tool sends real mail.
Production checklist
Before routing customer notifications through the integration:
- Verify the sender domain and compliance status, token permissions, stream, and production environment configuration.
- Validate message content and recipient selection; keep staging destinations separate from customer addresses.
- Persist notification jobs and message IDs, and define how uncertain attempts are investigated.
- Exercise validation, authentication, throttling, server-error, and timeout handling without blind retry loops.
- Verify webhook signatures, payload parsing, durable acknowledgment, and duplicate-event handling.
- Monitor delivery failures and complaints, and define who handles alerts and suppression questions.
- Confirm peak-day quotas and retention against support needs; document credential rotation and access ownership.
What APIScout tested
On September 18, 2026, one built-in demo-domain self-send reached the registered mailbox and showed Delivered in Mailtrap. This was not a custom-domain, webhook, scale, latency, uptime, or deliverability benchmark. The Node.js sample is documentation-based and was not executed against Mailtrap; inbound email, templates, MCP, and agent skills were not exercised.
Verdict
Mailtrap is worth evaluating when a team wants transactional sending, a separate testing product, and documented delivery diagnostics within the same product range. Its practical strengths are the straightforward HTTP interface, message-level correlation, and explicit event model. Those help build an integration that can explain failures rather than merely issue send requests.
The constraints are consequential: domain approval is part of setup, Free has a daily ceiling, provider logs have limited retention, and safe retries remain application work. Teams needing long investigation windows should resolve retention requirements before committing. For custom inbound domains, confirm that the documented catch-all behavior fits the application's routing needs. The documentation supports an evaluation, not a comparative reliability or inbox-placement ranking.
If that fit matches your application, evaluate Mailtrap's Email API with a controlled workflow before moving customer traffic.