Email Template Sender Rules Developer Guide - edmozley/freeitsm GitHub Wiki
Email template sender rules — Developer Guide
How a template is chosen for a recipient, why specificity replaced ordering, and the three places that record the consequence.
The user-facing page is Limiting automatic replies to particular senders.
1. 📁 The files involved
| File | Role | |
|---|---|---|
| ⚙️ | includes/template_email.php |
templateSelectForRecipient() — the only place specificity is decided. templateRulesByTemplate(), and getActiveTemplate() kept as a thin wrapper |
| 📋 | includes/email_log.php |
emailLogSkipped() — the deliberate non-send |
| 🔌 | api/tickets/save_email_template.php |
Validates rules before any write |
| 🔌 | api/tickets/get_email_templates.php |
Attaches rules to every template |
| 🔌 | api/tickets/delete_email_template.php |
Removes the rules too |
| 🔌 | api/tickets/simulate_email_template.php |
The simulator — calls the matcher, implements nothing |
| 🖥️ | tickets/settings/index.php |
Scope editor, scope column, no-catch-all warning, simulator |
| 🗄️ | ticket_email_template_rules |
template_id, match_type, match_value |
| 🌍 | lang/en/tickets.php |
settings.scope.* |
2. ⚠️ What it was before, which matters
SELECT * FROM ticket_email_templates
WHERE event_trigger = ? AND is_active = 1
ORDER BY display_order ASC, id ASC
LIMIT 1
LIMIT 1. Exactly one template per event has ever been sent — whichever sorted first — and every other template for that event was silently ignored. display_order looked like a display preference and was in fact the entire selection algorithm.
That is worth knowing before you conclude the new design added a risk. It replaced an invisible one.
3. 🔑 Specificity, not order
templateSelectForRecipient($conn, $eventTrigger, $recipientEmail)
→ ['template' => ?array, 'reason' => string, 'matched' => ?array]
Resolution, most specific first:
reason |
Wins when |
|---|---|
address |
a rule names this exact address |
domain |
a rule names this domain |
everyone |
a template has no rules at all |
no_match |
templates exist, all restricted, none matched |
no_active_template |
nothing active for this event |
The alternative — evaluate top to bottom, first match wins — requires the administrator to get the rules right and the ordering right, and gives no sign when the second is wrong. Here dragging rows cannot change what is sent. display_order survives only as a tie-break between two rules of equal specificity.
No rules means EVERYONE, not nobody
The permissive case is the empty case. Three consequences, all deliberate:
- a template nobody has restricted behaves exactly as it did before this feature existed;
- a new template starts unrestricted, so an install always has a catch-all unless one is deliberately removed;
templateRulesByTemplate()returns[]when the table is missing, so a part-upgraded install sends exactly as before rather than falling silent.
Invert any of those and "forgot to add a rule" starts meaning "nobody gets an email".
The reason string is not decoration
It is what the simulator displays and what the send log records. Selection that could only answer which template would leave "why did nobody get a reply?" unanswerable twelve months later.
4. 🔀 Order of operations changed in sendTemplateEmail()
// merge data FIRST — the template now depends on who the email is going to
$mergeData = buildTicketMergeData($conn, $ticketId);
$choice = templateSelectForRecipient($conn, $eventTrigger, $mergeData['requester_email'] ?? '');
It used to select the template and then build the merge data. Anything added to this function must not reintroduce that order.
5. 📋 The non-send is logged, and that is the point
emailLogSkipped($conn, templateGetMailboxForTicket($conn, $ticketId), 'template',
$recipient, $subject, $reason, $ticketId);
Three decisions inside those five arguments:
- Only
no_matchis logged, neverno_active_template. Nobody configured a template, so nobody is expecting an email; a row there would be noise on every install that never wanted the feature. - The mailbox is resolved even though nothing is sent. Logged against no mailbox it lands in the "sends with no mailbox" bucket, which is not where somebody asking "why did this mailbox not reply?" will look. One extra query, only on the path that sends nothing.
statusis'skipped', a third value in aVARCHAR(10)column — no schema change.
⚠️ The renderer had two states and defaulted to the wrong one
const failed = e.status === 'failed';
...
${failed ? 'Failed' : 'Sent'}
A skipped row would have rendered as Sent — a confident wrong answer in the one place somebody goes looking, which is worse than no answer. Any new status must be added to that ternary and to the in_array() whitelist in get_mailbox_outbound.php, or it becomes invisible, mislabelled, or both.
6. 🔌 Saving rules
Validate everything before writing anything. There is no transaction here:
$cleanRules = null; // absent key = leave rules alone
if (array_key_exists('rules', $data) && is_array($data['rules'])) {
$cleanRules = []; // empty array = applies to everyone
... throw on anything invalid ...
}
$conn = connectToDatabase();
// everything from here either writes or cannot throw
Found by testing the rejection path: an invalid rule used to be rejected after the template UPDATE, leaving the template saved while the caller was told the save failed.
Two more:
- Absent
rules≠ emptyrules. Collapsing them would let any older client that posts no rules silently unrestrict every template it saves. - A domain with no dot, or an
@still in it, is refused rather than stored. A rule that can never match looks exactly like a working rule on screen and quietly does nothing — precisely the fault this feature exists to avoid.
Rules are replaced wholesale rather than diffed. The set is tiny, and a diff is where "removed a rule that stayed anyway" comes from — which here means somebody keeps receiving an email the admin believes they stopped.
delete_email_template.php deletes the rules first: there is no foreign key, and an AUTO_INCREMENT id can be reissued after a restart, which would attach a deleted template's rules to a new one.
7. 🖥️ The front end
- The simulator posts to the server. It must never re-implement matching in the browser — an answer that can disagree with reality is worse than none.
- The warning is gated on
baseUrlState.loaded. Until the settings have actually been read we do not know whether it was dismissed, and guessing "not dismissed" nags somebody who already said they know. - The warning is per event, because a gap in one event says nothing about the others, and it only fires when templates for that event exist and none is unrestricted.
8. ✅ How this was verified
| Check | Result |
|---|---|
Restricted template at display_order 5, catch-all at 0 |
Restricted one wins — order is genuinely not consulted |
[email protected] with both an address and a domain rule |
reason: address |
[email protected] |
Same match — folded to lower case |
| Catch-all deactivated, unknown sender | reason: no_match |
| The real send path, no template matching | One skipped row, with the reason, against the ticket |
| Rules round-tripped through the API | Deduped, lower-cased, @ stripped |
| Invalid domain posted with a changed template name | Refused and the name confirmed unchanged |
9. Extending it
A new match type (a company, a group) needs: a match_type value, a branch in templateSelectForRecipient() placed at the right specificity level, validation in save_email_template.php, and a chip in the editor. Company was considered and parked — it needs the requester resolved to a company before the reply is chosen, and templates are currently install-wide with no tenant_id.
See also
- Limiting automatic replies to particular senders — the user page
- The public web address —
[ticket_url], from the same discussion - Email send log — Developer Guide — where
skippedis displayed - Canned Responses — Developer Guide — the shared merge-code vocabulary