Start with cleanup and validation.
Email verification APIEmail verification API
and mail workflows.
Integrate email validation, safe address cleanup and address analysis with documented JSON results. Explore the shared contract for inbound messages, sending and mailbox migration.
https://api.maail.co/v1Implementation blueprint, not a claim that every endpoint is live.The existing email handler informs this design. New payloads, routes, verification, jobs and events must be implemented against this contract before use. All examples are artificial.
Verify a receiving domain and handle signed events.
Inbound email APICompare extraction, security and automation scope.
Browse the productsExplicit requests. Predictable resources.
The three product workflows share authentication, error handling and asynchronous jobs. Stateless operations use POST with JSON so addresses and message content do not enter query URLs. Persistent resources use plural nouns; scoped actions use an explicit verb suffix.
POST https://api.maail.co/v1/email/clean Authorization: Bearer YOUR_API_KEY Content-Type: application/json Accept: application/json X-Request-ID: req_client_demo_1042
| Concern | Contract |
|---|---|
| Authorization | Tenant-scoped Bearer API keys. Never use query-string keys. Every referenced domain, route, message, connection and job must belong to the authenticated tenant. |
| Scopes | email:read for stateless address checks; inbound:read/write, messages:read/write, webhooks:read/write, diagnostics:read, migrations:read/write. Missing scope is 403; foreign or absent resource IDs are 404. |
| JSON and names | UTF-8, camelCase fields, opaque prefixed IDs, RFC 3339 UTC timestamps. Null means unknown or unavailable, not false. Unsupported request fields are rejected with 422. |
| Success envelope | {"data": …, "meta": {"requestId": "req_…", "apiVersion": "v1"}}. Collections additionally include page: {nextCursor: null|string, hasMore: boolean}. No success envelope for 204. |
| Status codes | 200 for synchronous results and reads; 201 + Location for created resources; 202 + Location for accepted jobs or sending; 204 for deletion/revocation. Acceptance is not completion or delivery. |
| Idempotency | Require Idempotency-Key on all state-changing POST/PATCH/DELETE requests. Same tenant + method + canonical path + key and same body replay the original response for 24 hours, including the same job ID. Changed body returns 409 idempotency_conflict; an in-flight duplicate returns 409 request_in_progress with Retry-After. Stateless checks do not require it. |
| Pagination | Collection GETs accept limit 1–100 (default 25) and opaque cursor. Order by createdAt descending, then ID descending; cursors bind tenant, filters and ordering. Invalid/expired cursors return 422; no totals implied. |
| Updates | PATCH reads use resource ETag. Require If-Match for PATCH/DELETE of mutable resources: absent 428, stale 412. Failed preconditions do not consume the idempotency key. Immutable jobs use action endpoints instead. |
| Versioning | Additive response fields are allowed; clients ignore unknown fields. Enum expansions require documented handling for unknown values. Breaking field, meaning or lifecycle changes require a new major version, not a silent alias. |
Defaults and limits below are proposed implementation requirements, not measured service performance or a published SLA. JSON operations accept up to 1 MiB, unless a narrower limit is stated; SMTP messages use separate 10 MiB limits. Never put secrets, raw mail, or personal information into metadata or request IDs.
An unavailable check is not a negative verdict.
{
"error": {
"code": "invalid_request",
"message": "Correct the highlighted fields.",
"details": [{"field": "domain", "code": "invalid_domain", "message": "Use a domain, not a URL."}],
"retryable": false
},
"meta": {"requestId": "req_demo_1042", "apiVersion": "v1"}
}
| HTTP | Code / meaning | Next step |
|---|---|---|
| 400 | malformed_json | Fix invalid JSON. Missing or wrongly typed fields are 422. |
| 401 / 403 | unauthenticated / insufficient_scope | Check credentials or granted scope; do not retry unchanged. |
| 404 / 405 | not_found / method_not_allowed | Check the resource or verb. 405 includes Allow. |
| 410 | results_expired | Known retained content/results expired or were deleted. Do not retry downloads or replays unchanged. |
| 409 | domain_conflict, invalid_state, resource_in_use, idempotency_conflict, request_in_progress | Resolve ownership/state or honor Retry-After for the same pending operation. |
| 412 / 428 | precondition_failed / precondition_required | Read the resource again and send its current ETag. |
| 413 / 415 / 422 | payload_too_large / unsupported_media_type / invalid_request | Respect size, media type and field constraints. |
| 429 | rate_limited | Honor Retry-After. Quotas are tenant/scope-specific; RateLimit-Limit, RateLimit-Remaining and RateLimit-Reset describe the active window. |
| 502 / 503 / 504 | dependency_failure / service_unavailable / deadline_exceeded | Bound retries with exponential backoff and jitter; keep the same idempotency key for writes. |
A malformed address is a successful validation result with status=invalid, not HTTP 422. A missing email field is 422. Completed DNS/SMTP checks can return partial evidence with status=unknown and explicit reason codes; a whole operation that cannot execute is an HTTP dependency error. Do not classify a resolver outage as “no MX”.
Email address cleanup · POST /v1/email/clean
Prepare a user-entered address without DNS, SMTP or semantic enrichment. Preserve the local part’s case, plus tags and dots; lowercase and IDNA-normalize the domain. Trim surrounding whitespace. Do not silently rewrite a likely misspelled provider.
Process: user input → safe cleanup → show any suggested correction → confirm mailbox control separately. Analyze already includes validation; calling every stage is optional and repeats work.
{
"email": " Demo.User+news@MAIL.EXAMPLE ",
"options": {"decodeObfuscation": false}
}
{
"data": {
"email": " Demo.User+news@MAIL.EXAMPLE ",
"cleanedEmail": "Demo.User+news@mail.example",
"status": "cleaned",
"changes": ["trimmed", "domain_lowercased"],
"suggestions": [],
"reasonCodes": []
},
"meta": {"requestId": "req_clean_demo", "apiVersion": "v1"}
}
| Field | Type / rules |
|---|---|
| Required string, 1–1,024 UTF-8 bytes of input; one address only, not a comma-separated list or display-name mailbox. | |
| options.decodeObfuscation | Boolean, default false. If true, decode unambiguous “(at)” / “[at]” and “(dot)” / “[dot]” forms; every transformation appears in changes. Reject ambiguous input rather than guess. |
| cleanedEmail | String or null. Null when the input cannot produce one valid address. Provider typo candidates are suggestions, not automatic changes. |
| status / changes | unchanged | cleaned | invalid; changes is a string array, e.g. trimmed, domain_lowercased, domain_idna, obfuscation_decoded. |
| suggestions / reasonCodes | Arrays. Suggestion objects contain email and reasonCode. Invalid input includes invalid_syntax or ambiguous_input. No claim of deliverability. |
Email validation · POST /v1/email/validate
Run safe cleanup, syntax/domain checks, DNS mail-route discovery and disposable/provider signals. Validate stops at DNS; use analyze for the SMTP recipient check and catch-all detection. Public DNS records alone cannot prove mailbox existence.
For a signup form, call this endpoint from your backend, keep the address out of query URLs and preserve unknown results for retry or confirmation. See the email verification guide for the full check sequence, or choose a newsletter, gated-content or licensing workflow.
{"email": "demo-user-1042@research.example"}
{
"data": {
"email": "demo-user-1042@research.example",
"cleanedEmail": "demo-user-1042@research.example",
"status": "valid",
"reasonCodes": ["valid_syntax", "has_mx"],
"syntax": {"status": "pass", "requiresSmtpUtf8": false},
"dns": {"status": "pass", "route": "mx", "checkedAt": "2026-10-31T12:00:00Z"},
"mailbox": {"status": "not_checked"},
"address": {"isDisposable": false},
"warnings": []
},
"meta": {"requestId": "req_validate_demo", "apiVersion": "v1"}
}
Input is the same required email string as clean. Validate does not decode obfuscation; explicitly clean it first. Disposable detection is context, not technical non-deliverability. A suggested typo does not authorize rewriting the user’s address.
| Status | Meaning |
|---|---|
| invalid | Unusable address syntax or domain syntax. |
| valid | Syntax and DNS route are usable. Mailbox acceptance is not established; catch-all results also remain valid. |
| deliverable | Analyze observed positive recipient acceptance on a non-catch-all server. Time-bounded evidence, not inbox placement or identity proof. |
| undeliverable | Definitive no-mail route (including Null MX), or a definitive recipient rejection from analyze. Absence of MX alone needs implicit A/AAAA fallback evaluation. |
| unknown | Required evidence is unavailable, temporary or unsupported. SMTP timeouts, graylisting and unsupported SMTPUTF8 are never invalid syntax or a permanent mailbox failure. |
Check states are pass | fail | unknown | not_checked. DNS route is mx | implicit | null_mx | none | unknown. Booleans can be null when enrichment has no evidence. Warnings are objects with code and message. Common reason codes include valid_syntax, invalid_syntax, has_mx, implicit_mx, null_mx, no_mail_route, dns_error, disposable and typo_domain.
Email analysis · POST /v1/email/analyze
Return validation plus address, likely-name, provider and server context. Every analysis includes a bounded SMTP recipient check with catch-all detection: Maail asks the receiving server whether it accepts the recipient, without sending DATA or an email.
{
"email": "Demo.User@research.example"
}
{
"data": {
"email": "Demo.User@research.example",
"cleanedEmail": "Demo.User@research.example",
"status": "deliverable",
"reasonCodes": ["valid_syntax", "has_mx", "recipient_accepted"],
"syntax": {"status": "pass", "requiresSmtpUtf8": false},
"dns": {"status": "pass", "route": "mx", "checkedAt": "2026-10-31T12:00:00Z"},
"mailbox": {"status": "accepted", "checkedAt": "2026-10-31T12:00:01Z", "smtpCode": 250, "reasonCodes": ["recipient_accepted"]},
"address": {"isDisposable": false, "isRole": false, "isGraylisted": false},
"name": {"value": null, "firstname": null, "lastname": null, "confidence": null},
"host": {"value": "research.example", "provider": null, "catchAll": false, "isKnown": false, "reputation": null},
"server": {"exists": true, "records": [{"exchange": "mx1.research.example", "priority": 10}]},
"warnings": []
},
"meta": {"requestId": "req_analyze_demo", "apiVersion": "v1"}
}
The SMTP check and catch-all detection always run; there is no option to switch them off. mailbox.status is accepted | rejected | catch_all | temporary_failure | unknown and includes checkedAt, nullable smtpCode and reasonCodes. A catch-all server accepts every recipient, so an accepted recipient there is reported as catch_all, not as deliverable. DNS and SMTP use server-owned deadlines and destination restrictions; clients cannot supply resolver URLs, probe hosts or ports. Refuse private/internal destinations and bound per-domain probing.
Names and roles are inferred, never verified identity. Name confidence is null or a documented 0–1 model score, not a probability of mailbox ownership. Provider and reputation are nullable contextual values, not a fraud verdict. Reputation enum is high, good, medium, low, bad or null. server.exists means a DNS mail route exists, not that SMTP succeeded; records are always an array. Failure to infer a field must not produce a fabricated default.
The address, name, host and server groups separate address context, inferred names, provider signals and server evidence. Inferred values do not establish identity or guarantee mailbox availability.
There is no isStudent or isAcademic field in this contract. For education licences, apply a maintained institution mapping and your own eligibility policy. For newsletter personalization, keep name hints optional and editable; do not infer age, gender or nationality from an address.
Address imports without request timeouts.
Create one asynchronous batch for up to 1,000 addresses. Results remain input-ordered, keep duplicates as separate client items, and never deduplicate away your client reference.
| Method / path | Input and response |
|---|---|
| POST /v1/email/batches | Required operation clean, validate or analyze; required items array (1–1,000) of {clientRef, email}; clientRef is unique within the batch, 1–64 characters. Analyze items always include the SMTP and catch-all check. Returns 202 Job. Requires idempotency and retentionHours 1–24, default 1. |
| GET /v1/email/batches/{id}/results | Cursor pagination. 409 results_not_ready until job completes. 200 collection of {clientRef, data, error}; exactly one of data or error is non-null. An invalid address is data.status=invalid, not an item error. 410 results_expired after deletion/expiry. |
{
"operation": "validate",
"items": [{"clientRef": "signup-1042", "email": "demo-user@research.example"}],
"retentionHours": 1
}
Use the shared Job API to observe or cancel the batch. Stateless single checks are not archived; batches necessarily retain transient input/results during processing. Their retentionHours window starts when the batch reaches a terminal state; input is discarded once processing no longer needs it. expiresAt is returned by the Job.
Tell Maail about a new inbound domain.
Process: register → publish ownership TXT → request verification → publish returned MX → check readiness → create explicit routes → receive signed events. Registration alone never activates receiving. A subdomain has its own registration; a parent claim does not silently capture all subdomains.
Prefer a dedicated receiving subdomain to avoid replacing your existing mailbox provider’s MX. The service returns environment-specific DNS values; never guess or hardcode a production MX target from this example.
POST /v1/inbound/domains Idempotency-Key: onboarding-inbound-demo-1042
{"domain": "inbound.mail.example"}
{
"data": {
"id": "dom_demo_1042",
"domain": "inbound.mail.example",
"status": "pending_verification",
"ownership": {"status": "pending", "verifiedAt": null, "challengeExpiresAt": "2026-11-07T12:00:00Z"},
"dnsRecords": [
{"purpose": "ownership", "type": "TXT", "name": "_maail-verification.inbound.mail.example", "value": "maail-verification=DEMO_NOT_A_REAL_TOKEN"},
{"purpose": "receiving", "type": "MX", "name": "inbound.mail.example", "priority": 10, "value": "mx.inbound.example"}
],
"createdAt": "2026-10-31T12:00:00Z",
"updatedAt": "2026-10-31T12:00:00Z"
},
"meta": {"requestId": "req_domain_demo", "apiVersion": "v1"}
}
| Method / path | Contract |
|---|---|
| POST /v1/inbound/domains | Required domain: public FQDN, no URL/IP/wildcard, IDNA-normalized, at most 253 ASCII characters. 201 Domain + Location. Same-tenant duplicate returns 409 domain_conflict with owned resourceId; cross-tenant conflict must not disclose the other tenant. Ownership claims need expiry/reclaim safeguards. |
| GET /v1/inbound/domains | 200 paginated Domain collection. Optional status filter using the documented lifecycle values. |
| GET /v1/inbound/domains/{id} | 200 Domain with current TXT/MX evidence and ETag. Reading does not perform a live DNS refresh. |
| POST /v1/inbound/domains/{id}/verify | Empty JSON body. 202 Job; bounded public DNS verification. Publishes no DNS. Missing evidence completes the job with Domain still pending and explicit findings; a DNS outage is a failed check, not proof of ownership loss. |
| PATCH /v1/inbound/domains/{id} | Only status=suspended or active. Resume requires current ownership and MX evidence; domain name is immutable. 200 Domain. Suspending stops acceptance of new SMTP recipients; already accepted work still drains. Restoring an old status must not bypass verification. |
| DELETE /v1/inbound/domains/{id} | 204; requires routes disabled/deleted and no pending accepted deliveries, otherwise 409 resource_in_use. Releases the claim after the defined cooldown; removal never changes customer DNS. No deletion of unrelated message archives. |
Lifecycle: pending_verification → pending_dns → active; active can become suspended when paused or when confirmed ownership/configuration loss is detected. Only active domains accept routed recipients. Pending challenges expire after seven days; return ownership.status=expired and renew the token through verify. VerifiedAt and evidence timestamps describe observation, not permanent domain ownership.
Verify must recheck the exact domain’s ownership TXT and expected MX, including dangerous competing MX configurations. Provider-specific correct records and findings are returned as {code, severity, query, message}. Observe DNS TTLs; a timeout cannot activate the domain. Ongoing rechecks and suspension events are implementation requirements.
Routes are explicit. Receipt is observable.
Create routes only on an active, verified domain. An exact localPart matches one recipient; catch-all is opt-in with localPart="*" and requires separate approval. Unknown recipients are rejected at SMTP time, not silently stored.
{
"domainId": "dom_demo_1042",
"localPart": "invoices",
"webhookEndpointId": "wh_demo_1042",
"processing": {"classify": false, "dmarcAggregate": false},
"retentionHours": 24
}
{
"data": {
"id": "route_demo_1042",
"domainId": "dom_demo_1042",
"localPart": "invoices",
"address": "invoices@inbound.mail.example",
"webhookEndpointId": "wh_demo_1042",
"processing": {"classify": false, "dmarcAggregate": false},
"retentionHours": 24,
"status": "active",
"createdAt": "2026-10-31T12:00:00Z",
"updatedAt": "2026-10-31T12:00:00Z"
},
"meta": {"requestId": "req_route_demo", "apiVersion": "v1"}
}
| Method / path | Contract |
|---|---|
| POST /v1/inbound/routes | Required domainId, localPart and active verified webhookEndpointId. localPart: 1–64 ASCII bytes, lower-case dot-atom, no consecutive/leading/trailing dots; domain-specific exact matching takes priority over catch-all. Unique per domain. Optional processing booleans default false. retentionHours 1–168, default 24. 201 Route. |
| GET /v1/inbound/routes | 200 paginated Route collection; optional domainId and status=active|disabled filters. |
| GET /v1/inbound/routes/{id} | 200 Route + ETag. Includes immutable address and domainId. |
| PATCH /v1/inbound/routes/{id} | Mutable webhookEndpointId, processing, retentionHours, status=active|disabled. 200 Route. Domain/localPart immutable; changes affect new messages only. Disabling does not drop accepted deliveries. |
| DELETE /v1/inbound/routes/{id} | 204; disabled route with no pending deliveries required. Remove/archive accepted messages separately. |
| GET /v1/inbound/messages | 200 paginated InboundMessage collection with metadata only; filters routeId, status=accepted|processing|processed|failed. Bodies are not included in collection responses. |
| GET /v1/inbound/messages/{id} | 200 InboundMessage: id, routeId, status, receivedAt, expiresAt, envelope {from,to}, headers [{name,value}], subject, text/html (nullable strings), attachments [{id,filename,contentType,sizeBytes}], processing {status,classification,dmarcReport,error}. Preserve repeated headers in order. Authentication headers remain untrusted claims. Binary attachments are never inlined in JSON. |
| GET /v1/inbound/messages/{id}/attachments/{attachmentId} | 200 binary stream with Content-Type and safe Content-Disposition: attachment; authenticated access, no arbitrary remote fetch. 404 cross-tenant, 410 expired/deleted. MIME/filename is untrusted. |
| DELETE /v1/inbound/messages/{id} | 204, idempotent even if already deleted. Stop future content downloads/replays; active deliveries must be canceled or finished first (409 otherwise). Deletion window and backup purge are explicit in retention terms. |
Receipt lifecycle: accepted → processing → processed or failed. Return SMTP acceptance only after durable storage and enqueueing succeed; otherwise return a temporary SMTP error. Classifier/report parser failures retain available message evidence and emit inbound.message.failed rather than a success-shaped empty result. One resource represents one route delivery; repeated SMTP submissions are not deduplicated by the untrusted Message-ID header alone. Disabling a route never discards a message already accepted.
Route a separate report address with processing.dmarcAggregate=true for aggregate XML. Decompression needs strict compressed/uncompressed size, ratio, entry and parser limits; DTD/entities and external fetches remain forbidden. Unsupported reports produce structured processing errors; they never masquerade as empty successful results. ARF/failure-report parsing and arbitrary invoice field extraction are not promised by this v1 contract.
At-least-once delivery, with authentication.
Create and challenge the HTTPS endpoint before attaching it to a route. Only public destinations are allowed; deny loopback, private/link-local ranges, redirects and DNS rebinding at validation and each delivery. TLS validation is mandatory.
{
"url": "https://hooks.product.example/mail",
"events": ["inbound.message.processed", "inbound.message.failed"]
}
| Method / path | Contract |
|---|---|
| POST /v1/webhook-endpoints | Required url (HTTPS, max 2,048 characters), events (non-empty event-name array). 201 WebhookEndpoint: id,url,events,status=pending_verification,createdAt, signingSecret (returned once). No query credentials. Never return the secret on later reads. |
| GET /v1/webhook-endpoints; GET /v1/webhook-endpoints/{id} | 200 collection or WebhookEndpoint + ETag. status=pending_verification|active|disabled. No secret, request body or customer content in list output. |
| POST /v1/webhook-endpoints/{id}/verify | 202 Job. Send signed webhook.endpoint.challenge with a random challenge field; receiver returns 200 JSON {challenge: same_value}. Only successful matching verification marks active. |
| PATCH /v1/webhook-endpoints/{id} | events and status=disabled|active only. Changing URL requires a new endpoint and new challenge. Reactivation requires verified URL. 200 resource. |
| POST /v1/webhook-endpoints/{id}/rotate-secret | 201 {signingSecret,previousSecretExpiresAt}. Previous key valid for one hour; communicate cutover securely. Require idempotency; encrypted replay cache must protect one-time secrets. |
| DELETE /v1/webhook-endpoints/{id} | 204 only after route references and pending deliveries are cleared; otherwise 409 resource_in_use. |
| GET /v1/webhook-deliveries | 200 metadata collection; filters endpointId,eventId,status=pending|delivered|failed. Fields id,eventId,endpointId,attempts,lastHttpStatus,nextAttemptAt,createdAt. Never include signing secrets. |
| POST /v1/webhook-deliveries/{id}/replay | 202 Job, empty body. Creates a delivery attempt for the same eventId using the currently valid endpoint/secret. 410 if retained event/message content expired; 409 if already pending or endpoint disabled. |
Maail-Event-ID: evt_demo_1042 Maail-Signature: t=1793448000,v1=HEX_HMAC_SHA256
{
"id": "evt_demo_1042",
"type": "inbound.message.processed",
"createdAt": "2026-10-31T12:00:00Z",
"apiVersion": "v1",
"data": {"messageId": "inmsg_demo_1042", "routeId": "route_demo_1042", "processingStatus": "processed"}
}
Compute lowercase hex HMAC-SHA256 of timestamp + "." + raw_request_body with the endpoint signing secret. Verify against raw bytes, compare in constant time and reject timestamps outside ±5 minutes. A retry gets a fresh signature timestamp but the same event ID. Persist event IDs for deduplication; return 2xx after durable queue acceptance, then process asynchronously. Do not trust a parsed/serialized body for signature verification.
Events: webhook.endpoint.challenge; inbound.domain.activated/suspended; inbound.message.received/processed/failed; message.accepted/delivered/bounced/failed; job.completed/failed. Resource events reference IDs and state rather than embedding entire sensitive bodies. Read the tenant-owned resource for details. Events may arrive out of order; there is no exactly-once or global ordering guarantee.
Delivery timeout is 10 seconds. Retry non-2xx/network failures at 1 minute, 5 minutes, 30 minutes, 2 hours, 8 hours and 24 hours after the initial failure; stop at content expiry if earlier. Mark failed after exhaustion and expose it in delivery metadata. The receiver’s 2xx acknowledges the event, not completion of a business action. Retention must cover the desired retry window; notify customers when earlier expiry cuts it short.
Classify first. Send deliberately.
POST /v1/email/classify is stateless (messages:read). Required from (address string), subject and text strings; optional html. Combined text/html at most 64 KiB. Empty text is allowed only with non-empty html. Returns {label: spam|ham|unknown, confidence: number|null, reasonCodes: string[], modelVersion: string}. Confidence is 0–1, not a verified truth. Unsupported content or insufficient evidence produces unknown with reasons.
{"from": "updates@service.example", "subject": "Artificial account notice", "text": "This is synthetic sample content."}
{
"data": {"label": "ham", "confidence": 0.96, "reasonCodes": ["transactional_pattern"], "modelVersion": "classifier-demo"},
"meta": {"requestId": "req_classify_demo", "apiVersion": "v1"}
}
Sending process: verify a sending domain → choose content or template → submit with idempotency → observe acceptance and delivery events. Inbound MX verification is not authorization to send as a domain.
| Method / path | Contract |
|---|---|
| POST /v1/sending-domains | Required domain with the same normalization as inbound. 201 SendingDomain {id,domain,status,dnsRecords,createdAt,updatedAt}; ownership TXT, provider DKIM and return-path records returned by service. status=pending_verification|active|suspended. |
| GET /v1/sending-domains; GET /v1/sending-domains/{id} | 200 collection/resource + ETag. Only the registered exact domain is authorized; subdomains need explicit registration. |
| POST /v1/sending-domains/{id}/verify | 202 Job. Check ownership and required authentication records before activation; DNS outages remain incomplete findings. No automatic DNS publication. |
| PATCH /v1/sending-domains/{id}; DELETE /v1/sending-domains/{id} | PATCH status=active|suspended; resume requires verified evidence. 200 resource. DELETE 204 after queued/sending messages drain, otherwise 409. |
| POST /v1/templates | Required name (1–100 characters), subject (1–998 bytes), and text or html; optional variables array of required variable names. 201 Template {id,name,subject,text,html,variables,version,createdAt,updatedAt}. No executable code. |
| GET /v1/templates; GET /v1/templates/{id} | 200 collection/resource + ETag. HTML/text total at most 64 KiB. |
| PATCH /v1/templates/{id}; DELETE /v1/templates/{id} | PATCH name,subject,text,html,variables; 200 with incremented immutable version. DELETE 204; accepted messages retain their rendered snapshot, not a live template reference. |
| POST /v1/messages | Required sendingDomainId, from {email,name?}, to array (1–50) of {email,name?}. Either message {subject,text?,html?} OR template {id,variables:object}, never both. Optional replyTo. From domain must match an active authorized domain. 202 OutboundMessage + Location. |
| GET /v1/messages; GET /v1/messages/{id} | 200 collection/resource; filters status and sendingDomainId. OutboundMessage {id,sendingDomainId,status,recipients:[{email,status,smtpCode,reasonCode}],createdAt,updatedAt,templateVersion:null|integer}. status=queued|sending|delivered|partially_delivered|bounced|failed|canceled. delivered means all recipient servers accepted, not inbox placement. |
| POST /v1/messages/{id}/cancel | Empty body; 200 OutboundMessage only while queued, otherwise 409 invalid_state. Cannot retract accepted SMTP delivery. |
{
"sendingDomainId": "senddom_demo_1042",
"from": {"email": "billing@mail.example", "name": "Demo Billing"},
"to": [{"email": "demo-recipient@customer.example"}],
"message": {"subject": "Artificial invoice notice", "text": "Your example invoice is ready."}
}
{
"data": {"id": "msg_demo_1042", "sendingDomainId": "senddom_demo_1042", "status": "queued", "recipients": [{"email": "demo-recipient@customer.example", "status": "pending", "smtpCode": null, "reasonCode": null}], "createdAt": "2026-10-31T12:00:00Z", "updatedAt": "2026-10-31T12:00:00Z", "templateVersion": null},
"meta": {"requestId": "req_send_demo", "apiVersion": "v1"}
}
Recipient states: pending, accepted, temporary_failure, rejected, failed. Temporary failures remain sending with bounded backoff for at most 24 hours; then mark that recipient failed with an explicit expiry reason. all accepted → delivered; mixed accepted and terminal failures → partially_delivered; no accepted and all rejected → bounced; transport/system failures without acceptance → failed. Terminal status means every recipient is terminal.
Templates use literal {{name}} placeholders for declared variable names, with string values only; no expressions, loops or code execution. Missing variables or unknown variable names return 422. Render and snapshot the template version at acceptance, reject CR/LF in headers and escape HTML substitutions. v1 does not accept arbitrary attachment URLs, raw SMTP options, executable templates or server credentials in messages. Attachments and raw RFC 822 sending need a separately specified upload contract, not an undocumented shortcut.
Bring useful public tools into the API.
These are proposed authenticated operations, reusing the framework-level diagnostic logic later. The public tool POST URLs return a different presentation envelope; they are not aliases of this v1 API.
| Method / path | Input / result |
|---|---|
| POST /v1/diagnostics/dns | Required domain (or public IP for ptr), type=health|mx|spf|spf-tree|dmarc|dmarc-inspect|dkim|a|aaaa|txt|cname|ns|soa|ptr|mta-sts|tlsrpt|bimi; selector required for dkim. 200 DiagnosticReport. Fixed resolver; no user-supplied destination URL. Partial query failure remains explicit. |
| POST /v1/diagnostics/headers | Required headers string, at most 64 KiB; body discarded. 200 DiagnosticReport with authentication claims, DKIM selectors and Received evidence. Does not validate DKIM/ARC cryptography or trusted header origin. |
| POST /v1/dmarc/records/generate | Required domain and reportEmail. policy=none|quarantine|reject default none; subdomainPolicy=inherit|none|quarantine|reject default inherit; adkim/aspf=r|s default r. enforcementConfirmed=true required if main or subdomain enforces. 200 {name,type:"TXT",value,warnings}. No publication. Legacy pct deliberately excluded from new API. |
| POST /v1/dmarc/reports/analyze | Required xml string, plain aggregate XML, at most 1 MiB and 1,000 records; no DTD/entities/remote fetch. 200 DiagnosticReport. Aligned SPF OR DKIM weighted by counts; no automatic source threat labels. Missing/malformed evaluations return 422. |
DiagnosticReport preserves the existing library shape: domain,type,selector,status,checkedAt,durationMs,resolver,scope,checks. Each check has type,query,recordType,status,records,findings, optional details and operation-specific dmarc/spfExpansion/metrics. Status is info|warn|fail|error, not the address-validation enum. Findings contain status,title,detail. Records include name,type,ttl,value and optional MX priority/exchange/addresses. Details contain title,columns,rows. UI-only followUps are omitted from API results.
DNS budget: 12 distinct queries / 15 seconds total; DMARC discovery at most eight policy TXT queries and six reporting destinations within that shared budget. MTA-STS/TLS-RPT/BIMI are DNS-only, not HTTPS/certificate/logo verification. Reports are one-report observations, not continuous monitoring or cross-report deduplication. Explore the working public tools.
{"domain": "mail.example", "type": "dmarc-inspect"}
Connections first. Jobs second.
Process: create source and destination connections → check capabilities and ownership → start copy → review counts and warnings → run delta → change provider delivery yourself → repeat delta if needed → revoke connections. A finished copy never changes MX or deletes source mail.
| Method / path | Contract |
|---|---|
| POST /v1/mailbox-connections | Required label (1–100 characters), host (public FQDN), port=993 and security=tls, username; auth is either {type:"password",password} or {type:"oauth2",accessToken}. 201 Connection. Secrets encrypted separately, never returned/logged. OAuth expiry requires explicit credential refresh; no implied automatic refresh. |
| GET /v1/mailbox-connections; GET /v1/mailbox-connections/{id} | 200 collection/resource + ETag. Connection {id,label,host,port,security,username,status,capabilities,lastCheckedAt,createdAt}; status=unchecked|ready|failed|revoked, capabilities string array. |
| POST /v1/mailbox-connections/{id}/check | Empty body; 202 Job, verifies TLS/auth/folder access and write readiness without modifying source messages. Returns check findings in job result; errors do not mark ready. |
| PATCH /v1/mailbox-connections/{id} | label or auth only, 200 Connection. Credential replacement resets unchecked and requires recheck; disallowed while referenced by a running migration. |
| DELETE /v1/mailbox-connections/{id} | 204 revokes and deletes secrets. 409 resource_in_use while jobs use it; cancel/wait first. Keep nonsecret audit identifiers according to retention terms. |
Check tenant authorization to access both mailboxes. Enforce public-host restrictions at every connection, certificate validation and per-provider limits; never accept arbitrary ports, internal IPs or disabled TLS. Resolve and pin safely against DNS rebinding. IPv4/IPv6 behavior and OAuth consent must be implemented explicitly.
{
"label": "Demo source mailbox",
"host": "imap.source.example",
"port": 993,
"security": "tls",
"username": "demo-user@source.example",
"auth": {"type": "password", "password": "DEMO_PLACEHOLDER_NOT_A_SECRET"}
}
{
"sourceConnectionId": "conn_demo_source",
"destinationConnectionId": "conn_demo_destination",
"options": {"preserveFlags": true, "preserveInternalDates": true, "folderMap": {}},
"retentionHours": 168
}
{
"data": {
"id": "mig_demo_1042",
"jobId": "job_demo_copy",
"sourceConnectionId": "conn_demo_source",
"destinationConnectionId": "conn_demo_destination",
"status": "queued",
"progress": {"foldersCopied": 0, "messagesCopied": 0, "bytesCopied": 0, "messagesSkipped": 0, "messagesFailed": 0},
"warnings": [],
"createdAt": "2026-10-31T12:00:00Z",
"updatedAt": "2026-10-31T12:00:00Z"
},
"meta": {"requestId": "req_migration_demo", "apiVersion": "v1"}
}
| Method / path | Contract |
|---|---|
| POST /v1/mailbox-migrations | Required distinct ready sourceConnectionId,destinationConnectionId. options flags/dates default true; folder hierarchy always copied, folderMap optional string-to-string mapping with collision validation. retentionHours 1–720, default 168. 202 Migration; Location identifies migration, jobId identifies the initial shared Job. Reject concurrent jobs writing the same destination with 409. |
| GET /v1/mailbox-migrations; GET /v1/mailbox-migrations/{id} | 200 collection/resource. Filter status=queued|running|completed|failed|canceled. Progress counters are cumulative for the migration, not proof of byte-exact fidelity. No source content/credentials returned. |
| POST /v1/mailbox-migrations/{id}/catch-up | Empty body, 202 Job; allowed after completed main/delta run with valid ready connections and no pending job. Migration returns queued/running while delta operates, then completed. Deduplicate using source UIDVALIDITY/UID plus destination mapping, not Message-ID alone. |
| POST /v1/mailbox-migrations/{id}/retry | Empty body, 202 Job; only failed/canceled migrations with ready connections. Resume checkpoints; UIDVALIDITY changes require explicit re-inventory, never silent skip. Successful prior copies are not blindly recopied. |
| POST /v1/mailbox-migrations/{id}/cancel | 202 Job; requests cancellation of the active run. Stop at a safe checkpoint; partial destination copies remain. 409 when no run is active. Cancellation does not undo copies. |
| DELETE /v1/mailbox-migrations/{id} | 204 removes retained manifests/status after a terminal run, not either mailbox’s messages. 409 while work is pending/running. Connection secrets are revoked separately. |
Migration progress distinguishes copied/skipped/failed counts and warnings with {code,message,folder?}. Destination limitations and unsupported flags/dates are reported. completed means the run ended without failed items; skipped policy-excluded items and nonfatal preservation warnings still require review. Failed items produce failed with recoverable checkpoints. No exact-once copy or full-fidelity guarantee is inferred from a status badge.
One asynchronous lifecycle across workflows.
| Method / path | Contract |
|---|---|
| GET /v1/jobs/{id} | 200 Job {id,kind,status,resourceId,progress,result,error,createdAt,updatedAt,expiresAt}. kind=email_batch|domain_verification|webhook_verification|connection_check|mailbox_copy|mailbox_catch_up|webhook_replay|migration_cancel. Status queued|running|completed|failed|cancel_requested|canceled. |
| POST /v1/jobs/{id}/cancel | Empty body, 202 Job. Only queued/running email_batch and mailbox_copy/catch_up are cancelable. Other kinds return 409 not_cancelable. Repeated cancellation with the same key returns the same response; cancellation may leave completed items. |
{
"data": {
"id": "job_demo_verify",
"kind": "domain_verification",
"status": "completed",
"resourceId": "dom_demo_1042",
"progress": {"completed": 2, "total": 2},
"result": {"domainId": "dom_demo_1042", "status": "pending_dns", "findings": [{"code": "mx_missing", "severity": "warn", "query": "inbound.mail.example", "message": "Expected receiving MX is not visible yet."}]},
"error": null,
"createdAt": "2026-10-31T12:00:00Z",
"updatedAt": "2026-10-31T12:00:03Z",
"expiresAt": "2026-11-07T12:00:03Z"
},
"meta": {"requestId": "req_job_demo", "apiVersion": "v1"}
}
Completed verification means the check ran, not necessarily that the domain/connection is ready. Always inspect result.status/findings. failed jobs have a structured error with code,message,retryable; result can retain partial evidence. Generic progress has completed and nullable total; only show percentages when total is known. Mailbox counters belong to the Migration resource.
Poll with bounded backoff; response Retry-After recommends the next read interval. Webhook events notify terminal jobs but clients must tolerate duplicates or missing notifications. Job metadata expires after seven days by default; batch content expires at retentionHours. Resource manifests/content have their own retention. Expired known results return 410; unknown/foreign IDs return 404.
Privacy is part of the contract.
Address checks are analysed immediately and not stored: neither the address nor the result is kept. To avoid billing an identical repeat request twice, only a one-way hash of the request is kept. Standalone classification and diagnostic payloads are likewise processed without an application archive. Domain/provider DNS requests go to configured resolvers; SMTP probing necessarily contacts mail infrastructure. Inbound bodies, delivery events, encrypted secrets and migration checkpoints are purpose-limited state. Publish processing location, subprocessors, access controls, backup/deletion windows and billing metadata retention before production onboarding. Workflows that hold mail by design (inbound bodies, batches during processing, migrations) state their retention per endpoint.
Return Cache-Control: no-store for authenticated API responses, especially addresses, message bodies and one-time secrets. Disable request-body/Authorization logging; redact credentials from errors and traces. Proposed inbound SMTP acceptance is capped at 10 MiB per message including encoded MIME attachments; sending JSON keeps the 1 MiB request limit and 64 KiB composed text/HTML. None of these are advertised latency or uptime guarantees.
Start with the workflow, not another endpoint.
This draft defines the processes, resources and boundaries for implementation. Access, limits and production availability are confirmed during onboarding.