client.emails
Every method in this namespace: its signature, its parameters, what it returns and an example.
Methods
Send mail now or later, in batches or translated, and follow what happened to it.
emails.send
Send, schedule or translate and send one email
send(body = nil, idempotency_key: nil, api_key: nil, **fields) -> HashSends one message now, or holds it for later with scheduledAt or an undo window with cancellableForSeconds. The body comes from exactly one source: html and or text, a stored template, or an existing draftId. Naming none is a 422, and template alongside html, text or draftId is refused. An immediate send is dispatched inside the request, so the call usually returns a sent, partial or failed message. A held send comes back as queued or scheduled, so read status rather than treating a returned message as delivered mail.
Every call carries an Idempotency-Key. The SDK generates one per call and reuses it on that call's retries, and the API claims it against the key's own unique index before anything is dispatched, so a retried network failure replays the original message instead of sending a second one. Pass idempotency_key: to extend that across processes and restarts, deriving it from what made the send necessary rather than from a clock. A replay returns replayed set to true and the stored message in its current state. The same key with a different body is a 422 idempotency_key_reuse.
Add translate to deliver the message in the recipient's language. The translation runs when the request is accepted, before any record exists, so a scheduled send carries the approved wording and a translation that cannot be produced refuses the whole send: nothing is ever delivered untranslated as a fallback. By default the subject is translated too and your original text is placed below the translation, captioned in the target language. It works with template, translating what the template rendered, and is refused alongside draftId because a draft goes as it was written.
Parameters
fromString or HashRequiredSender as
[email protected],Acme Billing <[email protected]>or a Hash withemailandname. It must be an address the key may send as, otherwise 403from_address_forbidden.toString, Hash or ArrayRequiredOne recipient or an Array of them, each a String or a Hash with
emailandname.to,ccandbcctogether hold at most 50 addresses, and more is a 422too_many_recipients.ccString, Hash or ArrayCopy recipients, counted toward the 50 recipient ceiling.
bccString, Hash or ArrayBlind copy recipients, counted toward the 50 recipient ceiling.
replyToString or HashWritten into the
Reply-Toheader.subjectStringAt most 998 characters. Falls back to the template or draft subject when empty.
htmlStringHTML body, at most 1,000,000 characters.
textStringPlain text body, at most 1,000,000 characters.
templateHashA stored template by id or slug, as a Hash with
idand optionalversion(an Integer),propsandslots(Hashes). Omittingversionresolves whatever is published at that moment, so pin it when somebody else owns the copy.draftIdStringSends an existing draft as written. Cannot be combined with
templateortranslate.threadIdStringFiles the sent message into an existing thread.
headersHashCustom headers, header name to String value, limited to
X-*,List-*,Reply-To,Precedence,Auto-Submitted,Importance,PriorityandFeedback-ID. Anything the server sets itself is a 422reserved_header.attachmentsArray<Hash>At most 20 files. Each entry is either an inline file, with
filename, an optionalcontentTypeandcontentas raw bytes (a binary String such asFile.binreadreturns, an IO or a Pathname, encoded for you) or base64 text, where inline files are capped at 10 MB in total once decoded, or a stored file as a Hash with onlyfileIdnaming a file already uploaded to the workspace, which is how a file larger than the inline cap is sent. A file at an https address is a Hash withurland optionallyfilenameandcontentType, fetched once when the message is accepted. Inline andurlfiles come to at most 25 MB together. Textcontentthat is not base64 raisesArgumentErrorbefore anything is sent.attachmentDeliveryStringHow the files in
attachmentstravel.mimecarries them inside the message, so files that come to more than 25 MB together are refused.linkuploads each file and puts a download link in the body in its place, so the message itself stays small.autolinks when the files together come to more than 25 MB, or to more than 2 MB when thefromdomain has an active files domain, and attaches them otherwise. Left out, the sender's mailbox setting applies, and that defaults toauto.scheduledAtTime, DateTime or StringA
TimeorDateTime, sent as a UTC ISO 8601 instant, an ISO 8601 instant String or a duration such asPT1HorP2D. At least one second and at most 365 days out.followUpAtTime, DateTime or StringAsks to be reminded if nobody replies: a
TimeorDateTime, sent as a UTC ISO 8601 instant, an ISO 8601 instant String or a duration from now such asP3D, later than the time the message goes out and at most 365 days out. If no real reply has arrived by then, the thread returns to the top of the inbox, unread, with a push.follow_ups.listlists the reminders andfollow_ups.cancelcancels one.cancellableForSecondsIntegerAn undo window from 0 to 900 seconds on an immediate send. Refused alongside
scheduledAt, which is already cancellable until it goes.trackingHashA Hash with optional Boolean
opensandclicksthat overrides the tracking setting for this send. A field left out takes the setting of the address it is sent from: its own, else its domain catch-all's when the catch-all caught that address, else off.signatureBooleanAn
htmlbody goes out exactly as written, so it carries a signature only when this istrue, while atext-only body carries one unless this isfalse. When it is added it is the default signature of the address it is sent from: the one it keeps for replies when the message answers a thread (threadIdor anIn-Reply-Toheader), and the one for new mail otherwise. An address with no signature of its own takes its domain catch-all's when the catch-all caught that address, else the Nextmail footer unless that address turned the footer off.signatureIdpicks another signature of the address. Template sends and encrypted sends never carry one.signatureIdStringAdds one particular signature of the
fromaddress in place of its default, by the idsignatures.listreturns. It signs anhtmlbody too, sosignature: trueis not needed with it, and it cannot be combined withsignature: false. An id that is not a signature of thefromaddress is a 422invalid_parameter. When the signature is deleted before a scheduled message goes out, the message carries the default of the address instead.tagsHashUp to 10 tags, keys of 1 to 64 letters, digits,
_or-, String values up to 256 characters. Echoed back on every read.streamStringThe lane the message travels in:
transactional, the default, for mail one person is waiting for, orbroadcastfor newsletters and other mail to many people. Each lane has its own queue and its own reputation.translateHashA Hash with
toand optionalfrom,includeOriginalandsubject.totakes a code, an English name or an endonym.includeOriginalandsubjectboth default to true.idempotency_keyStringYour own key, 1 to 255 characters of letters, digits,
_,.,:or-. Anything else is a 400invalid_idempotency_key.api_keyStringSends with this key instead of the client's, for a process sending on behalf of several workspaces.
Returns
A Hash with the message as get returns it, plus replayed. Notable fields are id (msg_ plus 24 hex), status, mode, from, subject, scheduledAt, cancellableUntil, sentAt, lastError, tags and, on a translated send, translation.
Example
sent = client.emails.send( from: "Acme Billing <[email protected]>", to: "[email protected]", subject: "Your September invoice", html: "<p>The invoice is attached. Tell me if anything on it looks wrong.</p>", translate: {to: "de"}, tags: {invoice: "inv_2026_09_4192"}, idempotency_key: "invoice:inv_2026_09_4192") p sent.values_at(:id, :status, :replayed), sent.dig(:translation, :language)Notes
A message sent with
streamset tobroadcastwhile that lane is paused for too many bounces or complaints is refused with 409stream_paused.sending.list_streamsshows why, and app mail on thetransactionallane still goes.On the
broadcastlane, a message to one recipient whoseheadershold noList-UnsubscribegetsList-UnsubscribeandList-Unsubscribe-Postfor one-click unsubscribe. Whoever uses them joins the unsubscribe list thatsuppressions.list_unsubscribesreads, and broadcast lane mail is not sent to anybody on that list: the recipient issuppressedandemail.suppressedsays why. Transactional mail still reaches them.A
fromon a domain that is known to the workspace but cannot sign mail yet is refused up front with 409domain_not_sendableandparamset tofrom, so nothing is accepted that would only fail at dispatch.addresses.listshows the same verdict ascanSendbefore you send.A test key (
oe_test_) never delivers. The message is markedsentwithtransportset totestand every recipientdelivered, so assert on the response and not on an inbox.The idempotency fingerprint covers the template version the send resolved to. Retrying an unpinned template send after somebody publishes a new version is a 422
idempotency_key_reuse, not a replay.scheduledAtis left out of the fingerprint.A spent send allowance is a 429
send_quota_exceededwith noRetry-After, and it resets on the first of the month. The SDK does not retry a 429 that carries noRetry-After, so it raises straight away.Translation failures refuse the send: 409
translation_not_configuredwhen the workspace has no AI, 422translation_too_longpast 30,000 characters, 429ai_quota_exceededwhen the workspace has used today's AI actions, and 503translation_failedwhen the provider did not answer.A translated send spends one AI action.
retryable?is true for every 429, butai_quota_exceededfails the same way until the allowance resets at midnight UTC, so show it to a person or send withouttranslate.A
followUpAtthat is not later than the time the message goes out, or is more than 365 days out, refuses the send with a 422 whoseparamisfollowUpAt, codedinvalid_follow_uporinvalid_parameter, and nothing is sent. The SDK sends aTimeor aDateTimeas a UTC ISO 8601 instant, as it does forscheduledAt.
Also available in
- API
POST /emails- TypeScript
nextmail.emails.send()- Python
emails.send()- PHP
emails->send- Go
Emails.Send- Java
emails().send- C#
Emails.SendAsync- CLI
openemail emails send
emails.send_batch
Send up to 100 independent emails in one request
send_batch(emails, idempotency_key: nil, api_key: nil) -> Nextmail::BatchResultSends each message in order, as if emails.send had been called for it, and reports per item. It is never all or nothing: a bad address on item 7 fails item 7 and the rest still go, because a batch that rolled back would turn your retry into a guess about which messages had already been delivered. The call returns whenever the batch was processed, so check failed and each item's status rather than relying on a raise.
The batch shares one Idempotency-Key, generated once per call or supplied as idempotency_key:, and the server derives a separate key per item from it and the item's position. Retrying the same Array replays the items that already went and sends only the ones that did not. Reordering the Array between attempts changes which body each position's key is bound to, so an item that moved comes back as an idempotency_key_reuse error.
Apart from a key or scope failure or a server fault, only problems with the batch as a whole raise, with a 422: an empty Array, more than 100 messages, or more than 10 messages carrying translate. Translation costs several model calls per message and they run one after another, so a larger translated batch would time out partway. Split it, or schedule the messages instead.
Parameters
emailsArray<Hash>RequiredBetween 1 and 100 messages, each a Hash shaped exactly like the body of
emails.send,followUpAtincluded, and validated on its own.idempotency_keyStringYour own batch key, 1 to 255 characters of letters, digits,
_,.,:or-.api_keyStringSends the batch with this key instead of the client's.
Returns
An Nextmail::BatchResult with sent, failed and items. Each item is a Hash with its index and either status set to ok with the email (a Hash shaped like the result of send) or status set to error with an error Hash carrying type, code, message and, when a field is to blame, param.
Example
shipments = [ {from: "[email protected]", to: "[email protected]", subject: "Order AC-4192 has shipped", text: "It is on its way."}, {from: "[email protected]", to: "[email protected]", subject: "Order AC-4193 has shipped", text: "It is on its way."}] result = client.emails.send_batch(shipments, idempotency_key: "shipments:2026-09-15") result.items.each do |item| warn "#{item[:index]} #{item[:error][:code]} #{item[:error][:message]}" if item[:status] == "error"end puts result.sent, result.failedNotes
Each entry is authorised on its own, so a
fromon a domain that cannot sign yet fails that entry withdomain_not_sendablewhile the rest go.Once the send allowance of the workspace runs out partway, every remaining item fails with
send_quota_exceededwhile the earlier ones stay sent. It is counted for that workspace alone, so sends from other workspaces never spend it. A workspace on a paid plan with pay as you go turned on keeps sending past it instead.Each item with
translatespends one AI action. Once that account has used today's AI actions, every remaining item withtranslatefails withai_quota_exceededwhile items without it still go. Retrying those items fails the same way until the allowance resets at midnight UTC, unless the account has pay as you go turned on.An unexpected server fault aborts the batch with a 500 after the earlier items have gone. The SDK retries it with the same key, which replays those items instead of sending them twice.
Items are processed one after another inside a single request, so a large batch of immediate sends takes noticeably longer than one
send. Keep the client'stimeout:generous.
Also available in
emails.translate
Preview a translation without sending anything
translate(body = nil, api_key: nil, **fields) -> HashRuns the same translation translate performs on a send and stops one step early. The same function produces both, so what comes back is what would go out. Nothing is stored and nothing is sent. Use it when somebody should read the translated wording before it reaches a recipient.
Send the approved result as an ordinary subject and html on emails.send with no translate field. Passing translate again translates a second time, moving the wording off the version that was signed off and discarding any edits. When includeOriginal is on, html already contains your original text below the translation, so do not append your own copy.
At least one of html, text or subject is required. to accepts a BCP-47 code, an English name or the language's own name, and the response reports the code it settled on in language[:code], which is the form worth storing. State from to skip language detection. Otherwise it is detected from the body, and a detector that cannot tell returns nil in detectedSourceLanguage rather than guessing.
Parameters
toStringRequiredTarget language as a code (
de), English name (German) or endonym (Deutsch). An unrecognised value is a 422invalid_parameteronto.fromStringThe language you wrote in. Stating it skips the detection call.
includeOriginalBooleanDefaults to true, placing your original text below the translation under a caption in the target language.
subjectStringSubject line to translate, at most 998 characters.
htmlStringHTML body to translate. Only the content inside
<body>is sent to the model when the markup is a full document.textStringPlain text body to translate. Translated separately when given alongside
html.api_keyStringRuns the preview with this key instead of the client's.
Returns
A Hash with object set to translation, language and detectedSourceLanguage as full language Hashes, subject, html and text (each nil when that input was not given) and includeOriginal.
Example
preview = client.emails.translate(to: "ja", subject: "Your September invoice", html: "<p>The invoice is attached.</p>") puts preview.dig(:language, :native), preview.dig(:detectedSourceLanguage, :code) client.emails.send( from: "Acme Billing <[email protected]>", to: "[email protected]", subject: preview[:subject] || "Your September invoice", html: preview[:html] || "<p>The invoice is attached.</p>")Notes
The SDK never retries this call. Each attempt spends one AI action, as a translated send does. Handle a 503
translation_failedyourself, and treat a 429ai_quota_exceededas final until the allowance resets at midnight UTC.Anything over 30,000 characters is refused with 422
translation_too_longrather than truncated, since half a translation has no seam to show where it stopped.A right-to-left target comes back with
htmlwrapped indir="rtl".A workspace with no AI configured gets 409
translation_not_configured, and retrying will fail the same way.
Also available in
emails.check
Check how a message would be rated, without sending it
check(body = nil, api_key: nil, **fields) -> HashScores a message the way a receiving mailbox would, before it goes out: a spam score, a phishing score and an AI-writing score, each 0 to 100, with the signals behind each one. Nothing is stored and nothing is sent.
The same checks score every message that arrives in a mailbox on Nextmail, so what comes back is what a recipient on Nextmail sees in Details. It cannot know a recipient's own filter, sender history or reputation, so a low score is a good sign and not a delivery guarantee.
Run it before an automated send, or as someone writes, and fix what signals names. Sender authentication is taken as passing, since the message will be signed for your domain.
Parameters
subjectStringSubject line, at most 998 characters.
htmlStringHTML body. Links and images are read from it.
textStringPlain text body. Taken from
htmlwhen left out.fromStringThe address it will be sent from.
fromNameStringThe display name it will carry. A name that claims another address or a known brand raises the phishing score.
replyToStringA Reply-To on a different domain raises the phishing score.
replyingBooleanTrue when it answers an existing thread. A
Re:subject on a message that answers nothing raises the spam score.attachmentNamesArray<String>File names, so an attachment that can run code is caught.
api_keyStringRuns the check with this key instead of the client's.
Returns
A Hash with object set to email_check and three scores, each a Hash. spam carries score, level (low, medium from 35, high from 60) and signals. phishing carries score, level (clear, caution from 30, danger from 60), signals and reasons. ai carries score (nil when not judged), level, signals, reasons, words and skipped (too-short under 40 words).
Example
check = client.emails.check( from: "[email protected]", subject: "Your September invoice", html: "<p>The invoice is attached.</p>") puts "Rework it first: #{check[:spam][:signals]}" unless check[:spam][:level] == "low" p check[:spam][:score], check[:phishing][:score], check[:ai][:score]Notes
It spends no AI action and never calls a model, so it is safe to run on every revision.
A score is not a probability. Each one adds up weighted signals, heaviest first in
signals.
Also available in
emails.list
List one page of sent emails, newest first
list(status: nil, from: nil, broadcast_id: nil, scheduled_from: nil, scheduled_to: nil, since: nil, until: nil, recipient: nil, tag: nil, limit: nil, cursor: nil, api_key: nil) -> Nextmail::PageReturns one page of the workspace's send records, ordered newest first. Paging is keyset rather than offset: next_cursor is the id of the last message on the page, and passing it back as cursor: continues strictly after it, so messages sent while you page never shift or repeat rows. has_more? is false on the last page and next_cursor is then nil.
Filter with status:, one value or an Array that the SDK joins with commas, with from:, which matches the sending address exactly and ignores case, with broadcast_id:, which keeps the copies of one broadcast, and with scheduled_from: and scheduled_to:, which keep the messages scheduled inside a window. An unrecognised status is a 422 invalid_parameter naming the offending values, and a cursor that names no message in the workspace is a 400 invalid_cursor.
Rows are the summary form. They never carry recipients or translation, whose absence on a row says nothing either way, and a tracked message carries only the counts half of tracking: opens, clicks, opened, clicked, openCount, clickCount and firstOpenAt. Call get for per-recipient delivery state and get_tracking for the full engagement report.
Parameters
statusString or Array<String>One or more of
queued,scheduled,sending,sent,partial,bounced,cancelledandfailed.bouncedmeans every recipient the message went to bounced, while one that bounced for some and reached the rest readspartial.fromStringA bare sending address such as
[email protected], matched exactly and case insensitively. A display name form does not match.broadcast_idStringOnly the copies of one broadcast, a
brd_id frombroadcasts.send. Each person a broadcast reaches gets a message of their own, so this lists who it went to and what happened to each copy. An id that names no broadcast answers an empty page.scheduled_fromTime, DateTime or StringOnly messages scheduled for this instant or later. With
scheduled_to:andstatus: ["scheduled", "queued"]it lists what is waiting to go out in a window, as the calendar of the app does. A message with noscheduledAtis left out.scheduled_toTime, DateTime or StringOnly messages scheduled for this instant or earlier.
scheduled_from:afterscheduled_to:is a 422invalid_parameter.sinceTime, DateTime or StringOnly messages made at this instant or later.
untilTime, DateTime or StringOnly messages made before this instant.
since:afteruntil:is a 422invalid_parameter.recipientStringOnly messages that went to this address as a to, cc or bcc recipient, matched exactly.
tagStringOnly messages sent with this tag:
namefor any value, orname:valuefor one value. Tags are stored encrypted, so the match is exact and case-sensitive.limitIntegerRows per page, a whole number from 1 to 100, defaulting to 25. Outside that range is a 422.
cursorStringThe
next_cursorfrom the previous page, which is a message id.api_keyStringLists with this key instead of the client's.
Returns
An Nextmail::Page of Hashes, with items, has_more? and next_cursor. Each item has id, status, mode, from, subject, transport, attempts, lastError, scheduledAt, cancellableUntil, sentAt, tags, broadcastId, source, createdAt and, when tracked, the trimmed tracking counts.
Example
page = client.emails.list(status: ["failed", "partial"], from: "[email protected]", limit: 50) page.items.each { |email| puts "#{email[:id]} #{email[:status]} #{email[:lastError]}" } if page.has_more? next_page = client.emails.list(status: ["failed", "partial"], cursor: page.next_cursor) puts next_page.items.sizeendNotes
With a narrowed key only messages sent from addresses it covers are read, and the page is cut after that filter, so every page but the last holds
limititems. A key that holds a whole domain covers every address on it.A
fromthe key does not cover returns an empty last page rather than a 403.trackingis absent, not zeroed, on a message that carried no pixel or rewritten link.
Also available in
- API
GET /emails- TypeScript
nextmail.emails.list()- Python
emails.list()- PHP
emails->list- Go
Emails.List- Java
emails().list- C#
Emails.ListAsync- CLI
openemail emails list
emails.list_all
Collect every matching sent email into one array
list_all(status: nil, from: nil, broadcast_id: nil, scheduled_from: nil, scheduled_to: nil, since: nil, until: nil, recipient: nil, tag: nil, limit: nil, cursor: nil, api_key: nil) -> Array<Hash>Follows next_cursor from page to page and returns once the last page has been read, with every matching send record in one Array, newest first. It accepts the same filters as list and returns the same summary rows, so there are no recipients or translation on them and tracking is the trimmed counts form.
Everything is held in memory before the call returns, and a workspace's send history grows without bound. Narrow it with status: or from:, or switch to iterate when you want to stop early or process rows as they arrive. limit: sets the page size of each underlying request, not the total, so a larger value means fewer round trips.
Parameters
statusString or Array<String>One or more statuses to keep, joined with commas on the wire.
fromStringA bare sending address, matched exactly and case insensitively.
broadcast_idStringOnly the copies of one broadcast, a
brd_id.scheduled_fromTime, DateTime or StringOnly messages scheduled for this instant or later.
scheduled_toTime, DateTime or StringOnly messages scheduled for this instant or earlier.
sinceTime, DateTime or StringOnly messages made at this instant or later.
untilTime, DateTime or StringOnly messages made before this instant.
recipientStringOnly messages that went to this address as a to, cc or bcc recipient.
tagStringOnly messages sent with this tag:
namefor any value, orname:valuefor one value.limitIntegerPage size per request, from 1 to 100, defaulting to 25 on the server.
cursorStringA message id to start after, skipping everything newer.
api_keyStringLists with this key instead of the client's.
Returns
An Array of Hashes holding every row across all pages.
Example
scheduled = client.emails.list_all(status: "scheduled", limit: 100)due_today = scheduled.select { |email| email[:scheduledAt]&.start_with?("2026-09-15") } puts scheduled.sizep due_today.map { |email| email[:id] }Notes
A failure on any page raises out of the whole call, and the rows already fetched are discarded.
With a narrowed key only messages sent from addresses it covers are collected, and every page but the last is full.
Also available in
- API
GET /emails- TypeScript
nextmail.emails.listAll()- Python
emails.list_all()- PHP
emails->listAll- Go
Emails.ListAll- Java
emails().listAll- C#
Emails.ListAllAsync
emails.iterate
Stream sent emails one at a time across pages
iterate(status: nil, from: nil, broadcast_id: nil, scheduled_from: nil, scheduled_to: nil, since: nil, until: nil, recipient: nil, tag: nil, limit: nil, cursor: nil, api_key: nil, &block) -> Enumerator<Hash>Returns an Enumerator that yields send records individually, newest first, and requests the next page only once the current one is drained. Given a block, it yields each record to the block instead. Nothing is fetched until you start consuming it, and breaking out of the loop stops the requests, so this is the cheapest way to find the most recent message matching a condition the filters cannot express.
The walk is keyset based, following next_cursor from page to page. Mail sent while you iterate lands ahead of where you started and is never yielded, and nothing already yielded comes round again. Rows are the same summary form list returns.
Parameters
statusString or Array<String>One or more statuses to keep, joined with commas on the wire.
fromStringA bare sending address, matched exactly and case insensitively.
broadcast_idStringOnly the copies of one broadcast, a
brd_id.scheduled_fromTime, DateTime or StringOnly messages scheduled for this instant or later.
scheduled_toTime, DateTime or StringOnly messages scheduled for this instant or earlier.
sinceTime, DateTime or StringOnly messages made at this instant or later.
untilTime, DateTime or StringOnly messages made before this instant.
recipientStringOnly messages that went to this address as a to, cc or bcc recipient.
tagStringOnly messages sent with this tag:
namefor any value, orname:valuefor one value.limitIntegerPage size per request, from 1 to 100, defaulting to 25 on the server.
cursorStringA message id to start after.
api_keyStringLists with this key instead of the client's.
Returns
An Enumerator of Hashes, one send record per step (or yields each one to a block).
Example
failed = client.emails.iterate(status: "failed", limit: 100).find do |email| email.dig(:tags, :invoice) == "inv_2026_09_4192"end puts failed[:id], failed[:lastError] if failedNotes
The Enumerator is lazy, so an abandoned loop costs only the pages you consumed.
With a narrowed key only messages sent from addresses it covers are yielded, and every page but the last is full.
Also available in
- API
GET /emails- TypeScript
nextmail.emails.iterate()- Python
emails.iterate()- PHP
emails->iterate- Go
Emails.Iterate- Java
emails().iterate- C#
Emails.IterateAsync
emails.get
Read one sent email with per-recipient state
get(id, api_key: nil) -> HashReturns the full send record for one message: its lifecycle status, delivery attempts and lastError, the schedule fields, and the two parts a list row leaves out. recipients has one entry per address with its own status, error and deliveredAt, and translation records what was done to a translated send.
A message that went out as a single call can still land differently per recipient. status on the message says how the send went as a whole, while each recipient moves on as delivery reports, bounces and complaints arrive. uncertain is a real recipient state: a transport that failed partway cannot say which recipients it reached. suppressed marks an address that previously bounced or complained in this workspace and was held back.
When the message was tracked, tracking carries the full engagement report with per-recipient and per-link detail. When it was not tracked, the field is absent rather than zeroed, because a message with no pixel has no evidence about whether anybody read it.
Parameters
idStringRequiredThe send id,
msg_followed by 24 hex characters, as returned bysend.api_keyStringReads with this key instead of the client's.
Returns
A Hash with id, status, mode, from, subject, threadId, transport, attempts, lastError, scheduledAt, cancellableUntil, sentAt, tags, broadcastId, source, createdAt, recipients and, when present, translation and the full tracking report.
Example
email = client.emails.get("msg_3f9a1c07d2b84e6a9c5b1f20")undelivered = (email[:recipients] || []).reject { |recipient| recipient[:status] == "delivered" } puts email[:status]p undelivered.map { |recipient| recipient.values_at(:email, :status, :error) }Notes
Do not correlate on
messageId. The header is rewritten on the way out, so that value appears in no bounce or delivery report. Webhook events name the send by thisid, asemailId.A 404 never distinguishes a missing id from one in another workspace, and a narrowed key gets the same 404 for a message sent from an address it does not cover.
transportstays nil until dispatch, and readsteston every message sent with a test key.
Also available in
- API
GET /emails/{id}- TypeScript
nextmail.emails.get()- Python
emails.get()- PHP
emails->get- Go
Emails.Get- Java
emails().get- C#
Emails.GetAsync- CLI
openemail emails get
emails.list_events
Read one page of the event trail of one sent email
list_events(id, limit: nil, cursor: nil, api_key: nil) -> Nextmail::PageReturns one page of everything recorded against one send, oldest first. Nothing is dropped from the trail, so following next_cursor while has_more? is true reaches its newest event, and list_all_events and iterate_events do that walk for you. It is the audit behind the current status: when the message was accepted or held, when it was rescheduled or cancelled, when it went out or failed, and every delivery report, bounce, complaint, open, click and file download attributed to it afterwards.
Each event has a dotted type and a data Hash whose shape depends on it. email.accepted, email.queued and email.scheduled open the trail with the source and recipient count. email.sent names the transport and messageId. email.failed carries the error. email.bounced and email.complained list the affected recipients and whether they were suppressed. email.delivered, email.rescheduled, email.cancelled, email.opened, email.clicked and email.downloaded follow as they happen. email.downloaded counts a person fetching a file that went out as a download link, never a scanner, and carries no recipient: the link is the same for everyone the message went to, so a download cannot be attributed. data is an empty Hash when an event carries nothing.
Webhooks deliver a subset of these same events as they occur, so this is where to look when a webhook was missed or never subscribed.
Parameters
idStringRequiredThe
msg_send id whose trail to read.limitIntegerEvents per page, a whole number from 1 to 100, defaulting to 25.
cursorStringThe
next_cursorfrom the previous page, which is an event id. One that names no event of this send is a 400invalid_cursor.api_keyStringReads with this key instead of the client's.
Returns
An Nextmail::Page of Hashes, with items, has_more? and next_cursor. Each item has object set to event, id, type, data and createdAt.
Example
page = client.emails.list_events("msg_3f9a1c07d2b84e6a9c5b1f20", limit: 100)bounce = page.items.find { |event| event[:type] == "email.bounced" } p page.items.map { |event| event[:type] }, bounce&.dig(:data), page.has_more?Notes
email.deliveredis recorded in this trail but is never sent as a webhook, so a delivery report surfaces only here and inrecipientsonget.A send made with a test key records
email.sentwithtransportset totestandsimulatedset to true indata.An unknown id is a 404, never an empty page.
A tracked message opened or clicked many times records one event per counted hit, so its trail can run to many pages.
Also available in
emails.list_all_events
Collect the whole event trail of one sent email into one array
list_all_events(id, limit: nil, cursor: nil, api_key: nil) -> Array<Hash>Walks every page of one send's event trail and returns all of it, oldest first: acceptance, scheduling, sending, every delivery report, bounce and complaint, and every counted open, click and download afterwards.
A widely read message can hold a great many events, all in memory before the call returns. Prefer iterate_events when you can stop early. limit: sets the page size of each request, not the total.
Parameters
idStringRequiredThe
msg_send id whose trail to read.limitIntegerPage size per request, from 1 to 100, defaulting to 25 on the server.
cursorStringAn event id to start after, skipping every older event.
api_keyStringReads with this key instead of the client's.
Returns
An Array of Hashes holding every event across all pages, oldest first.
Example
events = client.emails.list_all_events("msg_3f9a1c07d2b84e6a9c5b1f20", limit: 100)opens = events.count { |event| event[:type] == "email.opened" } puts events.size, opensNotes
A failure on any page raises out of the whole call, and the events already fetched are discarded.
An unknown id is a 404 on the first page.
Also available in
emails.iterate_events
Stream the event trail of one sent email one event at a time
iterate_events(id, limit: nil, cursor: nil, api_key: nil, &block) -> Enumerator<Hash>Returns an Enumerator over one send's event trail that yields events individually, oldest first, and fetches the next page only when the current one is drained. Given a block, it yields each event to the block instead. Nothing is requested until you consume it, and breaking out of the loop stops further requests.
The walk moves forward in time, so events recorded while you iterate are yielded when the walk reaches them, and it ends when a page reports has_more? false.
Parameters
idStringRequiredThe
msg_send id whose trail to read.limitIntegerPage size per request, from 1 to 100, defaulting to 25 on the server.
cursorStringAn event id to start after, skipping every older event.
api_keyStringReads with this key instead of the client's.
Returns
An Enumerator of Hashes, one event per step (or yields each one to a block).
Example
delivered = client.emails.iterate_events("msg_3f9a1c07d2b84e6a9c5b1f20").find { |event| event[:type] == "email.delivered" } puts "delivered at #{delivered[:createdAt]}" if deliveredNotes
The Enumerator is lazy, so an abandoned loop costs only the pages you consumed.
Also available in
emails.get_tracking
Read the engagement report for a sent email
get_tracking(id, api_key: nil) -> HashReturns the same document tracking.get serves, reached from the msg_ id a sender already holds. It has the message totals, one entry per tracked copy under recipients, and every rewritten link with its clicks under links.
A message that was never tracked is a 404 here rather than an empty report. "We were not recording" and "nobody opened it" are different answers, and a client that renders them the same way makes a claim about a reader on no evidence. Tracking applies per send: opens and clicks record what was applied when the message went out, resolved from the setting of the address it was sent from (its own, else its domain catch-all's when the catch-all caught that address, else off) and any tracking override on the send, not what is switched on now.
Read every count as a floor. An open is inferred from a mail client fetching an image, so a reader whose client blocks images is never counted, and Gmail fetches the image once through its proxy and serves later views from cache. A click is stronger evidence than an open.
Parameters
idStringRequiredThe
msg_send id returned bysend.api_keyStringReads with this key instead of the client's.
Returns
A Hash with object set to tracking, id (the tmsg_ tracking id), sendId, opens, clicks, opened, clicked, attributable, openCount, clickCount, openCountRaw, clickCountRaw, the first and last open and click times, recipients and links.
Example
report = client.emails.get_tracking("msg_3f9a1c07d2b84e6a9c5b1f20") if report[:attributable] unopened = report[:recipients].select { |recipient| recipient[:attributed] && recipient[:openCount] == 0 } p unopened.map { |recipient| recipient[:email] }end puts report[:openCount]p report[:links].map { |link| link.values_at(:url, :clickCount) }Notes
Only claim a named recipient has not opened when
attributableis true. Mail that went to the whole list as one body has a shared copy whoseemailis nil, and its opens cannot be pinned to anybody.A message sent with a test key is never tracked, so this is always a 404 for one.
openCountRawminusopenCountincludes machine fetches such as Apple Mail Privacy Protection and repeats within thirty seconds, so do not read the difference as a pure machine count.
Also available in
emails.cancel
Stop a queued or scheduled email before it goes
cancel(id, api_key: nil) -> HashCancels a message that has not been dispatched yet: a send held by scheduledAt, or an immediate send still inside its cancellableForSeconds undo window. The message moves to cancelled, nothing is delivered, and an email.cancelled event is recorded and sent to subscribed webhooks.
Only queued and scheduled messages can be cancelled. Once a message is sending, sent, partial, bounced or failed the call is a 409 email_not_cancellable, since there is no pending dispatch left to stop and mail that has gone cannot be recalled. An immediate send with no undo window is dispatched inside the send request, so by the time you hold its id it is usually past this point.
Cancelling is idempotent. Cancelling an already cancelled message returns the same cancelled message rather than an error, and the SDK retries the call after a network failure or a retryable status.
Parameters
idStringRequiredThe
msg_send id to cancel.api_keyStringCancels with this key instead of the client's.
Returns
A Hash with the message in its new state, with status set to cancelled and scheduledAt and cancellableUntil still showing when it would have gone.
Example
queued = client.emails.send( from: "[email protected]", to: "[email protected]", subject: "Your September invoice", text: "Invoice attached.", cancellableForSeconds: 30) cancelled = client.emails.cancel(queued[:id]) puts cancelled[:status]Notes
cancellableUntilon the message is the moment it stops being cancellable. Past it, expect the 409.A cancelled message stays cancelled. There is no way to resume it, so send again if you change your mind.
A narrowed key gets a 404 for a message sent from an address it does not cover.
Also available in
emails.reschedule
Move a queued or scheduled email to a new send time
reschedule(id, scheduled_at, api_key: nil) -> HashChanges when a message that has not gone yet will be dispatched. scheduledAt is the only thing this call can change, and the SDK sends nothing else: the body, recipients and any translation stay exactly as they were accepted.
The new time takes a Time or DateTime, an ISO 8601 instant or a duration such as PT30M or P2D, measured from when the server receives the request. It must be at least one second in the future and at most 365 days out, otherwise the call is a 422 on scheduledAt, usually invalid_parameter. Earlier and later times are both allowed.
Only queued and scheduled messages can be moved. Anything already sending, sent, partial, bounced, cancelled or failed is a 409 email_not_cancellable. A queued message inside its undo window can be rescheduled too, which turns it into a scheduled send that stays cancellable until the new time.
Parameters
idStringRequiredThe
msg_send id to move.scheduled_atTime, DateTime or StringRequiredThe new send time. A
TimeorDateTimeis sent as a UTC ISO 8601 instant, and a String is passed through as an instant or a duration.api_keyStringReschedules with this key instead of the client's.
Returns
A Hash with the message, its status set to scheduled and scheduledAt and cancellableUntil both set to the new time.
Example
tomorrow_morning = Time.utc(2026, 9, 16, 8) moved = client.emails.reschedule("msg_3f9a1c07d2b84e6a9c5b1f20", tomorrow_morning) puts moved[:status], moved[:scheduledAt]Notes
The SDK retries this call after a network failure. A duration is resolved again on each attempt, so a retried
PT1Hlands an hour after the last attempt the server received.An
email.rescheduledevent with the newscheduledAtis added to the trail on every successful move.A translated scheduled message keeps its approved wording. To change the text itself, cancel it and send again.
Also available in
emails.update
Change an email that has not gone yet
update(id, patch = nil, api_key: nil, **fields) -> HashChanges a queued or scheduled message before it is dispatched: when it goes with scheduledAt, what it says with subject, html and text, the address it goes out as with from, and who it goes to with to, cc and bcc. Send any of them together, and a field you leave out keeps its value. This is what editing a scheduled message in the calendar of the app does.
A recipient list replaces the stored one whole, and takes a String such as Ada <[email protected]>, a Hash with email and name, or an Array of either. from is checked as it is on a send, so it has to be an address the key may send as, or the call is a 403 from_address_forbidden.
Only messages that have not gone can change. Anything already sending, sent, partial, bounced, cancelled or failed is a 409 email_not_cancellable. A message translated when it was accepted keeps its approved wording, so a new subject, html or text on it is a 409 translation_locked, and one that was encrypted before it was scheduled keeps its wording and its recipients. Cancel those and send again instead.
Parameters
idStringRequiredThe
msg_send id to change.scheduledAtTime, DateTime or StringA new send time: a
TimeorDateTime, sent as a UTC ISO 8601 instant, an ISO 8601 instant String or a duration such asPT2H, in the future and at most 365 days out.subjectStringThe new subject, up to 998 characters.
htmlStringThe new HTML body.
textStringThe new plain text body.
fromStringThe address it goes out as instead, one the key may send as.
toString, Hash or ArrayReplaces the recipients, at least one and at most 50 across the three lists.
ccString, Hash or ArrayReplaces the copied recipients.
bccString, Hash or ArrayReplaces the blind copied recipients.
api_keyStringChanges it with this key instead of the client's.
Returns
A Hash with the message as it is now. Its subject, from and scheduledAt show the change.
Example
updated = client.emails.update( "msg_3f9a1c07d2b84e6a9c5b1f20", subject: "Your September invoice, corrected", to: ["[email protected]", "[email protected]"], scheduledAt: Time.utc(2026, 10, 5, 8)) puts updated[:status], updated[:subject], updated[:scheduledAt]Notes
The SDK retries this call after a network failure, which is safe because a repeat writes the same values.
An
email.updatedevent naming the changed fields is added to the trail, and a move addsemail.rescheduledas well.rescheduleis the same call with onlyscheduledAt.
Also available in
emails.compose
Write an email with AI
compose(body = nil, api_key: nil, **fields) -> HashWrites the body of an email from prompt, an instruction, a rough draft or a few notes, in the style of the mail this workspace has sent before, as the composer of the app does. subject, to and cc help the greeting and the tone fit, and from, the address it goes out as, has it written as that address.
Give threadId to write a reply: the messages of that thread are read as context, which also needs threads:read, and a key limited to particular addresses can only use a thread that arrived at them.
Give draft, the body written so far, and prompt says what to change in it, as the describe bar of the composer does. withSubject: true adds subject to the answer. Give send, the send options as they stand, even {}, and prompt may change the recipients, the send time, tracking, the signature and the language: the answer's send holds only what changed, in the shape emails.send takes, and nil takes an option away. Add send[:fromOptions], the addresses it may go out as, and prompt may move it to one of them, which the answer names in send[:from]. Add send[:encrypt], whether it is encrypted end to end as it stands, only when every recipient can receive encrypted mail, and prompt may turn encryption on or off. Times such as "tomorrow at 9" are read in timeZone, or the time zone of the account.
Give templates: true and prompt may switch the email to one of the workspace's published templates, which the answer names in template: send that template with emails.send in place of body, because its body replaces it. Give template, the id of the template the email uses now, and prompt leaves the body alone. Give files: true and prompt may attach files the workspace holds, found by their name: the answer lists them in attach, each ready to send as {fileId: file[:id]} in attachments, and names in attachMissing what matched no file. templates needs templates:read and files needs files:read, and each is ignored without its scope. A key limited to particular addresses only finds the files at those addresses.
Nothing is saved or sent. Pass body to emails.send or drafts.create when it reads right. Each call spends one of the workspace's AI actions, and a workspace that has used them all for the day is refused with a 429 ai_quota_exceeded.
Parameters
promptStringRequiredWhat to write, up to 20,000 characters. With
draft, what to change in it, and it may be empty to have the draft finished as it is.subjectStringThe subject so far, if there is one.
fromStringThe address it goes out as, so it is written as that address.
templateStringThe id of the template the email uses now, up to 128 characters. Its body is then the template, so
promptleaves the body alone.templatesBooleanLet
promptswitch the email to one of the workspace's published templates, which the answer names intemplate. Needstemplates:read, and without it this is ignored.filesBooleanLet
promptattach files the workspace holds, found by their name. The answer lists them inattach, each ready to send as{fileId: file[:id]}, and what matched no file inattachMissing. Needsfiles:read, and without it this is ignored.withSubjectBooleanAlso write a subject. The answer then carries
subject.draftStringThe body written so far, as text or Markdown, up to 20,000 characters.
toArray<String>Who it goes to.
ccArray<String>Who is copied.
bccArray<String>Who is blind copied.
sendHashThe send options as they stand:
scheduledAt,tracking,signature,translate,fromOptionsandencrypt, each optional. Give it, even{}, to letpromptchange them.fromOptionslists up to 100 addresses it may go out as, sopromptcan move it to one of them, andencryptsays whether it is encrypted end to end: give it only when every recipient can receive encrypted mail, sopromptcan turn encryption on or off.timeZoneStringThe IANA time zone to read times in, such as
Europe/Berlin. Without it, the time zone of the account.threadIdStringA thread to reply in, read as context.
api_keyStringOverrides the client's API key for this call only.
Returns
A Hash with object set to composition and body, the written text, plus subject when asked with withSubject, send when send was given, template, attach and attachMissing when templates or files was given and prompt asked for them, note, a short sentence when part of prompt cannot be done this way, such as adding somebody whose address it was not given, and sources when the draft drew on the knowledge base. Its send can carry from, the address to send it from instead, one of send[:fromOptions], and encrypt, whether to encrypt it end to end, when send[:encrypt] was given. template is a Hash with the id and name of the template to send it with instead, whose body replaces body. attach is an Array of the files to attach, each a Hash with id, filename, contentType and size in bytes, and attachMissing an Array of what prompt asked to attach that matched no file, as prompt named it. sources is an Array of the knowledge base items it drew on, the pinned notes at the levels of the sending address and the items whose passages matched the request, each a Hash with id, title, kind (note, file or link), scope, the level it sits at, and url, the page a link reads or nil.
Example
composition = client.emails.compose( prompt: "Send Ada the signed contract and ask for the invoice by Friday.", from: "[email protected]", to: ["[email protected]"], withSubject: true, files: true) client.emails.send( from: "[email protected]", to: ["[email protected]"], subject: composition.fetch(:subject, "The signed contract"), text: composition[:body], attachments: composition.fetch(:attach, []).map { |file| {fileId: file[:id]} })Notes
The SDK does not retry it, because a second call writes something different and spends a second AI action.
A server with no AI configured answers 409
ai_not_configured.
Also available in
emails.rewrite
Rewrite part of an email with AI
rewrite(body = nil, api_key: nil, **fields) -> HashRewrites a subject or a body and returns different versions of it, as the rewrite menu of the composer does. action is shorten, lengthen, rephrase, formal, casual or custom, and custom needs instruction to say what to change, or the call is a 422 invalid_parameter on instruction. target is body, the default, or subject, and count asks for 1 to 5 versions, 3 by default.
Give threadId when the text is a reply, so the rewrite fits the conversation. That also needs threads:read. The versions never repeat the original and never add facts that are not in it.
Nothing is saved. Each call spends one of the workspace's AI actions.
Parameters
textStringRequiredThe subject or body to rewrite.
actionStringRequiredWhat to do:
shorten,lengthen,rephrase,formal,casualorcustom.targetStringbodyorsubject. Defaults tobody.instructionStringWhat to change, up to 500 characters. Required with
custom.countIntegerHow many versions, 1 to 5. Defaults to 3.
threadIdStringThe thread the text replies in, read as context.
api_keyStringOverrides the client's API key for this call only.
Returns
A Hash with object set to rewrite, target and variations, an Array of Strings.
Example
rewrite = client.emails.rewrite( text: "Hey, just checking whether you had a chance to look at the contract?", action: "formal") puts rewrite[:variations]Notes
The SDK does not retry it, because a second call spends a second AI action.
Fewer versions than
countcan come back when two of them turned out the same.
Also available in
emails.suggest_subject
Suggest a subject line
suggest_subject(body = nil, api_key: nil, **fields) -> HashReads the body of an email and returns a short subject for it, under 100 characters, in the style of the mail this workspace has sent, as the subject button of the composer does.
Nothing is saved. Each call spends one of the workspace's AI actions.
Parameters
messageStringRequiredThe body of the email, as text or HTML.
api_keyStringOverrides the client's API key for this call only.
Returns
A Hash with object set to subject_suggestion and subject.
Example
suggestion = client.emails.suggest_subject(message: "Thanks for the signed contract. Could you send the invoice by Friday?") puts suggestion[:subject]Notes
The SDK does not retry it, because a second call spends a second AI action.