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

@@ -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. */