Workflow Team Email Developer Guide - edmozley/freeitsm GitHub Wiki
5.16.0. #502: a workflow's Send an email can go to the members of a team - the ticket's, or one chosen on the action - as one email or a separate email each. The user's view: Workflows ยง Emailing a team (5.16.0).
The whole change is inside one action, send_email in workflow/includes/engine.php. Three new args say whether a team is added and how it is sent; one new function, sendEmailRecipients(), turns the args into a recipient list and a list of batches (one send each); and the send loop now tries every batch, logs each one, and fails the run at the end if anybody missed out. There is no schema change - the args live in the workflow's stored action JSON like every other arg, and an action saved before 5.16.0 has no team_mode, which means "no team".
| File | What |
|---|---|
workflow/includes/engine.php |
availableActions() - the three new send_email args; action_send_email() - recipients, the pre-send try/catch, the per-batch loop; new sendEmailRecipients(), teamMemberEmails(), sendEmailFailureMessage()
|
includes/email_log.php |
Unchanged. emailLogSent() / emailLogFailed() with route 'workflow' (Workflow action) |
includes/ticket_sensitivity.php |
Unchanged. ticketEmailRecipientsAllowed() - the confidential-ticket rule, now handed the whole list |
includes/watchtower_queries.php |
Unchanged. The Workflows tile counts workflow_executions with status = 'failed' - which is why a partial failure must FAIL the run |
lang/en/workflow.php |
actions_row6_does / actions_row6_args - the in-app help's row for Send an email |
tests/workflow-send-email-team.php |
New. 17 checks, including a real send to a refused SMTP port |
In availableActions(), between To and Subject:
'to' => ['type' => 'text', 'label' => 'To (blank = ticket requester, or only the team when one is chosen below)', 'supports_vars' => true],
// GH #502: the members of a team - the ticket's, or one chosen here. Empty =
// no team, which is every action saved before this existed.
'team_mode' => ['type' => 'select', 'label' => 'Also send to a team', 'options' => [
['value' => '', 'label' => 'No team'],
['value' => 'ticket', 'label' => 'The members of the ticket\'s team'],
['value' => 'team', 'label' => 'The members of the team chosen below'],
]],
'team_id' => ['type' => 'lookup', 'label' => 'Team (for "the team chosen below")', 'lookup' => 'team'],
'team_send' => ['type' => 'select', 'label' => 'Send the team', 'options' => [
['value' => '', 'label' => 'One email to everyone'],
['value' => 'each', 'label' => 'A separate email to each person'],
]],-
The empty value is the old behaviour in both selects. Nothing has to be migrated: an old action has neither key, and
(string)($args['team_mode'] ?? '')reads it as No team. -
team_iduses the existingteamlookup (ACTION_ARG_LOOKUPS['team']โticket.assigned_team_id, the same list as Assign ticket to team), so the editor's dropdown needed no new code. - Send the team is a choice, not a fixed rule, because teams genuinely differ: one email keeps replies in one thread and everyone sees who else got it; a copy each keeps the list private.
| To | Also send to a team | Who gets it |
|---|---|---|
| given | No team | those addresses |
| blank | No team | the ticket's requester - as it always was |
| given | a team | those addresses and the team |
| blank | a team | the team only - not the requester |
The last row is the point of the issue: "tell the queue a ticket arrived" is not also an email to the person who raised it.
$teamMode = (string)($args['team_mode'] ?? '');
$teamEmails = [];
if ($teamMode === 'ticket' || $teamMode === 'team') {
$teamEmails = self::teamMemberEmails($conn, $teamMode, $ticketId, (int)self::argInt($args, 'team_id', $payload));
if (!$teamEmails && $to === '') {
return ['skip' => $teamMode === 'ticket'
? 'The ticket has no team, or nobody in it has an email address'
: 'Nobody in the chosen team has an email address'];
}
} else {
$teamMode = '';
}
$recipient = $to !== '' ? $to : ($teamMode !== '' ? '' : $requesterEmail);-
TRAP: an empty team with a blank To is a skip, never a fall-back to the requester. The person who chose a team asked for the team; emailing the requester instead would send a "new ticket for your queue" message to a customer.
action_send_email()returns it as['skipped' => true, 'reason' => ...], so the step's result in the run log says why. - An empty team with a To still sends to the To.
-
Any other
team_mode(a value typed through the API, say) is treated as No team.
Then the To addresses and the team are merged, case-insensitively de-duplicated, and split into batches:
foreach (array_merge(preg_split('/[,;]\s*/', $recipient, -1, PREG_SPLIT_NO_EMPTY) ?: [], $teamEmails) as $a) {
$a = trim($a);
if ($a === '' || isset($seen[strtolower($a)])) continue;
$seen[strtolower($a)] = true;
$list[] = $a;
}
$recipient = implode(', ', $list);
...
$batches = ($teamEmails && ($args['team_send'] ?? '') === 'each')
? (preg_split('/[,;]\s*/', $recipient, -1, PREG_SPLIT_NO_EMPTY) ?: [])
: [$recipient];- The first spelling wins:
Boss@x, sam@xplus a memberboss@xkeepsBoss@x. The To addresses come first, so a typed address is never replaced by the team's spelling. - One email to everyone is a single batch - the whole list, comma-separated.
- A separate email to each person is one batch per address - and that includes the To addresses, not just the members.
- Without a team,
team_sendis ignored and there is always one batch, exactly as before 5.16.0. -
$recipient(the whole list) is also what the confidential check and the ticket's filed copy use, whichever way it was sent.
if ($mode === 'ticket') {
if (!$ticketId) return [];
$s = $conn->prepare('SELECT assigned_team_id FROM tickets WHERE id = ?');
$s->execute([$ticketId]);
$teamId = (int)$s->fetchColumn();
}
if ($teamId <= 0) return [];
$s = $conn->prepare("SELECT DISTINCT a.email FROM analyst_teams at
JOIN analysts a ON a.id = at.analyst_id
WHERE at.team_id = ? AND a.is_active = 1 AND a.email IS NOT NULL AND a.email <> ''
ORDER BY a.email");- Active members with an address only. An inactive analyst (someone who has left) is not emailed, and a member with no address is left out rather than failing the send.
-
ticketreadstickets.assigned_team_idat the moment the action runs - so on A ticket is created, a workflow that assigns the team earlier in the same action list is seen by a later Send an email. -
ticketwith no ticket (a form's workflow sending from a chosen mailbox) is an empty list, which is the skip above when To is blank.
Unchanged, but now handed the whole list:
if ($sensTicket > 0 && !ticketEmailRecipientsAllowed($conn, $sensTicket, $recipient)) {
return ['skipped' => true, 'reason' => TICKET_EMAIL_CONFIDENTIAL_SKIP, 'confidential' => true,
'ticket_id' => $sensTicket];
}ticketEmailRecipientsAllowed() splits on , / ; and allows the send only when every address is the requester or an active analyst. Team members are analysts, so a team on its own always passes.
TRAP: it is all or nothing. A confidential ticket's email to a team plus an outside address in To is skipped whole - the team does not get it either. That is deliberate: the check runs before batching, so a separate copy each does not change the answer.
Before sending. The mailbox and token lookup (chosen mailbox or the ticket's, then Microsoft / Google / IMAP-SMTP) is wrapped so a failure there is logged against everyone it was for, then rethrown:
} catch (Throwable $e) {
foreach ($batches as $batch) {
emailLogFailed($conn, $mailbox, 'workflow', $batch, $subject, $e->getMessage(), $ticketId ?: null);
}
throw $e;
}Before #502 only the send itself reached the email log, so "no failures" in Activity โ Outbound could mean "never got as far as sending". $mailbox can be null here (no mailbox found), which emailLogFailed() accepts.
The send. One attempt per batch; a failure is logged and remembered, and the loop carries on:
$failed = [];
$sentAny = false;
foreach ($batches as $batch) {
try {
if ($provider === MailboxProvider::Imap) {
imapSmtpSend($mailbox, $batch, '', $fullSubject, $fullBody);
} elseif ($provider === MailboxProvider::Google) {
...
gmailSendEmail($accessToken, $batch, $fullSubject, $fullBody, $fromAddress); // splits a list itself
} else {
... templateSendViaGraph($accessToken, $message, $graphBase);
}
} catch (Throwable $e) {
emailLogFailed($conn, $mailbox, 'workflow', $batch, $fullSubject, $e->getMessage(), $ticketId);
$failed[] = ['to' => $batch, 'error' => $e->getMessage()];
continue;
}
emailLogSent($conn, $mailbox, 'workflow', $batch, $fullSubject, $ticketId);
$sentAny = true;
}- TRAP: never stop at the first failure. With A separate email to each person, one bad address (or one refused recipient) must not stop the rest of the team hearing about the ticket.
-
Each batch is its own
email_send_logrow, sent or failed, with the provider's message as the reason - the same pattern as the SLA route. One email to everyone is one row with the whole list into_address.
Microsoft Graph takes one recipient object per address:
'toRecipients' => array_map(fn($a) => ['emailAddress' => ['address' => $a]],
preg_split('/[,;]\s*/', $batch, -1, PREG_SPLIT_NO_EMPTY) ?: [$batch]),Before 5.16.0 the whole To string went in as one address. That only ever worked for a single address; a team in one email would have been a single invalid recipient. Gmail (gmailSendEmail()) and SMTP (imapSmtpSend()) already split a list themselves.
The ticket's copy. Filed once, with the whole list, and only when somebody actually got it:
if ($ticketId && $sentAny) {
templateSaveSentEmail($conn, $ticketId, $mailbox, $recipient, $fullSubject, $body);
}So the ticket's conversation shows one email whichever Send the team was chosen - a copy each does not put ten identical emails on the ticket.
After the loop, any failure throws, so the step and the run are failed:
if ($failed) {
throw new Exception(self::sendEmailFailureMessage($failed, count($batches)));
}public static function sendEmailFailureMessage(array $failed, int $total): string
{
// One send (the usual case): the provider's own words, exactly as before #502.
if ($total <= 1) return (string)($failed[0]['error'] ?? 'Email could not be sent');
$who = array_map(fn($f) => $f['to'] . ' (' . $f['error'] . ')', array_slice($failed, 0, 5));
$more = count($failed) > 5 ? ' and ' . (count($failed) - 5) . ' more' : '';
$rest = count($failed) < $total ? ' - the others were sent' : '';
return 'Email not sent to ' . count($failed) . ' of ' . $total . ': ' . implode('; ', $who) . $more
. $rest . '. See Activity โ Outbound on the mailbox in Tickets โ Settings โ Mailboxes.';
}- A single send keeps the provider's own words, so every Send an email that worked as before 5.16.0 reports a failure exactly as it did.
- Several sends name up to five who missed out with their reasons, then and N more; the others were sent only when somebody did get it.
-
TRAP: a partial failure must FAIL the run, not just log. A failing workflow is otherwise silent by design (the engine never lets a rule break the save that fired it). The failed run is what puts it in the workflow's run history and on the Workflows tile of Watchtower (
includes/watchtower_queries.phpcounts real runs withstatus = 'failed'in the last 24 hours and names the worst workflows). A "success" with failures only in the email log would be found by nobody. - As with any failed action,
executeActionList()stops the chain there - later actions in the same workflow do not run.
| Test | Checks |
|---|---|
tests/workflow-send-email-team.php |
17. Recipients, against a ZZ team of four (one inactive, one with no address) made and deleted by the test: no team (requester / To), a chosen team with a blank To (active members with an address, not the requester), one batch by default, one per person with each, To plus team de-duplicated case-insensitively, the ticket's team (one existing ticket's team borrowed and put back), a ticket with no team skipped, a To still sent. Then a real send through a ZZ IMAP mailbox whose SMTP server is 127.0.0.1:1, which refuses every connection: with each the run is failed, both people are tried and each has its own failed log row with a reason, and the message names both without claiming the others were sent; with one email, one failed row for the whole list; with the mailbox switched to Google and no token, a failed row for every person before sending. Plus the two message shapes (some sent; a single send keeps the provider's words) |
Run it against a test database: FREEITSM_TEST_DATABASE=<test db> php tests/workflow-send-email-team.php. It cleans up its ZZ mailbox, log rows, executions, analysts and team in finally.
- Workflows ยง Emailing a team (5.16.0) - the user's view
-
Email send log - Developer Guide -
email_send_log, the routes and Activity โ Outbound - Workflow engine - Developer Guide - how actions run and how a run is marked failed
- Notifications - every team member already gets a bell notification when a ticket lands in their queue, without any workflow