NightmailDocs
Docs
Guide

Rules and AI decisions

Ready-made or scripted rules that post, forward, junk and label mail, and the questions they can ask Nightmail’s AI.

What a rule is

A rule is a short script that runs on every email sent to the addresses it’s attached to. It reads the email and chooses what happens: junk it, label it, post it to Slack, send it to a webhook, forward it. It can’t do anything else: no loops, no clock, no network calls of its own, so it always finishes and does the same thing for the same email.

export default function route(email, ctx) {
  // Newsletters go to Junk: kept, but not sent anywhere.
  if (email.headers.has("list-unsubscribe") || email.flags.bulk) {
    junk("newsletter")
    return
  }
  // Refund requests get a label and a Slack post.
  const asks = decisions(email, { refund: "Is the sender asking for a refund?" })
  if (asks.refund >= 0.7) {
    label("refund")
    endpoints.support({ text: `Refund request from ${email.from.address}: ${email.subject}` })
  }
}

Ready-made rules

Mail routing → Rules → New rule lists ready-made rules by what they do: tell your team, pass it on, keep out junk, sort with AI. Pick one, fill in one or two fields (a Slack channel, the senders to block) and choose its addresses; Save turns it on. A Slack, Discord or webhook URL you paste there becomes an endpoint, stored encrypted.

Each one writes an ordinary rule, shown in the list as its sentence, like Post new mail to support in Slack, with when it last matched and a switch that turns it off without detaching it. Opening one shows its code; saving a change there makes it your own script. AI rules are free.

Writing a script

For anything else, Mail routing → Rules → New rule → Write code. A rule’s page is its code. The editor checks it as you type and completes email., ctx. and your endpoint names. Try on recent mail (⌘↵) runs your draft on recent emails without saving or sending anything. Save (⌘S) keeps the code, where it runs and whether it’s on, together; Undo goes back to the saved rule, and leaving asks first.

Where it runs

A rule runs only on mail to the addresses it’s attached to. Choose its addresses on the line beside its name, or attach it from an address’s page. Up to 10 rules run on an address, in order. The first one that acts stops the rest, unless its Run the next one too is on; ready-made rules always have it on and run before your scripts.

What it can do

CallWhat it does
block(reason?: string)Reject this message for this recipient. Nothing is stored or delivered.
drop(reason?: string)Discard this message for this recipient without storing it.
junk(reason?: string)Store it as junk: kept, but not delivered to webhooks without junk include.
allow()Clear the junk flag. Ignored unless the sender is authenticated (email.auth.fromVerified).
label(name: string)Add a label to the stored message (up to 10).
inbox.deliver(key: string)Also deliver to the inbox with this key.
decisions(email, { name: "question" })Ask Nightmail’s AI each question once per message. Returns a 0–1 score per name, or a boolean for type "boolean". Questions must be literal text.
lists.has(list: string, value: string)True when the sender list contains the address, or "@domain" covers it.
addr.matches(address: string, pattern: string)Glob match on an address: "*@example.com", "billing+*@acme.io".
text.snippet(text: string, maxChars: number)The first maxChars characters (at most 4,096).
email.headers.get(name: string)First value of a header, or null.
email.headers.getAll(name: string)Every value of a header, in order.
email.headers.has(name: string)True when the header is present.
Endpoint callWhat it does
endpoints.support({ text })Posts plain text to a Slack incoming webhook. Mentions and link previews are off.
endpoints.alerts({ content })Posts plain text to a Discord webhook. Mentions are off.
endpoints.crm(payload?)Posts a signed JSON request: your payload as its body, or the message.received event without one.
endpoints.team()Forwards the message (text, HTML and attachments) from the receiving address. The recipient must have confirmed.

What it can read

The email, as email, and the run, as ctx. Everything sender-supplied is untrusted: check email.auth.fromVerified before trusting who it’s from.

FieldMeaning
email.idNightmail message ID (msg_…).
email.messageIdThe Message-ID header.
email.subjectSubject line.
email.fromA parsed address.
email.from.nameDisplay name, if any. Unverified unless auth.fromVerified.
email.from.addressLowercase email address.
email.from.localThe part before @.
email.from.domainThe part after @.
email.toTo recipients.
email.ccCc recipients.
email.replyToReply-To addresses.
email.envelopeSMTP envelope.
email.envelope.fromMAIL FROM.
email.envelope.toRCPT TO addresses.
email.dateThe Date header (ISO 8601).
email.receivedAtWhen Nightmail received it (ISO 8601).
email.sizeRaw size in bytes.
email.headersHeaders by lowercase name. Prefer email.headers.get(name).
email.textPlain-text body.
email.visibleTextText a reader would see, with hidden content removed (64 KiB max).
email.hiddenContentTrue when the HTML hides text from readers.
email.linksVisible links.
email.htmlSanitized HTML body.
email.attachmentsAll attachments.
email.imagesImage attachments.
email.authSender authentication from SES.
email.auth.fromVerifiedTrue when DMARC-aligned SPF or DKIM authenticates the From domain.
email.auth.spfpass, fail, gray or none.
email.auth.dkimpass, fail, gray or none.
email.auth.dmarcpass, fail, gray or none.
email.spamSpam verdict.
email.spam.sesSES spam verdict: pass, fail, gray or none.
email.spam.junkTrue when Nightmail already marked it junk.
email.spam.reasonWhy it is junk.
email.flagsMessage traits.
email.flags.automatedAuto-generated or bulk mail.
email.flags.autoReplyHas Auto-Submitted.
email.flags.bulkHas List-Id.
email.flags.listIdThe List-Id header.
email.flags.forwardHopsNightmail forwarding hops already taken.
email.threadConversation.
email.thread.idThread ID.
email.thread.isReplyTrue when it replies to an earlier message.
email.thread.inReplyToIn-Reply-To Message-ID.
email.thread.referencesReferences Message-IDs.
email.parsedFalse when the MIME could not be parsed; only headers are reliable.
email.truncatedTrue when the stored body was cut at the size limit.
ctx.recipientThe address this run is for (one run per recipient).
ctx.localLocal part of the recipient.
ctx.hostDomain of the recipient.
ctx.subaddressText after + in the local part.
ctx.routeThe route this rule runs on.
ctx.route.idRoute ID.
ctx.route.tierexact, pattern, plus, catch-all or default.
ctx.defaultsDestinations routing already chose (inbox and webhook IDs).
ctx.junkTrue when the message is junk so far.
ctx.nowReceipt time (ISO 8601). Rules have no clock.

AI decisions: questions for Nightmail’s AI

Questions a rule asks Nightmail’s AI about an email, answered 0 to 1. Ask with decisions(email, { name: "question" }); each name comes back as a score you compare, like asks.refund >= 0.7. One request per email answers every question in every rule.

Nightmail’s AI only reads mail at the receiving hosts you list under AI decisions can read mail at in the rule editor. Everywhere else, and in Try it and Test, an AI decision gives its default answer instead; in Try it you set each answer with a slider to see what the rule would do.

Sender lists

Named lists of senders, edited below the rule: vip: ceo@example.com, @partner.example. Check one with lists.has("vip", email.from.address); @domain covers everyone at that domain.