Mail rules
Most users who want their mail sorted never write Sieve. They want newsletters filed into a folder, mail from one sender flagged, a copy of invoices forwarded to the accountant, or a reply sent while they are away, and they expect to set this up in a form. Mail rules provide that. A mail rule is a structured object (MailRule), with conditions and actions chosen from fixed lists, that users create in the WebUI under Account › Filters & Auto-Replies › Mail Rules, that JMAP clients manage through the x:MailRule object, and that Outlook creates from its own rules when it connects over the Exchange protocols.
Rules are not a second filtering engine. Stalwart compiles every rule of an account, the account’s blocked and safe senders and its vacation response into one Sieve script named managed, and runs that script at delivery like any other user script, in the untrusted interpreter. The rules are therefore subject to the same limits as user scripts, and they can be combined with a script the user writes, as described in Managed script.
A rule has a name, and runs only while isEnabled is set. Rules run in ascending order of position, and rules with the same position in the order they were created. Beyond these, a rule is made of two objects: conditions, which select the messages the rule applies to, and actions, which say what happens to them.
Conditions
Section titled “Conditions”Mail clients present rules as forms with a few fixed groups, and the conditions object follows that layout. It holds three lists of tests:
matchAll: every test in the list must matchmatchAny: at least one test in the list must match, unless the list is emptymatchNone: no test in the list may match; these are the rule’s exceptions
A message matches the rule when all three groups agree, so the rule reads as “all of these, and any of those, unless one of these others”. A rule whose groups are all empty applies to every message. Each list holds up to 32 tests, and the same kind of test may appear more than once in a list, for example two From tests with different operators or two Header tests on different headers.
There is one group of alternatives per rule. A test that compares a field with several values already matches when any value matches, so “from A or B, and with C or D in the subject” fits in matchAll as two tests. Two independent sets of alternatives on different fields, such as “from A or with C in the subject, and to B or with D in the body”, need two rules.
The tests examine the message, its envelope and its classification:
- Addresses:
From,To,Cc,ToOrCcand the envelope recipient (RecipientAddress), compared withis,contains,domainormatches(a wildcard pattern) against up to 64 values of at most 320 bytes each - Text:
Subject,Body,SubjectOrBody,AttachmentName,AttachmentTypeand the detail of a sub-address (RecipientDetail, thetagofuser+tag@), compared withcontains,isormatches - Headers: the value of any header (
Header), or merely its presence (HeaderExists) - Addressing: whether the user is in
To, inCc, in either, the only recipient, or not inTo(SentToMe) - Size:
SizeOverandSizeUnder, in kilobytes - Content and type:
HasAttachment,Importance,Sensitivity,MailingList,PrivateEvent, andMessageTypefor meeting requests, responses and cancellations, non-delivery reports, read receipts, automatic replies and forwards, signed and encrypted messages and voicemail - Spam:
SpamScore, a spam probability of at least a given percentage; a message the spam filter classified as spam has a score of 50 or more - Keywords:
Keyword,AnyKeywordandFlagged, which match keywords set by an earlier rule as well as the keywords and flags a message carries in itsKeywordsandX-Message-Flagheaders - Time:
ReceivedAfterandReceivedBefore, which compare with a date in UTC, andSchedule, which matches during up to 14 weekly time slots, such as working hours - Absence:
IsAway, which matches while the vacation response is in effect, so that a user can forward mail to a colleague during a holiday and not otherwise
Size bounds are strict: SizeOver matches messages larger than the given size, and SizeUnder messages smaller than it. A range is therefore a SizeOver and a SizeUnder test together in matchAll. To exclude a range, place a SizeUnder test with its lower bound and a SizeOver test with its upper bound in matchAny.
Each Schedule test has its own timeZone, as the other date tests compare instants and need none. When a schedule has no timeZone, the account’s time zone at the time the rules were last saved applies.
Actions
Section titled “Actions”The actions object names each action at most once, so a rule has no list of actions to order and no action can be repeated. The actions are the following:
- Keywords:
addKeywordsandremoveKeywordsare sets of keywords in the JMAP spelling. Adding$seenmarks the message as read,$flaggedflags it and$notjunkkeeps it out of the Junk folder, and removing$flaggedclears the flag.clearKeywordsfirst removes the keywords that earlier rules added. A keyword cannot be both added and removed by the same rule. - Importance:
setImportancegives the message a low, normal or high importance. - Forwarding:
redirectsends the message to up to 64addresses, and keeps a copy in the account unlesskeepCopyis turned off. - Answering:
replyanswers the sender with a subject and body, at most once per sender everydaysdays, or to every message whendaysis0. Automatic replies describes when a reply is not sent. - Filing:
copyToandmoveToare sets of up to 16 mailboxes, identified by their ids so that the rule keeps working when a mailbox is renamed. A message moved to several mailboxes is filed into each of them. Trash always has the idband the Junk folder the idc, somoveTowithbdeletes a message andmoveTowithcfiles it as spam, which also adds the$junkkeyword. - Refusing:
discarddrops the message silently, andrejectrefuses it with areason, as described in Rejected messages. - Stopping:
stopProcessingprevents the rules that follow from running on a message the rule applied to.
A rule needs at least one action, and stopProcessing alone counts, so that a rule can shield messages from later rules. The server applies the actions in a fixed order: keywords are cleared, removed and added, the importance is set, then the message is redirected, answered, copied, moved, discarded or rejected, and processing stops last. Because removal comes before addition, a rule that clears or removes keywords and adds others replaces them. A move to the Junk folder is applied after the other moves, because the last move decides which keywords the delivered message carries.
Two actions have restrictions. reject must be the only action of its rule apart from stopProcessing, and the server turns stopProcessing on for it. It may be combined with any conditions. Forwarding sends mail out of the server, so a user may enable forwarding only when allowed to write Sieve scripts, that is with the jmapSieveScriptCreate, jmapSieveScriptUpdate or sievePutScript permission; otherwise the change is refused with Forwarding rules require permission to write Sieve scripts. The number of forwarding addresses is also bounded by the smaller of maxRedirects and maxOutMessages on the SieveUserInterpreter object, and a rule above that limit is refused with The rule forwards to <n> addresses, but the server forwards a message to at most <limit> (maxRedirects and maxOutMessages). Both checks apply only when a change alters what is forwarded: creating a forwarding rule, enabling one, or changing its addresses or keepCopy. A forwarding rule saved before the permission was withdrawn or the limit lowered can still be renamed, moved, disabled or deleted. A forwarded message carries an X-Forwarded-By header that prevents it from being forwarded in a loop, where the interpreter allows that header to be edited.
Example
Section titled “Example”The following x:MailRule/set call creates a rule that files invoices from a partner into a folder, marks them as read and tags them, unless the spam filter classified them as spam, and stops further rules:
[ "x:MailRule/set", { "create": { "r1": { "name": "Partner invoices", "position": 10, "conditions": { "matchAll": { "0": {"@type": "Subject", "operator": "contains", "values": {"invoice": true}} }, "matchAny": { "1": {"@type": "From", "operator": "domain", "values": {"partner.example": true}} }, "matchNone": { "0": {"@type": "SpamScore", "percent": 50} } }, "actions": { "addKeywords": {"$seen": true, "invoices": true}, "moveTo": {"f": true}, "stopProcessing": true } } } }, "0"]Here f stands for the id of the Invoices mailbox. The lists of tests are objects keyed by position, and the sets are objects whose keys are the members.
Saved form
Section titled “Saved form”The server saves every rule in one canonical form, so that two rules that mean the same thing look the same to every client. Keywords are lowercase, with system keywords in their JMAP spelling (\Seen becomes $seen), duplicate members of a set are dropped, the keys of each list are renumbered from 0, and a move to the Junk folder comes last in moveTo. Some tests are saved in a simpler equivalent form; a Header test on Subject, for example, is saved as a Subject test. x:MailRule/get also returns every action the rule does not use, with its default value.
Because a saved rule may differ from what the client sent, the created and updated entries of the x:MailRule/set response contain every property the server changed, as RFC 8620 requires, and the client should apply them to its copy of the rule.
Updates
Section titled “Updates”An update is a JSON patch, as in any JMAP /set call. A path that reaches inside an object changes one field or one member: actions/moveTo/b set to true adds Trash to the moves, actions/redirect/keepCopy changes one setting of the redirect, and conditions/matchAll/1 replaces the second test of matchAll. A path that names a whole object, such as actions, actions/redirect or conditions/matchAny/0, replaces that object entirely, and the fields not sent take their defaults. A member of a set can be removed by any spelling of it: actions/addKeywords/\Seen set to null removes $seen.
Two paths in one update must not overlap. When one path is the prefix of another, such as conditions/matchAll and conditions/matchAll/0, RFC 8620 requires the update to be rejected, and the server answers invalidPatch with A patch path is the prefix of another one. A list index too large to be a position is refused the same way, with A list index is out of range.
Automatic replies
Section titled “Automatic replies”A message can trigger more than one automatic reply: the vacation response, a reply action of a rule, or a vacation action in the user’s own script. Stalwart sends at most one of them for each delivery, the first one that is due, and silently skips the later ones, as RFC 5230 allows a single vacation action per script run. A reply is due when the sender has not received that reply within its period. The managed script places the vacation response before the rules, so while the user is away, a sender who is due the vacation response receives it instead of a matching rule’s reply. When the user’s own script includes the managed script, a vacation action placed before the include comes first in the same way.
Replies are also never sent to spam. The vacation response and every reply action are skipped for a message whose spam score is 50 or more, so that a user’s automatic replies do not confirm addresses to spammers.
A rejection cancels the automatic reply of the same delivery. When a rule or script both replies to a message and rejects it, the reply is withdrawn, whether the rejection is bounced or discarded, as RFC 5230 makes vacation and reject incompatible. Redirects and notifications of the same delivery are still sent. A withdrawn reply is not recorded as sent, so the next message from that sender can receive it.
Rejected messages
Section titled “Rejected messages”A rejection sends a report to the envelope sender of the message. When that address is forged, the report goes to someone who never wrote to the user, which is how rejections turn into backscatter. Stalwart therefore bounces a rejection only when the return path is verified, and otherwise discards the message silently, as RFC 5429 allows when the envelope sender cannot be trusted. This applies at delivery to every rejection: those of mail rules, of the user’s own scripts and of global scripts.
The return path counts as verified in three cases:
- The message was submitted by an authenticated user.
- SPF passed for the
MAIL FROMdomain, and the return path still has that domain after any rewriting by scripts or milters. - The message was sent by a Sieve script of an account on the server, for example a redirect or a notification, with that account as its return path.
An empty return path is never verified, since no report can be sent to it. Because SPF decides most cases, a rejection bounces only where the server checks SPF on MAIL FROM. By default spfFromVerify checks it only on port 25, as described in SPF, so mail that arrives over LMTP, on other ports or through a gateway in front of Stalwart is discarded instead of bounced. The same holds for senders without an SPF record and for mail forwarded by another server that breaks SPF. Deployments that need bounces in those cases must enable SPF verification on MAIL FROM for that traffic, and make sure it can pass. Messages submitted through a contact form are never verified, as their sender is whatever the visitor typed.
A message that another account redirected to the user is not guaranteed to bounce either. Its return path is the forwarding account, and a report reaches that account only when its redirect asked for failure notifications (redirect :notify "failure" in a Sieve script). The original sender never receives it.
Rejections in system scripts, which run during the SMTP session, are not affected: they refuse the message with an SMTP reply, as described in Replies and actions.
Blocked and safe senders
Section titled “Blocked and safe senders”Each account also has two lists of senders, the BlockedSender and SafeSender objects. An entry is an email address, or a domain written as @example.org, which also covers its subdomains. Entries cannot be edited, only added and removed, and each list holds up to 1024 entries.
Mail from a blocked sender is filed into the Junk folder with the $junk keyword, and no rule runs on it. Mail from a safe sender is marked with $notjunk, which overrides the spam filter’s verdict, so the message is not treated as spam. The safe list applies only to senders whose identity is established, by DMARC or by authenticated submission. When a sender is on both lists, the safe list wins.
Managed script
Section titled “Managed script”The managed script is regenerated each time a rule, a sender list entry or the vacation response changes, and it is the only place they are stored. Within it, the sender lists come first, then the vacation response, then the rules in order.
The script is read-only. It can be listed and downloaded over ManageSieve and JMAP, but any attempt to change it is refused with The 'managed' script cannot be modified, use VacationResponse/set or x:MailRule/set instead. over JMAP and with The 'managed' script is read-only, use VacationResponse or x:MailRule instead. when renamed over ManageSieve. The name is reserved: a user script cannot be created or renamed as managed (The 'managed' name is reserved, please use a different name.).
Activation
Section titled “Activation”Only one Sieve script of an account is active at a time, and the managed script must be active, or included by the active script, for rules and the vacation response to run. When a change leaves the managed script with something to do, the server therefore makes it the active script if it is not already in effect. A script the user had active before stops running. It is not deleted, but it is not reactivated when the rules are later removed.
A user who wants a Sieve script of their own and mail rules at the same time includes the managed script from their own script with the include extension (RFC 6609), and keeps their own script active:
require ["include", "fileinto"];
include "managed";
if header :contains "list-id" "<dev.lists.example.org>" { fileinto "Lists/Dev";}The server recognises the include and leaves the user’s script active when rules change. The include must name the script literally, as a personal script: include :global "managed" and names built from variables are not recognised. The include runs the rules at that point of the user’s script, so commands placed before it act before the rules do.
While the managed script is not in effect, the vacation response reports isEnabled as false to JMAP clients, whatever was set, because it would not be sent.
Limits and errors
Section titled “Limits and errors”The managed script is compiled with the limits of the untrusted interpreter, and the rules of an account are saved together, as one script. When the script they produce would exceed a limit, the change is refused whole, whichever protocol made it: JMAP fails every change of the x:MailRule/set call, EWS refuses the whole request, and Outlook over MAPI receives an out of memory error (ecNotEnoughMemory) and saves nothing. A script longer than maxScriptSize is refused with The rules script failed to compile: <error>., where the error reads Sieve script is too large, and one too large for the maxCpuCycles limit with The rules script has <n> instructions, above the limit of <limit> (maxCpuCycles). Other compilation failures, for example when a Sieve extension a rule needs is disabled with disableCapabilities, are refused with The rules script failed to compile: <error>. as well.
Invalid values are refused with invalidProperties and a description that names the problem, among them the following:
Invalid entry <entry>: use an email address or a domain written as @example.org.Invalid schedule: use at most 14 slots per condition, each starting before 24:00 and ending at a different time.A rule that rejects mail cannot have other actions.The rule actions must not be empty., for a rule with no action, not evenstopProcessingThe keyword "<keyword>" cannot be both added and removed.An address value is too long: use at most 320 bytes., for an address test value or a redirect addressThe rule values must not be empty., for an empty test valueThe list cannot have more than 1024 entries., for a full sender listInvalid size <n>: use 1 to 4294967296 kilobytes.Invalid date <timestamp>: use a date between 1970 and 3000.The rule keywords must not be empty.andInvalid keyword "<keyword>".Invalid header name "<name>".
Two clients saving rules at the same moment conflict, and the later one receives Another process modified the mail rules, please try again.
Outlook rules
Section titled “Outlook rules”Outlook and other Exchange clients manage the same rules through their own rule editors, over MAPI over HTTP and EWS. Each Outlook rule is saved as a mail rule: its conditions become matchAll, its exceptions matchNone, “only while out of office” an IsAway test, and “stop processing more rules” stopProcessing; its name, order and enabled state are kept. Outlook’s delete becomes a move to Trash, permanent delete becomes discard with stopProcessing, categories become keywords, and the three kinds of forwarding share the one redirect. A rule edited in Outlook is therefore visible and editable in the WebUI, and the reverse.
The translation follows the rules above, so an Outlook rule behaves slightly differently from the same rule on an Exchange server. Its size limits are strict: “at least 100 KB” matches messages larger than 100 KB. A move to the Junk folder also adds the $junk keyword. Actions are merged by kind and applied in the fixed order, and categories are stored in lowercase. Outlook for Windows receives a rule it saved, and that nobody changed since, exactly as it was saved.
Some Outlook rules have no server-side equivalent, such as rules that run only in the client, deferred delivery, or conditions Stalwart cannot express. Such a rule is kept so that Outlook shows it, but it never runs on the server and does not appear as a mail rule. Conversely, a rule edited in the WebUI or over JMAP into something Outlook cannot express is hidden from Outlook, and the next rule save from Outlook keeps it as a mail rule.
EWS reports these rules as not supported, and also mail rules that hold more than its rule format can show, such as two size ranges. An EWS client can delete such a rule but not change it, not even to rename or disable it: the change fails with UnsupportedRule. Outlook for Windows edits it over MAPI.
Outlook’s junk mail settings maintain the blocked and safe sender lists, and its out of office settings, like those of EWS and ActiveSync clients, edit the vacation response. Outlook for Windows describes the Outlook side.
Permissions
Section titled “Permissions”Users manage their own rules and lists with the sysMailRule*, sysBlockedSender* and sysSafeSender* permissions, which the default user and group roles include, and an OAuth token needs the mail scope for them. Forwarding additionally requires the permission to write Sieve scripts, as described in Actions.