Mail review stage 2: the mail queue sends at most config_mail_send_per_minute a minute (database 4.2.9, Admin > Settings > Mail, Sending) over one connection with bulk email last, retries over about eight hours on a growing wait, stops for the minute when the server turns two away in a row, costs no email a try when the server can't be reached, doesn't retry an address turned away for good and marks its contact Email bounced, sends an email once when only someone copied in is turned away, tells admins once an hour at most instead of every agent per email, and gives each email a plain text part and ITFlow's own host name; 26.12.3 changelog

This commit is contained in:
johnnyq
2026-11-30 16:50:04 -05:00
parent a9e5bc66db
commit 899f2259fe
12 changed files with 488 additions and 320 deletions

View File

@@ -6,7 +6,7 @@ This file documents all notable changes made to ITFlow.
### Upgrading to 26.12.3
Update from Maintenance > Update as usual - this release has seven database changes: 4.2.2 adds a table for passkeys and a setting to turn them on or off, 4.2.3 lets a document keep the Markdown it was written in, 4.2.4 lets a ticket keep its pictures as files, 4.2.5 adds identity providers, 4.2.6 keeps each ticket's email conversation together, 4.2.7 lets a reply from a CC say who sent it, and 4.2.8 renames the watchers table for CCs. The client portal's Microsoft 365 single sign-on becomes the first identity provider, for client contacts, and keeps its redirect address, so nothing changes in Microsoft Entra. Nothing else is required: passkeys are on, and no one has one until they add it. Pictures already inside tickets move to files in the background afterwards - the new Ticket Pictures job in Maintenance > Cron does a batch a minute, so an install with years of emailed screenshots may take a while, and tickets work as usual meanwhile. A passkey is made for your ITFlow's address (the one in config.php) and only works there, over HTTPS - if you move ITFlow to a new address, everyone adds theirs again. Watchers are called CCs now. Emails about a ticket go to its contact with the CCs copied in, rather than one each - Admin > Settings > Tickets has the switch, under Emails about a ticket.
Update from Maintenance > Update as usual - this release has eight database changes: 4.2.2 adds a table for passkeys and a setting to turn them on or off, 4.2.3 lets a document keep the Markdown it was written in, 4.2.4 lets a ticket keep its pictures as files, 4.2.5 adds identity providers, 4.2.6 keeps each ticket's email conversation together, 4.2.7 lets a reply from a CC say who sent it, 4.2.8 renames the watchers table for CCs, and 4.2.9 lets the mail queue go at a pace your mail host takes. The client portal's Microsoft 365 single sign-on becomes the first identity provider, for client contacts, and keeps its redirect address, so nothing changes in Microsoft Entra. Nothing else is required: passkeys are on, and no one has one until they add it. Pictures already inside tickets move to files in the background afterwards - the new Ticket Pictures job in Maintenance > Cron does a batch a minute, so an install with years of emailed screenshots may take a while, and tickets work as usual meanwhile. A passkey is made for your ITFlow's address (the one in config.php) and only works there, over HTTPS - if you move ITFlow to a new address, everyone adds theirs again. Watchers are called CCs now. Emails about a ticket go to its contact with the CCs copied in, rather than one each - Admin > Settings > Tickets has the switch, under Emails about a ticket.
### New Features & Updates
@@ -62,6 +62,8 @@ Update from Maintenance > Update as usual - this release has seven database chan
- Email sent by a system, a mailing list or a newsletter still makes tickets - alerts emailed in keep working - but is never answered: no "we have your email", no "that ticket is closed". ITFlow's own automatic emails say they are automatic, so the other side's out-of-office doesn't answer them, and no one address gets more than five of them an hour - so two systems can't keep answering each other.
- Two people at a client raising the same problem in the same week - "Printer not working" - get a ticket each, linked as related, rather than the second email landing on the first person's ticket. It's still a reply on the ticket from its contact or a CC.
- A reply to a closed ticket is kept on it as an internal note instead of left in the mailbox, and the notice says so. The ticket isn't reopened. The client or CC is told it is closed, as before - but not someone with no part in the ticket, who learned nothing from a number they guessed.
- Mail queue: email goes out at a pace your mail host takes - 30 a minute to start, set under Pace in Admin > Settings > Mail, Sending - over one connection, ticket emails first and email from the contacts or clients list last. A host's limit doesn't lose email any more: the rest wait their turn. A failed email is tried again over about eight hours, sooner at first. An address the mail server turns away for good isn't tried again, and its contact shows Email bounced. A mail server ITFlow can't reach or sign in to costs no email a try - it waits, and goes once it can. Admins hear about the queue once an hour at most, where every agent got a notice for each failed email.
- Every email has a plain text part beside its HTML, and names the machine sending it by ITFlow's own address rather than the server's own name ("vm", say) - both counted against an email with spam filters.
### Bug Fixes
@@ -83,6 +85,7 @@ Update from Maintenance > Update as usual - this release has seven database chan
- Ticket emails: a ticket with a subject over about 245 characters - an emailed-in monitoring alert, say - had none of its emails sent. An agent's reply was saved and the page then showed an error; an emailed-in one was made a ticket, but nobody was told and the email was left flagged in the mailbox. A subject too long for an email is cut to fit now, and an email that can't be queued is logged (App Logs, Mail) without stopping the page or the mailbox - the reply shows it wasn't emailed.
- Files with an email: they're taken by the same list as files you attach yourself, so a client's .pptx, .msg, .odt, .mov or .mp4 is added to the ticket rather than left out - and iPhone photos (.heic), scans (.tif), forwarded emails (.eml), .xlsm, .ppt, .rtf and .log files can now be attached anywhere tickets take files. A file that still isn't added - another kind, or over 15 MB - is named in an internal note on the ticket, where it used to be in the audit log alone.
- Email-to-ticket: a name with an apostrophe got a stray backslash - a contact made from an email at a client's domain was saved as O\'Brien, and the "Email from" line of an emailed ticket showed it the same way. A new contact's name is cut to fit, too, where a very long one left the email flagged in the mailbox.
- Mail queue: an email whose To address went but one of the people copied in was turned away was sent to everyone again, up to three more times. It goes once now, and says who was turned away.
### Developer Updates
@@ -133,6 +136,7 @@ Update from Maintenance > Update as usual - this release has seven database chan
- The ticket email parser waits while a database update is pending, rather than flag email it can't take - a flagged email is left in the mailbox for good.
- API ticket CCs: api/v1/ticket_ccs/ has read.php (ticket_id or ticket_cc_id), create.php (ticket_cc_email - one address, or several as a list or separated by commas - and ticket_cc_notify) and delete.php (ticket_cc_id, or ticket_id and ticket_cc_email), each finding the ticket through ticket_cc_find.php, and is mapped to module_support in enforce_api_rbac.php. Its delete.php needs Modify, as the ticket page does, through the new $resource_operation_level, which sets one resource's file apart from $operation_level. A closed ticket's CCs aren't changed. tickets/create.php takes ticket_ccs and answers with those added, and tickets/read.php attaches each ticket's ticket_ccs (ticketCcsApiAttach(), when $api_ticket_ccs is set for read_output.php). ticketCcEmailsValid() is ticketCcEmails() naming the first entry that isn't an email address, for the API to refuse.
- Mail review stage 1: emailQueue() cuts the subject and the recipient's and sender's names to the queue's 255 characters (emailFit(), functions/email.php) and queues each email on its own; addToMailQueue() (functions/app.php) catches an insert the database turns away, logs it to App Logs (Mail) and returns how many went in, so emailQueue() answers with only those queued and a ticket reply's Emailed state is right - the email preview's send too. cron/ticket_email_parser.php takes TICKET_ATTACHMENT_EXTENSIONS (functions/files.php) in place of its own list; the list gains heic, heif, tif, tiff, eml, xlsm, ppt, rtf and log, and ticketAttachmentAccept() gives every file field's accept from it (the reply box, New Ticket, the portal's two, canned responses). Files not added - a kind it doesn't take (ticketMailFileTypeWhy()) or over $max_attachment_bytes - go in an internal note (ticketMailFilesLeftOut(), functions/ticket_mail_thread.php) through addTicket()'s new $dropped and addReply()'s email dropped. addReply() makes the copied-in CCs (ticketMailCopiedCcs()) only when the email is threaded. addTicket() takes its SQL-escaped name and address back to raw and escapes each once for HTML and SQL; the domain-match contact is inserted as escaped once, its name cut to 200 characters.
- Mail review stage 2: cron/mail_queue.php sends what is due - waiting, and failed ones whose wait is over - in one query, at most mailQueuePerMinute() a run (settings.config_mail_send_per_minute, database 4.2.9), ORDER BY email_bulk (4.2.9, emailQueue()'s bulk, set by emailBulkSend()), over one PHPMailer kept open (SMTPKeepAlive, mailQueueMailer()). MailQueueSmtp keeps each refused recipient's code: everyone refused for good (5xx) - email_attempts 99 and contactBounceMark(); some refused - sent, and they're named in email_error; refused for now (4xx) - tried again. A connection or sign-in failure (MailQueueUnreachable) puts the email back as it was and ends the run with cronJobStop(..., 1); two failures in a row end it for the minute. MAIL_QUEUE_RETRY_MINUTES gives way to MAIL_QUEUE_RETRY_AFTER - 5, 10, 20, 40, 60, 120 and 240 minutes (mailQueueRetryMinutes(), mailQueueRetryDueSql()) - and MAIL_QUEUE_TRIES is 8. Each failed email's appNotify() to every agent gives way to one mailQueueNotifyAdmins() for the run, an hour apart at most. PHPMailer's Hostname is mailQueueHostname(), its AltBody mailQueueTextPart(). sendQueueEmail() takes the run's mailer and answers with who the mail server took and turned away.
## [26.12.2]

View File

@@ -0,0 +1,28 @@
<?php
/*
* ITFlow - Database update to version 4.2.9 (from 4.2.8)
* Included by admin/database_updates.php - do not access directly
*
* The mail queue goes at a pace the mail host takes, and ticket email goes before bulk email:
* settings.config_mail_send_per_minute - the most emails sent a minute (Admin > Settings > Mail,
* Sending), 30 to start - what Microsoft 365 takes from one mailbox
* email_queue.email_bulk - 1 for an email from the contacts or clients list (Email), which waits
* behind everything else
*
* Re-runnable: each column is added only where it isn't there.
*/
defined('FROM_DB_UPDATER') || die("Direct file access is not allowed");
$itflow_pace_columns = [
['settings', 'config_mail_send_per_minute', "int(11) NOT NULL DEFAULT 30 AFTER `config_smtp_password`"],
['email_queue', 'email_bulk', "tinyint(1) NOT NULL DEFAULT 0 AFTER `email_sensitive`"],
];
foreach ($itflow_pace_columns as [$itflow_table, $itflow_column, $itflow_definition]) {
$itflow_column_exists = mysqli_query($mysqli, "SELECT 1 FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = '$itflow_table' AND COLUMN_NAME = '$itflow_column' LIMIT 1");
if (!$itflow_column_exists || mysqli_num_rows($itflow_column_exists) === 0) {
mysqli_query($mysqli, "ALTER TABLE `$itflow_table` ADD `$itflow_column` $itflow_definition");
}
}

View File

@@ -34,6 +34,19 @@ if (isset($_POST['edit_mail_smtp_settings']) || isset($_POST['edit_mail_imap_set
}, ['provider', 'host', 'port', 'encryption', 'username', 'password']));
[$after, $errors] = settingsMailServerCheck($server, $before, $_POST);
// Sending's pace - how many emails go out a minute (database 4.2.9, functions/mail_queue.php)
if ($server === 'smtp' && mailQueuePaceReady() && isset($_POST['config_mail_send_per_minute'])) {
$before += settingsCurrent(['config_mail_send_per_minute']);
$after['config_mail_send_per_minute'] = $before['config_mail_send_per_minute'];
$per_minute = trim((string) $_POST['config_mail_send_per_minute']);
if (!ctype_digit($per_minute) || intval($per_minute) < 1 || intval($per_minute) > 1000) {
$errors['config_mail_send_per_minute'] = 'A number from 1 to 1000.';
} else {
$after['config_mail_send_per_minute'] = intval($per_minute);
}
}
if ($errors) {
settingsRefuse('mail', $errors, $mail_tab_redirect);
}

View File

@@ -73,7 +73,7 @@ if ($config_login_key_required && trim((string) $config_login_key_secret) === ''
$mail_queue = mailQueueSummary();
if ($mail_queue['failed_day']) {
$attention[] = ['danger', 'fa-envelope-open-text', $mail_queue['failed_day'] . ' email' . ($mail_queue['failed_day'] === 1 ? '' : 's') . ' failed to send',
'In the last day - ITFlow tried ' . MAIL_QUEUE_TRIES . ' times and gave up. The Mail Queue says why, and can try again.', 'mail_queue.php?show=failed', 'See why'];
'In the last day - out of tries, or turned away for good by the mail server. The Mail Queue says why, and can try again.', 'mail_queue.php?show=failed', 'See why'];
}
$mail_queue_health = mailQueueHealth();
if (!empty($config_smtp_provider) && in_array($mail_queue_health['key'], ['cron_off', 'cron_stopped', 'job_off', 'slow'], true)) {

View File

@@ -213,6 +213,14 @@ if (!$config_module_enable_ticketing) {
<?= $oauth_pointer('smtp') ?>
<?= settingsSectionEnd() ?>
<?php if (mailQueuePaceReady()) { ?>
<?= settingsSectionStart('sending-pace', 'Pace', 'How many emails go out a minute, at most. The rest wait their turn - ticket emails first, email to many from the contacts or clients list last - so a mail host\'s limit doesn\'t turn them away.') ?>
<?= settingsInput('config_mail_send_per_minute', mailQueuePerMinute(), ['icon' => 'fa-tachometer-alt', 'type' => 'number', 'label' => 'Emails a minute', 'required' => true,
'min' => 1, 'max' => 1000, 'inputmode' => 'numeric', 'placeholder' => '30',
'help' => 'Microsoft 365 takes 30 a minute from a mailbox. Raise it only if your mail host takes more.']) ?>
<?= settingsSectionEnd() ?>
<?php } ?>
<?= settingsSaveBar('edit_mail_smtp_settings') ?>
</form>
</div>

View File

@@ -26,6 +26,7 @@ require_once "../libs/PHPMailer/src/OAuth.php";
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\OAuthTokenProvider;
use PHPMailer\PHPMailer\SMTP;
if (!defined('GOOGLE_OAUTH_TOKEN_URL')) {
define('GOOGLE_OAUTH_TOKEN_URL', 'https://oauth2.googleapis.com/token');
@@ -200,30 +201,121 @@ function resolveMailOauthAccessToken(string $provider, string $oauth_client_id,
return $tokens['access_token'];
}
function sendQueueEmail(
string $provider,
string $host,
int $port,
string $encryption,
string $username,
string $password,
string $from_email,
string $from_name,
string $to_email,
string $to_name,
string $subject,
string $html_body,
string $ics_str,
string $attachments_json,
string $oauth_client_id,
string $oauth_client_secret,
string $oauth_tenant_id,
string $oauth_refresh_token,
string $oauth_access_token,
string $oauth_access_token_expires_at,
string $cc_json = '',
string $headers_json = ''
) {
/** =======================================================================
* The SMTP conversation, keeping why the mail server turned each recipient away - PHPMailer keeps the
* words alone, without the code that says whether it is for good (5xx) or for now (4xx)
* ======================================================================= */
class MailQueueSmtp extends SMTP {
public array $refused = [];
public function recipient($address, $dsn = '') {
$accepted = parent::recipient($address, $dsn);
if (!$accepted) {
$error = $this->getError();
$this->refused[strtolower(trim((string) $address))] = ['code' => (string) ($error['smtp_code'] ?? ''), 'detail' => trim(trim((string) ($error['smtp_code_ex'] ?? '')) . ' ' . trim((string) ($error['detail'] ?? '')))];
}
return $accepted;
}
}
/** A mail server that can't be reached or signed in to - nothing about any one email, so it costs none a try. */
class MailQueueUnreachable extends \RuntimeException {}
/*
* The mailer for this run - one connection to the mail server, kept open from email to email
* (SMTPKeepAlive), where each used to open its own; or, for Microsoft 365 with Mail.Send, a Graph token.
* ['mail' => PHPMailer, 'graph' => token or null]. Throws MailQueueUnreachable when it can't sign in.
*/
function mailQueueMailer(string $provider, string $host, int $port, string $encryption, string $username, string $password, string $system_from,
string $oauth_client_id, string $oauth_client_secret, string $oauth_tenant_id, string $oauth_refresh_token, string $oauth_access_token, string $oauth_access_token_expires_at): array {
// Google and Microsoft each expose exactly one XOAUTH2 SMTP endpoint, so the stored host/port/encryption are overridden rather
// than used as a fallback - an install that moved from Standard SMTP to OAuth still has the old server saved, hidden on the page
if ($provider === 'google_oauth') {
$host = 'smtp.gmail.com';
$port = 587;
$encryption = 'tls';
} elseif ($provider === 'microsoft_oauth') {
$host = 'smtp.office365.com';
$port = 587;
$encryption = 'tls';
}
$mail = new PHPMailer(true);
$mail->setSMTPInstance(new MailQueueSmtp());
$mail->CharSet = "UTF-8";
$mail->SMTPDebug = 0;
$mail->isSMTP();
$mail->Host = $host;
$mail->Port = $port;
// Bound the SMTP conversation - an unresponsive mail server held the cron lock open and stalled the queue
$mail->Timeout = 30;
$mail->SMTPKeepAlive = true;
// This machine's name to the mail server, and in a Message-ID of PHPMailer's - ITFlow's address, not "vm" (mailQueueHostname())
$mail->Hostname = mailQueueHostname($system_from);
$enc = strtolower($encryption);
if ($enc === '' || $enc === 'none') {
$mail->SMTPAutoTLS = false;
$mail->SMTPSecure = false;
$mail->SMTPOptions = ['ssl' => ['verify_peer' => false, 'verify_peer_name' => false]];
} else {
$mail->SMTPSecure = $enc; // 'tls' | 'ssl'
}
// Microsoft 365 sends through Microsoft Graph when the app has Mail.Send - no SMTP sign-in then (functions/mail_graph.php)
try {
$graph_token = $provider === 'microsoft_oauth' ? mailGraphToken('Mail.Send') : null;
} catch (\Throwable $e) {
throw new MailQueueUnreachable($e->getMessage());
}
if ($graph_token !== null) {
return ['mail' => $mail, 'graph' => $graph_token];
}
if ($provider === 'google_oauth' || $provider === 'microsoft_oauth') {
$username = $username !== '' ? $username : $system_from;
$mail->SMTPAuth = true;
$mail->AuthType = 'XOAUTH2';
$mail->Username = $username;
$access_token = resolveMailOauthAccessToken($provider, trim($oauth_client_id), trim($oauth_client_secret), trim($oauth_tenant_id), trim($oauth_refresh_token),
trim($oauth_access_token), trim($oauth_access_token_expires_at));
if (empty($access_token)) {
throw new MailQueueUnreachable("Missing OAuth access token for XOAUTH2 SMTP - connect the mailbox again in Admin > Settings > Mail.");
}
$mail->setOAuth(new StaticTokenProvider($username, $access_token));
} else {
$mail->SMTPAuth = $username !== '';
$mail->Username = $username;
$mail->Password = $password;
}
return ['mail' => $mail, 'graph' => null];
}
/** Connected and signed in, or MailQueueUnreachable with the mail server's reason - before an email, so a lost connection is opened again. */
function mailQueueConnect(array $mailer): void {
if ($mailer['graph'] !== null) {
return;
}
try {
if (!$mailer['mail']->smtpConnect()) {
throw new MailQueueUnreachable('Couldn\'t connect to the mail server');
}
} catch (MailQueueUnreachable $e) {
throw $e;
} catch (\Throwable $e) {
$smtp = $mailer['mail']->getSMTPInstance()->getError();
$detail = trim(preg_replace('/\s+/', ' ', trim(($smtp['smtp_code'] ?? '') . ' ' . ($smtp['detail'] ?? ''))));
throw new MailQueueUnreachable($e->getMessage() . ($detail !== '' && strpos($e->getMessage(), $detail) === false ? " The mail server said: $detail" : ''));
}
}
/*
* Send one email over the run's mailer. Who it went to: ['accepted' => addresses the mail server took,
* 'refused' => [address => [code, detail]] it turned away]. Throws for anything else that stopped it.
*/
function sendQueueEmail(array $mailer, string $from_email, string $from_name, string $to_email, string $to_name, string $subject, string $html_body,
string $ics_str, string $attachments_json, string $cc_json = '', string $headers_json = ''): array {
/** @var PHPMailer $mail */
$mail = $mailer['mail'];
// The people copied in, and the headers that keep a ticket's conversation together (functions/mail_queue.php)
$cc = mailQueueCc($cc_json);
$headers = mailQueueHeaders($headers_json);
@@ -236,80 +328,19 @@ function sendQueueEmail(
$cc = [];
}
// Google and Microsoft each expose exactly one XOAUTH2 SMTP endpoint, so the
// stored host/port/encryption are overridden rather than used as a fallback -
// the same thing cron/ticket_email_parser.php already does on the IMAP side.
//
// These used to apply only when the columns were blank, which quietly broke
// every install that moved from Standard SMTP to OAuth: the old server is
// still sitting in config_smtp_host/port/encryption, the settings page hides
// those fields for OAuth providers so there is no way to clear them, and the
// send then pointed an M365 bearer token at the previous mail host. Only a
// fresh install, where the columns happened to be empty, ever worked.
if ($provider === 'google_oauth') {
$host = 'smtp.gmail.com';
$port = 587;
$encryption = 'tls';
if (!$username) $username = $from_email;
} elseif ($provider === 'microsoft_oauth') {
$host = 'smtp.office365.com';
$port = 587;
$encryption = 'tls';
if (!$username) $username = $from_email;
// What the last email left - the mailer goes from one to the next
$mail->clearAllRecipients();
$mail->clearAttachments();
$mail->clearCustomHeaders();
$mail->clearReplyTos();
$mail->Ical = '';
$mail->AltBody = '';
$mail->MessageID = '';
$smtp = $mail->getSMTPInstance();
if ($smtp instanceof MailQueueSmtp) {
$smtp->refused = [];
}
$mail = new PHPMailer(true);
$mail->CharSet = "UTF-8";
$mail->SMTPDebug = 0;
$mail->isSMTP();
$mail->Host = $host;
$mail->Port = $port;
// Bound the SMTP conversation. Without this an unresponsive mail server can
// hold the cron lock open indefinitely and stall the whole queue.
$mail->Timeout = 30;
$enc = strtolower($encryption);
if ($enc === '' || $enc === 'none') {
$mail->SMTPAutoTLS = false;
$mail->SMTPSecure = false;
$mail->SMTPOptions = ['ssl' => ['verify_peer' => false, 'verify_peer_name' => false]];
} else {
$mail->SMTPSecure = $enc; // 'tls' | 'ssl'
}
// Microsoft 365 sends through Microsoft Graph when the app has Mail.Send - no SMTP sign-in then
// (functions/mail_graph.php). Microsoft refusing Graph stops this email with its reason.
$graph_token = $provider === 'microsoft_oauth' ? mailGraphToken('Mail.Send') : null;
if ($graph_token === null && ($provider === 'google_oauth' || $provider === 'microsoft_oauth')) {
// XOAUTH2
$mail->SMTPAuth = true;
$mail->AuthType = 'XOAUTH2';
$mail->Username = $username;
$access_token = resolveMailOauthAccessToken(
$provider,
trim($oauth_client_id),
trim($oauth_client_secret),
trim($oauth_tenant_id),
trim($oauth_refresh_token),
trim($oauth_access_token),
trim($oauth_access_token_expires_at)
);
if (empty($access_token)) {
throw new Exception("Missing OAuth access token for XOAUTH2 SMTP.");
}
$mail->setOAuth(new StaticTokenProvider($username, $access_token));
} else {
// Standard SMTP (with or without auth)
$mail->SMTPAuth = !empty($username);
$mail->Username = $username ?: '';
$mail->Password = $password ?: '';
}
// Recipients & content
$mail->setFrom($from_email, $from_name);
$mail->addAddress($to_email, $to_name);
foreach ($cc as $person) {
@@ -318,6 +349,8 @@ function sendQueueEmail(
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->Body = $html_body;
// A plain text part beside it (mailQueueTextPart())
$mail->AltBody = mailQueueTextPart($html_body);
// Its own Message-ID, and the emails it answers - a mail program keeps a ticket's emails together by them, and a
// reply names them back, so the email parser finds its ticket whatever its subject says. A big email sent through
@@ -330,47 +363,36 @@ function sendQueueEmail(
}
}
// A meeting invitation or cancellation goes in as its own text/calendar part
// beside the HTML - the way calendar apps send them, and the only way Outlook
// shows one as a meeting rather than a file. Only a meeting does: one with an
// organiser and attendees (an event's invitation). Microsoft 365 turns that part
// into a meeting as it takes the email, and refuses one with nobody in it -
// "data not accepted" - so a calendar file without them (a ticket's booking and
// its cancellation) is attached like a published event to add. PHPMailer only
// builds the part when there are no file attachments or pictures in the
// message either, so those also travel as an attached invite.ics.
// A meeting invitation or cancellation goes in as its own text/calendar part beside the HTML - the way calendar
// apps send them, and the only way Outlook shows one as a meeting rather than a file. Only a meeting does: one with
// an organiser and attendees (an event's invitation). Microsoft 365 turns that part into a meeting as it takes the
// email, and refuses one with nobody in it - "data not accepted" - so a calendar file without them (a ticket's
// booking and its cancellation) is attached like a published event to add. PHPMailer only builds the part when
// there are no file attachments or pictures in the message either, so those also travel as an attached invite.ics.
if (!empty($ics_str)) {
$meeting = preg_match('/^METHOD:(REQUEST|CANCEL)\r?$/m', $ics_str) && preg_match('/^ORGANIZER[;:]/m', $ics_str) && preg_match('/^ATTENDEE[;:]/m', $ics_str);
if ($meeting && empty($attachments_json)) {
$mail->Ical = $ics_str;
$mail->AltBody = $mail->html2text($html_body);
} else {
$mail->addStringAttachment($ics_str, 'invite.ics', 'base64', 'text/calendar');
}
}
// File attachments arrive as a manifest of app-root-relative paths. Each one is
// resolved and confirmed to still be inside uploads/ before it is attached - the
// same guard the ticket attachment download endpoints apply - and a file that
// has been deleted since the message was queued is simply skipped.
// File attachments arrive as a manifest of app-root-relative paths. Each one is resolved and confirmed to still be
// inside uploads/ before it is attached - the same guard the ticket attachment download endpoints apply - and a
// file that has been deleted since the message was queued is simply skipped.
if (!empty($attachments_json)) {
$attachment_manifest = json_decode($attachments_json, true);
$uploads_base = realpath(__DIR__ . '/../uploads');
if (is_array($attachment_manifest) && $uploads_base !== false) {
foreach ($attachment_manifest as $attachment) {
if (empty($attachment['path']) || empty($attachment['name'])) {
continue;
}
$attachment_path = realpath(__DIR__ . '/../' . $attachment['path']);
if ($attachment_path === false || strpos($attachment_path, $uploads_base) !== 0) {
continue;
}
// A picture that was in the message as data goes in inline, where its cid: points (emailInlineImages())
if (!empty($attachment['cid'])) {
$mail->addEmbeddedImage($attachment_path, (string) $attachment['cid'], basename($attachment['name']));
@@ -381,24 +403,42 @@ function sendQueueEmail(
}
}
if ($graph_token !== null) {
mailGraphSend($mail, $graph_token);
return true;
$everyone = array_values(array_unique(array_map('strtolower', array_merge([$to_email], array_column($cc, 'email')))));
if ($mailer['graph'] !== null) {
mailGraphSend($mail, $mailer['graph']);
return ['accepted' => $everyone, 'refused' => []];
}
mailQueueConnect($mailer);
try {
$mail->send();
} catch (Exception $e) {
$refused = $smtp instanceof MailQueueSmtp ? $smtp->refused : [];
// Some or all of its recipients turned away - PHPMailer sent it to the rest, and said so last
if ($e->getCode() === PHPMailer::STOP_CONTINUE && $refused) {
return ['accepted' => array_values(array_diff($everyone, array_keys($refused))), 'refused' => $refused];
}
// Part-way through - a new conversation for the next email
$mail->smtpClose();
// PHPMailer names the step that failed ("data not accepted"); the mail server's reply says why - keep it with the email
$smtp = $mail->getSMTPInstance()->getError();
$detail = trim(preg_replace('/\s+/', ' ', (string) ($smtp['detail'] ?? '')));
$error = $smtp->getError();
$detail = trim(preg_replace('/\s+/', ' ', (string) ($error['detail'] ?? '')));
if ($detail !== '' && strpos($e->getMessage(), $detail) === false) {
$code = trim(($smtp['smtp_code'] ?? '') . ' ' . ($smtp['smtp_code_ex'] ?? ''));
$code = trim(($error['smtp_code'] ?? '') . ' ' . ($error['smtp_code_ex'] ?? ''));
throw new Exception($e->getMessage() . ' The mail server said: ' . ($code !== '' ? "$code " : '') . $detail, $e->getCode(), $e);
}
throw $e;
}
return true;
return ['accepted' => $everyone, 'refused' => []];
}
/** Why the mail server turned recipients away, in a line - "address: 550 5.1.1 User unknown; ...". */
function mailQueueRefusedText(array $refused) {
$parts = [];
foreach ($refused as $address => $why) {
$parts[] = $address . ': ' . trim($why['code'] . ' ' . $why['detail']);
}
return implode('; ', $parts);
}
/** =======================================================================
@@ -409,7 +449,7 @@ function sendQueueEmail(
* delivered. The cron lock above guarantees no other run of this script is in
* progress, so any row still sitting at status 1 is by definition orphaned and
* safe to reclaim. It is moved to failed rather than queued so it inherits the
* retry pass's 30 minute backoff and attempt cap instead of retrying instantly.
* retry pass's wait and attempt cap instead of retrying instantly.
*
* This can re-send a message that did go out but died before being marked sent.
* That trade is deliberate: a duplicate is recoverable, an invoice that silently
@@ -423,198 +463,162 @@ if ($orphaned_emails > 0) {
}
/** =======================================================================
* SEND: status = 0 (Queued)
* SEND: what is due - waiting (status 0) and failed ones whose wait is over (status 2) - at most the
* pace a minute (mailQueuePerMinute()), bulk email after everything else, oldest first
* ======================================================================= */
// The copied in and the headers - once the 4.2.6 update has made their columns
$thread_columns = ticketMailThreadReady() ? 'email_cc, email_headers' : "'' AS email_cc, '' AS email_headers";
$per_minute = mailQueuePerMinute();
$bulk_order = mailQueuePaceReady() ? 'email_bulk, ' : '';
$sql_queue = mysqli_query($mysqli, "SELECT email_attachments, email_cal_str, email_content, email_from, email_from_name, email_id,
email_recipient, email_recipient_name, email_subject, $thread_columns FROM email_queue WHERE email_status = 0 AND email_queued_at <= NOW()");
$sql_queue = mysqli_query($mysqli, "SELECT email_attachments, email_attempts, email_cal_str, email_content, email_from, email_from_name, email_id,
email_recipient, email_recipient_name, email_status, email_subject, $thread_columns FROM email_queue
WHERE (email_status = 0 AND email_queued_at <= NOW())
OR (email_status = 2 AND email_attempts < " . MAIL_QUEUE_TRIES . " AND " . mailQueueRetryDueSql() . ")
ORDER BY {$bulk_order}email_queued_at, email_id LIMIT $per_minute");
if (mysqli_num_rows($sql_queue) > 0) {
while ($rowq = mysqli_fetch_assoc($sql_queue)) {
$email_id = (int)$rowq['email_id'];
$email_from = $rowq['email_from'];
$email_from_name = $rowq['email_from_name'];
$email_recipient = $rowq['email_recipient'];
$email_recipient_name = $rowq['email_recipient_name'];
$email_subject = $rowq['email_subject'];
$email_content = $rowq['email_content'];
$email_ics_str = $rowq['email_cal_str'];
$email_attachments = $rowq['email_attachments'];
$mailer = null;
$no_mx_check = in_array('--no-mx-validation', $argv ?? [], true);
// sent, tried again later, given up on (out of tries, or no address), turned away for good, the addresses turned away for good, sent with some of the copied in turned away
$run = ['sent' => 0, 'again' => 0, 'gave_up' => 0, 'turned_away' => 0, 'refused' => [], 'partial' => 0, 'stopped' => '', 'stopped_soft' => false, 'last_error' => ''];
$temporary_in_a_row = 0;
// Check sender
if (!filter_var($email_from, FILTER_VALIDATE_EMAIL)) {
$email_from_logging = escapeSql($rowq['email_from']);
$why = (trim((string) $email_from) === '' ? 'It has no from address' : "The from address isn't one: $email_from") . ' - the addresses are set in Settings > Mail > From addresses';
mysqli_query($mysqli, "UPDATE email_queue SET email_status = 2, email_attempts = 99, email_failed_at = NOW()" . mailQueueErrorSql($why) . " WHERE email_id = $email_id");
logApp("Cron-Mail-Queue", "Error", "Failed to send email #$email_id due to invalid sender address: $email_from_logging - check configuration in settings.");
appNotify("Mail", "Failed to send email #$email_id due to invalid sender address");
continue;
}
while ($sql_queue && ($rowq = mysqli_fetch_assoc($sql_queue))) {
$email_id = (int) $rowq['email_id'];
$was = (int) $rowq['email_status'];
$attempts = (int) $rowq['email_attempts'] + 1;
$email_recipient = (string) $rowq['email_recipient'];
$email_recipient_logging = escapeSql($email_recipient);
$email_subject_logging = escapeSql($rowq['email_subject']);
// Claim the row - the conditional UPDATE is the lock. If another run already took
// this email, skip it rather than sending the client a second copy.
mysqli_query($mysqli, "UPDATE email_queue SET email_status = 1 WHERE email_id = $email_id AND email_status = 0");
if (mysqli_affected_rows($mysqli) !== 1) {
continue;
}
// Basic recipient syntax check
if (!filter_var($email_recipient, FILTER_VALIDATE_EMAIL)) {
mysqli_query($mysqli, "UPDATE email_queue SET email_status = 2, email_attempts = 99, email_failed_at = NOW()" . mailQueueErrorSql("The address it is to isn't an email address") . " WHERE email_id = $email_id");
$email_to_logging = escapeSql($email_recipient);
$email_subject_logging = escapeSql($rowq['email_subject']);
logApp("Cron-Mail-Queue", "Error", "Failed to send email: $email_id to $email_to_logging due to invalid recipient address. Email subject was: $email_subject_logging");
appNotify("Mail", "Failed to send email #$email_id to $email_to_logging due to invalid recipient address: Email subject was: $email_subject_logging");
continue;
}
// A domain with no mail server (if not disabled with --no-mx-validation) - a failed try like any other, tried
// again as they are, as a lookup can fail for a moment. It used to end the email there and then
$domain_problem = in_array('--no-mx-validation', $argv) ? '' : mailQueueDomainProblem($email_recipient);
if ($domain_problem !== '') {
mysqli_query($mysqli, "UPDATE email_queue SET email_status = 2, email_attempts = 1, email_failed_at = NOW()" . mailQueueErrorSql($domain_problem) . " WHERE email_id = $email_id");
$email_to_logging = escapeSql($email_recipient);
$email_subject_logging = escapeSql($rowq['email_subject']);
logApp("Cron-Mail-Queue", "Error", "Failed to send email: $email_id to $email_to_logging - " . escapeSql($domain_problem) . ". Email subject was: $email_subject_logging");
appNotify("Cron-Mail-Queue", "Failed to send email #$email_id to $email_to_logging - " . escapeSql($domain_problem) . " - it is tried again in " . MAIL_QUEUE_RETRY_MINUTES . " minutes",
"/admin/mail_queue.php?show=retrying", 0, $email_id);
continue;
}
try {
sendQueueEmail(
($config_smtp_provider ?: 'standard_smtp'),
(string)$config_smtp_host,
(int)$config_smtp_port,
(string)$config_smtp_encryption,
(string)$config_smtp_username,
(string)$config_smtp_password,
(string)$email_from,
(string)$email_from_name,
(string)$email_recipient,
(string)$email_recipient_name,
(string)$email_subject,
(string)$email_content,
(string)$email_ics_str,
(string)$email_attachments,
(string)$config_mail_oauth_client_id,
(string)$config_mail_oauth_client_secret,
(string)$config_mail_oauth_tenant_id,
(string)$config_mail_oauth_refresh_token,
(string)$config_mail_oauth_access_token,
(string)$config_mail_oauth_access_token_expires_at,
(string)$rowq['email_cc'],
(string)$rowq['email_headers']
);
// Sent - one with a link or code that opens something is cleared now (mailQueueSentSql())
mysqli_query($mysqli, "UPDATE email_queue SET email_status = 3, email_sent_at = NOW(), email_attempts = 1" . mailQueueSentSql() . mailQueueErrorSql(null) . " WHERE email_id = $email_id");
} catch (\Throwable $e) {
// Anything that stops this one email - not only PHPMailer's own Exception, which is what Exception names
// in this file. An Error used to end the whole run with this email left as Sending and the rest unsent.
mysqli_query($mysqli, "UPDATE email_queue SET email_status = 2, email_failed_at = NOW(), email_attempts = 1" . mailQueueErrorSql($e->getMessage()) . " WHERE email_id = $email_id");
$email_recipient_logging = escapeSql($rowq['email_recipient']);
$email_subject_logging = escapeSql($rowq['email_subject']);
$err = substr("Mailer Error: " . $e->getMessage(), 0, 100) . "...";
appNotify("Cron-Mail-Queue", "Failed to send email #$email_id to $email_recipient_logging - " . escapeSql(mb_strimwidth(mailQueueErrorText($e->getMessage()), 0, 200, '...'))
. " - it is tried again in " . MAIL_QUEUE_RETRY_MINUTES . " minutes", "/admin/mail_queue.php?show=retrying", 0, $email_id);
logApp("Cron-Mail-Queue", "Error", "Failed to send email: $email_id to $email_recipient_logging regarding $email_subject_logging. $err");
}
// Claim the row - the conditional UPDATE is the lock. If another run already took this email, skip it rather than
// sending the client a second copy
mysqli_query($mysqli, "UPDATE email_queue SET email_status = 1 WHERE email_id = $email_id AND email_status = $was");
if (mysqli_affected_rows($mysqli) !== 1) {
continue;
}
// A from address or an address it is to that isn't one - not tried again
$not_one = !filter_var($rowq['email_from'], FILTER_VALIDATE_EMAIL)
? (trim((string) $rowq['email_from']) === '' ? 'It has no from address' : "The from address isn't one: " . $rowq['email_from']) . ' - the addresses are set in Admin > Settings > Mail, From addresses'
: (!filter_var($email_recipient, FILTER_VALIDATE_EMAIL) ? "The address it is to isn't an email address" : '');
if ($not_one !== '') {
mysqli_query($mysqli, "UPDATE email_queue SET email_status = 2, email_attempts = 99, email_failed_at = NOW()" . mailQueueErrorSql($not_one) . " WHERE email_id = $email_id");
logApp("Cron-Mail-Queue", "Error", "Didn't send email #$email_id to $email_recipient_logging - " . escapeSql($not_one) . ". Subject: $email_subject_logging");
$run['gave_up']++;
$run['last_error'] = $not_one;
continue;
}
// Its domain asked first - a domain with no mail server is a failed try, about this address alone (functions/mail_queue.php)
$domain_problem = $no_mx_check ? '' : mailQueueDomainProblem($email_recipient);
if ($domain_problem !== '') {
mysqli_query($mysqli, "UPDATE email_queue SET email_status = 2, email_failed_at = NOW(), email_attempts = $attempts" . mailQueueErrorSql($domain_problem) . " WHERE email_id = $email_id");
logApp("Cron-Mail-Queue", "Error", "Failed to send email #$email_id to $email_recipient_logging - " . escapeSql($domain_problem) . ". Subject: $email_subject_logging");
$run['last_error'] = $domain_problem;
$attempts >= MAIL_QUEUE_TRIES ? $run['gave_up']++ : $run['again']++;
continue;
}
try {
if ($mailer === null) {
$mailer = mailQueueMailer(($config_smtp_provider ?: 'standard_smtp'), (string) $config_smtp_host, (int) $config_smtp_port, (string) $config_smtp_encryption,
(string) $config_smtp_username, (string) $config_smtp_password, (string) emailFrom()['email'], (string) $config_mail_oauth_client_id,
(string) $config_mail_oauth_client_secret, (string) $config_mail_oauth_tenant_id, (string) $config_mail_oauth_refresh_token,
(string) $config_mail_oauth_access_token, (string) $config_mail_oauth_access_token_expires_at);
}
$result = sendQueueEmail($mailer, (string) $rowq['email_from'], (string) $rowq['email_from_name'], $email_recipient, (string) $rowq['email_recipient_name'],
(string) $rowq['email_subject'], (string) $rowq['email_content'], (string) $rowq['email_cal_str'], (string) $rowq['email_attachments'],
(string) $rowq['email_cc'], (string) $rowq['email_headers']);
} catch (MailQueueUnreachable $e) {
// The mail server, not this email - it waits as it was, and the run stops: the rest would only fail the same way
mysqli_query($mysqli, "UPDATE email_queue SET email_status = $was WHERE email_id = $email_id AND email_status = 1");
$run['stopped'] = $e->getMessage();
break;
} catch (\Throwable $e) {
// Anything else that stopped this one email - tried again after a wait (MAIL_QUEUE_RETRY_AFTER), unless that was its last try
mysqli_query($mysqli, "UPDATE email_queue SET email_status = 2, email_failed_at = NOW(), email_attempts = $attempts" . mailQueueErrorSql($e->getMessage()) . " WHERE email_id = $email_id");
logApp("Cron-Mail-Queue", "Error", "Failed to send email #$email_id to $email_recipient_logging regarding $email_subject_logging. " . escapeSql(mb_substr("Mailer Error: " . $e->getMessage(), 0, 300)));
$run['last_error'] = $e->getMessage();
if ($attempts >= MAIL_QUEUE_TRIES) {
$run['gave_up']++;
} else {
$run['again']++;
}
// Two in a row turned away for now - a host's limit, or its trouble: the rest wait for the next minute rather than use up their tries
if (++$temporary_in_a_row >= 2) {
$run['stopped'] = 'The mail server turned away two emails in a row for now - the rest wait for the next minute. It said: ' . mailQueueErrorText($e->getMessage());
$run['stopped_soft'] = true;
break;
}
continue;
}
$temporary_in_a_row = 0;
// Who the mail server turned away for good (5xx) - their contacts show Email bounced (functions/contact_bounce.php), and no email
// to them is tried again
$for_good = array_filter($result['refused'], function ($why) {
return substr($why['code'], 0, 1) === '5';
});
foreach ($for_good as $address => $why) {
foreach (contactBounceMark($address, trim($why['code'] . ' ' . $why['detail'])) as $bounced_contact_id => [$bounced_name, $bounced_client_id]) {
logAudit("Contact", "Edit", "Mail queue: the mail server turned away " . escapeSql($address) . " (" . escapeSql($bounced_name) . ") - marked Email bounced", $bounced_client_id, $bounced_contact_id);
}
$run['refused'][$address] = trim($why['code'] . ' ' . $why['detail']);
}
if ($result['accepted']) {
// Sent - one with a link or code that opens something is cleared now (mailQueueSentSql()). Any of the copied in turned away
// are said with it: it isn't sent again, as everyone else has it
$note = $result['refused'] ? 'Sent - but the mail server turned away ' . mailQueueRefusedText($result['refused']) : null;
mysqli_query($mysqli, "UPDATE email_queue SET email_status = 3, email_sent_at = NOW(), email_attempts = $attempts" . mailQueueSentSql() . mailQueueErrorSql($note) . " WHERE email_id = $email_id");
$run['sent']++;
if ($result['refused']) {
$run['partial']++;
}
} elseif (count($for_good) === count($result['refused'])) {
// Everyone turned away for good - not tried again
mysqli_query($mysqli, "UPDATE email_queue SET email_status = 2, email_failed_at = NOW(), email_attempts = 99" . mailQueueErrorSql('Turned away for good - ' . mailQueueRefusedText($result['refused'])) . " WHERE email_id = $email_id");
logApp("Cron-Mail-Queue", "Error", "The mail server turned away email #$email_id for good - " . escapeSql(mailQueueRefusedText($result['refused'])));
$run['turned_away']++;
} else {
// Turned away for now - tried again after a wait
$why = 'Turned away for now - ' . mailQueueRefusedText($result['refused']);
mysqli_query($mysqli, "UPDATE email_queue SET email_status = 2, email_failed_at = NOW(), email_attempts = $attempts" . mailQueueErrorSql($why) . " WHERE email_id = $email_id");
$run['last_error'] = $why;
$attempts >= MAIL_QUEUE_TRIES ? $run['gave_up']++ : $run['again']++;
}
}
if ($mailer !== null && $mailer['graph'] === null) {
$mailer['mail']->smtpClose();
}
/** =======================================================================
* RETRIES: status = 2 (Failed), attempts < MAIL_QUEUE_TRIES (4), wait
* MAIL_QUEUE_RETRY_MINUTES (30) - functions/mail_queue.php, which the Mail
* Queue page reads too, to say when the next try is
* =======================================================================
*/
$sql_failed_queue = mysqli_query(
$mysqli,
"SELECT email_attachments, email_attempts, email_cal_str, email_content, email_from,
email_from_name, email_id, email_recipient, email_recipient_name, email_subject, $thread_columns FROM email_queue
WHERE email_status = 2
AND email_attempts < " . MAIL_QUEUE_TRIES . "
AND email_failed_at <= NOW() - INTERVAL " . MAIL_QUEUE_RETRY_MINUTES . " MINUTE"
);
if (mysqli_num_rows($sql_failed_queue) > 0) {
while ($rowf = mysqli_fetch_assoc($sql_failed_queue)) {
$email_id = (int)$rowf['email_id'];
$email_from = $rowf['email_from'];
$email_from_name = $rowf['email_from_name'];
$email_recipient = $rowf['email_recipient'];
$email_recipient_name = $rowf['email_recipient_name'];
$email_subject = $rowf['email_subject'];
$email_content = $rowf['email_content'];
$email_ics_str = $rowf['email_cal_str'];
$email_attachments = $rowf['email_attachments'];
$email_attempts = (int)$rowf['email_attempts'] + 1;
// Claim the row - same lock as the send path, from the failed state this time.
mysqli_query($mysqli, "UPDATE email_queue SET email_status = 1 WHERE email_id = $email_id AND email_status = 2");
if (mysqli_affected_rows($mysqli) !== 1) {
continue;
}
if (!filter_var($email_recipient, FILTER_VALIDATE_EMAIL)) {
mysqli_query($mysqli, "UPDATE email_queue SET email_status = 2, email_attempts = $email_attempts, email_failed_at = NOW()" . mailQueueErrorSql("The address it is to isn't an email address") . " WHERE email_id = $email_id");
continue;
}
try {
// Its domain asked again - a failed try, as one that won't send is, until the last of them
$domain_problem = in_array('--no-mx-validation', $argv) ? '' : mailQueueDomainProblem($email_recipient);
if ($domain_problem !== '') {
throw new \RuntimeException($domain_problem);
}
sendQueueEmail(
($config_smtp_provider ?: 'standard_smtp'),
(string)$config_smtp_host,
(int)$config_smtp_port,
(string)$config_smtp_encryption,
(string)$config_smtp_username,
(string)$config_smtp_password,
(string)$email_from,
(string)$email_from_name,
(string)$email_recipient,
(string)$email_recipient_name,
(string)$email_subject,
(string)$email_content,
(string)$email_ics_str,
(string)$email_attachments,
(string)$config_mail_oauth_client_id,
(string)$config_mail_oauth_client_secret,
(string)$config_mail_oauth_tenant_id,
(string)$config_mail_oauth_refresh_token,
(string)$config_mail_oauth_access_token,
(string)$config_mail_oauth_access_token_expires_at,
(string)$rowf['email_cc'],
(string)$rowf['email_headers']
);
// Sent - one with a link or code that opens something is cleared now (mailQueueSentSql())
mysqli_query($mysqli, "UPDATE email_queue SET email_status = 3, email_sent_at = NOW(), email_attempts = $email_attempts" . mailQueueSentSql() . mailQueueErrorSql(null) . " WHERE email_id = $email_id");
} catch (\Throwable $e) {
mysqli_query($mysqli, "UPDATE email_queue SET email_status = 2, email_failed_at = NOW(), email_attempts = $email_attempts" . mailQueueErrorSql($e->getMessage()) . " WHERE email_id = $email_id");
$email_recipient_logging = escapeSql($rowf['email_recipient']);
$email_subject_logging = escapeSql($rowf['email_subject']);
$err = substr("Mailer Error: " . $e->getMessage(), 0, 100) . "...";
// The last of its tries - nothing more happens to it unless someone retries it
if ($email_attempts >= MAIL_QUEUE_TRIES) {
appNotify("Cron-Mail-Queue", "Gave up on email #$email_id to $email_recipient_logging after $email_attempts tries - " . escapeSql(mb_strimwidth(mailQueueErrorText($e->getMessage()), 0, 200, '...')),
"/admin/mail_queue.php?show=failed", 0, $email_id);
}
logApp("Cron-Mail-Queue", "Error", "Failed to re-send email #$email_id to $email_recipient_logging regarding $email_subject_logging. $err");
}
}
* What the admins hear - once for the run, not once an email to every agent, and once an hour at most
* (mailQueueNotifyAdmins()): an email given up on or turned away, or a run stopped. One that failed for
* now and is tried again shows in Admin > Mail Queue, Retrying
* ======================================================================= */
$said = [];
if ($run['stopped'] !== '' && !$run['stopped_soft']) {
$said[] = 'Email can\'t go out - ITFlow couldn\'t reach or sign in to the mail server: ' . mailQueueErrorText($run['stopped']) . ' It waits in the queue and goes once the server takes it - nothing is lost.';
} elseif ($run['stopped'] !== '') {
$said[] = $run['stopped'];
}
if ($run['refused']) {
$said[] = 'The mail server turned away ' . count($run['refused']) . ' address' . (count($run['refused']) === 1 ? '' : 'es') . ' for good, now marked Email bounced: '
. mb_strimwidth(implode('; ', array_map(function ($address, $why) { return "$address ($why)"; }, array_keys($run['refused']), $run['refused'])), 0, 300, '...') . '.';
}
if ($run['gave_up']) {
$said[] = $run['gave_up'] . ' email' . ($run['gave_up'] === 1 ? ' was' : 's were') . ' given up on' . ($run['last_error'] !== '' ? ' - ' . mb_strimwidth(mailQueueErrorText($run['last_error']), 0, 200, '...') : '') . '.';
}
if ($said) {
mailQueueNotifyAdmins('Mail queue: ' . implode(' ', $said), '/admin/mail_queue.php' . ($run['gave_up'] || $run['turned_away'] ? '?show=failed' : ($run['again'] ? '?show=retrying' : '')));
}
echo "Sent: {$run['sent']}, to try again: {$run['again']}, given up: {$run['gave_up']}, turned away: {$run['turned_away']}" . ($run['stopped'] !== '' ? " - stopped: {$run['stopped']}" : '') . "\n";
// A mail server out of reach is this job's error - Maintenance > Cron and Admin > Mail Queue say it
if ($run['stopped'] !== '' && !$run['stopped_soft']) {
cronJobStop("Couldn't reach or sign in to the mail server: " . $run['stopped'], 1);
}

2
db.sql
View File

@@ -1777,6 +1777,7 @@ CREATE TABLE `email_queue` (
`email_sent_at` datetime DEFAULT NULL,
`email_ticket_reply_id` int(11) DEFAULT NULL,
`email_sensitive` tinyint(1) NOT NULL DEFAULT 0,
`email_bulk` tinyint(1) NOT NULL DEFAULT 0,
PRIMARY KEY (`email_id`),
KEY `email_status` (`email_status`,`email_queued_at`),
KEY `email_ticket_reply_id` (`email_ticket_reply_id`)
@@ -4026,6 +4027,7 @@ CREATE TABLE `settings` (
`config_smtp_encryption` varchar(200) DEFAULT NULL,
`config_smtp_username` varchar(200) DEFAULT NULL,
`config_smtp_password` varchar(200) DEFAULT NULL,
`config_mail_send_per_minute` int(11) NOT NULL DEFAULT 30,
`config_mail_from_email` varchar(200) DEFAULT NULL,
`config_mail_from_name` varchar(200) DEFAULT NULL,
`config_imap_provider` varchar(200) DEFAULT NULL,

View File

@@ -859,6 +859,8 @@ function addToMailQueue($data) {
$ticket_reply_sql = !empty($email['ticket_reply_id']) ? ', email_ticket_reply_id = ' . intval($email['ticket_reply_id']) : '';
// One with a link or code that opens something, cleared once it has gone (emailQueue()'s sensitive) - once the 3.7.1 update has made the column
$sensitive_sql = !empty($email['sensitive']) && mailQueueHasSensitive() ? ', email_sensitive = 1' : '';
// An email to many, sent after everything else (emailQueue()'s bulk) - once the 4.2.9 update has made the column
$sensitive_sql .= !empty($email['bulk']) && mailQueuePaceReady() ? ', email_bulk = 1' : '';
// The people copied in, and the conversation's headers (emailQueue()'s together and thread) - once the 4.2.6 update has made the columns
$thread_sql = '';
if (ticketMailThreadReady()) {

View File

@@ -553,6 +553,8 @@ function emailInlineImages($html, array $ticket = []) {
* and answering, the Message-ID of the email it answers, when it answers one
* auto replied (an automatic answer to an email) or generated (sent by ITFlow by
* itself) - headers saying so, so it isn't answered (ticketMailAutoHeaders())
* bulk an email to many - the contacts or clients list's Email - which the mail queue
* sends after everything else (email_queue.email_bulk)
* Who it was queued to, "Name (email)" - the copied in too: only those that went in the queue
* (addToMailQueue()). Nothing is queued without mail set up. The subject is cut to fit (emailFit()).
*/
@@ -621,6 +623,7 @@ function emailQueue(array $recipients, $subject, array $email, array $opts = [])
+ ($queued_at !== '' ? ['queued_at' => $queued_at] : [])
+ (intval($opts['ticket_reply_id'] ?? 0) > 0 && ticketReplyEmailReady() ? ['ticket_reply_id' => intval($opts['ticket_reply_id'])] : [])
+ (!empty($opts['sensitive']) ? ['sensitive' => 1] : [])
+ (!empty($opts['bulk']) ? ['bulk' => 1] : [])
+ ($cc_list ? ['cc' => $cc_list] : [])
+ ($thread !== null || $auto_headers ? ['headers' => ($thread !== null ? ticketMailHeaders($thread_id, (string) $from['email'], $thread) : []) + $auto_headers] : []);
// Each on its own, so who it went to is only those queued - one that couldn't be is logged (addToMailQueue())
@@ -715,5 +718,5 @@ function emailBulkSend(array $recipients, $mailbox, $from_name, $subject, $body,
'title' => trim((string) $subject),
'preview' => mb_substr(trim(preg_replace('/\s+/', ' ', html_entity_decode(strip_tags((string) $body), ENT_QUOTES, 'UTF-8'))), 0, 140),
'content' => (string) $body,
], ['from' => ['email' => $box['email'], 'name' => $from_name !== '' ? $from_name : $box['name']], 'queued_at' => $queued_at]);
], ['from' => ['email' => $box['email'], 'name' => $from_name !== '' ? $from_name : $box['name']], 'queued_at' => $queued_at, 'bulk' => true]);
}

View File

@@ -8,10 +8,11 @@
* email_status is where it is:
* 0 waiting - or scheduled, while its email_queued_at is still ahead
* 1 being sent this minute
* 2 failed - tried again every MAIL_QUEUE_RETRY_MINUTES until it has had
* MAIL_QUEUE_TRIES; 99 tries means it isn't tried again (a bad address).
* A domain with no mail server is a failed try like any other
* (mailQueueDomainProblem()), as a lookup can fail for a moment
* 2 failed - tried again after a wait that grows (MAIL_QUEUE_RETRY_AFTER, about eight
* hours in all) until it has had MAIL_QUEUE_TRIES; 99 tries means it isn't tried
* again - an address the mail server turned away for good. A domain with no mail
* server is a failed try like any other (mailQueueDomainProblem()), as a lookup
* can fail for a moment
* 3 sent - it keeps what it said, its calendar file and attachments, except
* one that carried a link or code that opens something (email_sensitive:
* a shared login, an invite, a password link, a signing or approval link),
@@ -26,10 +27,16 @@
* headers that keep its conversation together (email_headers - mailQueueHeaders()). The address
* it is to is the one whose domain is checked before each try; a mail server turns away the
* copied-in itself.
*
* The job sends at most config_mail_send_per_minute a run (database 4.2.9 - 30 until then) over one
* connection, bulk email (email_bulk) after everything else, and stops for the minute when the mail
* server turns two away in a row for now - a host's limit - so the rest wait their turn rather than
* use up their tries. A mail server it can't reach or sign in to costs no email a try.
*/
const MAIL_QUEUE_TRIES = 4;
const MAIL_QUEUE_RETRY_MINUTES = 30;
// Minutes before each try again - after the first failed try, the second... about eight hours in all
const MAIL_QUEUE_RETRY_AFTER = [5, 10, 20, 40, 60, 120, 240];
const MAIL_QUEUE_TRIES = 8;
const MAIL_QUEUE_KEEP_DAYS = 90;
const MAIL_QUEUE_CANCELLED = 4;
// Pictures that were in an email as data, kept once each for the queue to attach inline (emailInlineImages()) - the web can't reach uploads/tmp
@@ -41,6 +48,101 @@ const MAIL_QUEUE_IMAGE_DIR = 'uploads/tmp/mail_images';
* (cron/mail_queue.php), so a lookup that failed for a moment is asked again on the next try
* rather than ending the email.
*/
/** Minutes between an email's failed try $attempts (1, 2...) and its next (MAIL_QUEUE_RETRY_AFTER). */
function mailQueueRetryMinutes($attempts) {
$after = MAIL_QUEUE_RETRY_AFTER;
return $after[max(0, min(count($after), intval($attempts)) - 1)];
}
/* SQL - a failed email whose wait for its next try is over (mailQueueRetryMinutes()), for its email_failed_at and email_attempts. */
function mailQueueRetryDueSql() {
$cases = '';
foreach (MAIL_QUEUE_RETRY_AFTER as $i => $minutes) {
$cases .= ' WHEN ' . ($i + 1) . " THEN $minutes";
}
$last = MAIL_QUEUE_RETRY_AFTER[count(MAIL_QUEUE_RETRY_AFTER) - 1];
return "email_failed_at <= NOW() - INTERVAL (CASE email_attempts$cases ELSE $last END) MINUTE";
}
/* Whether the 4.2.9 update has run - the sending pace (config_mail_send_per_minute) and bulk email (email_bulk). */
function mailQueuePaceReady() {
global $mysqli;
static $ready = null;
if ($ready === null) {
$version = defined('CURRENT_DATABASE_VERSION') ? CURRENT_DATABASE_VERSION
: (string) (mysqli_fetch_row(mysqli_query($mysqli, "SELECT config_current_database_version FROM settings WHERE company_id = 1"))[0] ?? '0');
$ready = version_compare($version, '4.2.9', '>=');
}
return $ready;
}
/* The most emails the queue sends a minute (Admin > Settings > Mail, Sending) - 30 before the 4.2.9 update. */
function mailQueuePerMinute() {
global $mysqli;
if (!mailQueuePaceReady()) {
return 30;
}
$per_minute = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT config_mail_send_per_minute FROM settings WHERE company_id = 1"))[0] ?? 30);
return max(1, min(1000, $per_minute));
}
/*
* The name the queue gives its mail server for this machine (SMTP HELO) and puts in a Message-ID of
* its own - the host of ITFlow's address (config.php), or else that of $from_email. PHPMailer took
* the machine's own name, "vm" or a container's, which spam filters count against an email.
*/
function mailQueueHostname($from_email = '') {
global $config_base_url;
foreach ([(string) parse_url('https://' . trim((string) $config_base_url), PHP_URL_HOST), substr((string) $from_email, strrpos((string) $from_email, '@') !== false ? strrpos((string) $from_email, '@') + 1 : strlen((string) $from_email))] as $host) {
$host = strtolower(trim($host, '[] '));
if (preg_match('/^(?=.{4,253}$)([a-z0-9]([a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,63}$/', $host)) {
return $host;
}
}
return '';
}
/*
* An email's plain text part, beside its HTML - the reply line first when it has one, so a reply in
* plain text is cut cleanly too (emailReplyText()); each link as its words and address; a table's cells
* apart; and not the hidden line an inbox shows beside the subject. An email of HTML alone counts against it
* with spam filters, and a mail program that shows only text showed its HTML.
*/
function mailQueueTextPart($html) {
$html = (string) $html;
$marker = strpos($html, EMAIL_REPLY_MARKER) !== false;
$html = preg_replace('#<div style="display:none[^"]*"[^>]*>.*?</div>#is', '', $html) ?? $html;
$html = preg_replace_callback('#<a\b[^>]*\bhref\s*=\s*(["\'])(https?://[^"\']+)\1[^>]*>(.*?)</a>#is', function ($m) {
$label = trim(html_entity_decode(strip_tags($m[3]), ENT_QUOTES | ENT_HTML5, 'UTF-8'));
$url = html_entity_decode($m[2], ENT_QUOTES | ENT_HTML5, 'UTF-8');
return htmlspecialchars($label === '' || $label === $url ? $url : "$label: $url", ENT_QUOTES, 'UTF-8');
}, $html) ?? $html;
$html = preg_replace('#</t[dh]\s*>#i', ' $0', $html) ?? $html;
$text = emailPlainText($html);
return ($marker ? EMAIL_REPLY_MARKER . "\n\n" : '') . $text;
}
/*
* Tell the admins about the mail queue - $text, and where to look ($action). Once an hour at most: an
* admin with a notice from the queue that is still there from the last hour isn't told again, as a run
* a minute with a mail server down would fill their bell. It used to tell every agent, once an email.
*/
function mailQueueNotifyAdmins($text, $action = '/admin/mail_queue.php') {
global $mysqli;
$text_sql = logSqlText($text, 1000);
$action_sql = logSqlText($action, 250);
$sql = mysqli_query($mysqli, "SELECT user_id FROM users JOIN user_roles ON role_id = user_role_id
WHERE role_is_admin = 1 AND user_type = 1" . serviceAccountsOutSql() . " AND user_status = 1 AND user_archived_at IS NULL
AND user_id NOT IN (SELECT notification_user_id FROM notifications WHERE notification_type = 'Mail Queue' AND notification_dismissed_at IS NULL
AND notification_timestamp >= NOW() - INTERVAL 1 HOUR)");
$told = 0;
while ($row = mysqli_fetch_row($sql)) {
mysqli_query($mysqli, "INSERT INTO notifications SET notification_type = 'Mail Queue', notification = '$text_sql', notification_action = '$action_sql', notification_user_id = " . intval($row[0]));
$told++;
}
return $told;
}
function mailQueueDomainProblem($recipient) {
static $asked = []; // each domain once a run - a queue of email to one client asks once
$recipient = (string) $recipient;
@@ -101,7 +203,7 @@ function mailQueueStateOf(array $row) {
'detail' => 'Going now', 'title' => ''];
}
if ($status === 2 && $tries < MAIL_QUEUE_TRIES) {
$next = $failed !== '' ? strtotime($failed) + MAIL_QUEUE_RETRY_MINUTES * 60 : time();
$next = $failed !== '' ? strtotime($failed) + mailQueueRetryMinutes($tries) * 60 : time();
return ['key' => 'retrying', 'label' => 'Retrying', 'badge' => 'text-bg-warning', 'icon' => 'fa-redo-alt',
'detail' => 'Tried ' . max(1, $tries) . ' of ' . MAIL_QUEUE_TRIES . ' · next ' . ($next > time() ? 'about ' . date('g:i A', $next) : 'any minute'),
'title' => $failed !== '' ? 'Last failed ' . $when($failed) : ''];
@@ -230,8 +332,9 @@ function mailQueueHealth() {
return ['level' => 'warning', 'key' => 'slow', 'title' => 'Email is waiting longer than it should', 'text' => trim($held) . ' The Mail Queue job last ran ' . $ago($job['cron_job_last_run_at'] ?? null) . '.' . $error,
'url' => 'cron.php', 'action' => 'Maintenance > Cron', 'waiting' => $waiting];
}
return ['level' => '', 'key' => 'ok', 'title' => '', 'text' => 'Sent by the Mail Queue job each minute - it last ran ' . $ago($job['cron_job_last_run_at'] ?? null) . '. A failed email is tried '
. (MAIL_QUEUE_TRIES - 1) . ' more times, ' . MAIL_QUEUE_RETRY_MINUTES . ' minutes apart. Email is kept ' . MAIL_QUEUE_KEEP_DAYS . ' days - with what it said, apart from one with a link or code that opens something, cleared once it has gone.', 'url' => '', 'action' => '', 'waiting' => 0];
return ['level' => '', 'key' => 'ok', 'title' => '', 'text' => 'Sent by the Mail Queue job each minute, up to ' . mailQueuePerMinute() . ' a minute, bulk email last - it last ran '
. $ago($job['cron_job_last_run_at'] ?? null) . '. A failed email is tried ' . (MAIL_QUEUE_TRIES - 1) . ' more times over about '
. round(array_sum(MAIL_QUEUE_RETRY_AFTER) / 60) . ' hours, and one the mail server turns away for good isn\'t tried again. Email is kept ' . MAIL_QUEUE_KEEP_DAYS . ' days - with what it said, apart from one with a link or code that opens something, cleared once it has gone.', 'url' => '', 'action' => '', 'waiting' => 0];
}
/* Whether email_queue has email_error yet - not until the 3.3.7 update has run. */

View File

@@ -369,6 +369,7 @@ function settingsFields() {
'words' => 'smtp tls ssl starttls secure'],
'config_smtp_username' => ['page' => 'mail', 'tab' => 'sending', 'section' => 'Sending', 'label' => 'SMTP username', 'words' => 'smtp user login sign in'],
'config_smtp_password' => ['page' => 'mail', 'tab' => 'sending', 'section' => 'Sending', 'label' => 'SMTP password', 'kind' => 'secret', 'words' => 'smtp password app password'],
'config_mail_send_per_minute' => ['page' => 'mail', 'tab' => 'sending', 'section' => 'Sending', 'label' => 'Emails a minute', 'words' => 'pace rate limit throttle per minute speed queue bulk'],
'config_imap_provider' => ['page' => 'mail', 'tab' => 'receiving', 'section' => 'Receiving', 'label' => 'Receiving provider', 'kind' => 'select', 'options' => 'mail_providers',
'words' => 'imap inbound receive mailbox email to ticket inbox'],
'config_imap_host' => ['page' => 'mail', 'tab' => 'receiving', 'section' => 'Receiving', 'label' => 'IMAP host', 'words' => 'imap server host'],

View File

@@ -271,7 +271,7 @@ function healthMailChecks() {
}
$summary = mailQueueSummary();
if ($summary['failed_week']) {
$items[] = healthItem('Failed', 'warning', $summary['failed_week'] . ' in the last week', 'Tried ' . MAIL_QUEUE_TRIES . ' times and given up on - the Mail Queue says why, and can try again.', 'mail_queue.php?show=failed', 'Mail Queue');
$items[] = healthItem('Failed', 'warning', $summary['failed_week'] . ' in the last week', 'Out of tries, or turned away for good by the mail server - the Mail Queue says why, and can try again.', 'mail_queue.php?show=failed', 'Mail Queue');
} else {
$items[] = healthItem('Failed', 'ok', 'None in the last week');
}