Files
itflow/cron/mail_queue.php

634 lines
34 KiB
PHP

<?php
// Set working directory to the directory this cron script lives at.
chdir(dirname(__FILE__));
// Ensure we're running from command line
if (php_sapi_name() !== 'cli') {
die("This script must be run from the command line.\n");
}
// Prevent overlapping runs of this script
$cron_lock_script = __FILE__;
require_once "includes/cron_lock.php";
require_once "../config.php";
require_once "../includes/inc_set_timezone.php";
require_once "../functions.php";
require_once "../libs/vendor/autoload.php";
// PHP Mailer Libs
require_once "../libs/PHPMailer/src/Exception.php";
require_once "../libs/PHPMailer/src/PHPMailer.php";
require_once "../libs/PHPMailer/src/SMTP.php";
require_once "../libs/PHPMailer/src/OAuthTokenProvider.php";
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');
}
if (!defined('MICROSOFT_OAUTH_BASE_URL')) {
define('MICROSOFT_OAUTH_BASE_URL', 'https://login.microsoftonline.com/');
}
/** =======================================================================
* XOAUTH2 Token Provider for PHPMailer (simple “static” provider)
* ======================================================================= */
class StaticTokenProvider implements OAuthTokenProvider {
private string $email;
private string $accessToken;
public function __construct(string $email, string $accessToken) {
$this->email = $email;
$this->accessToken = $accessToken;
}
public function getOauth64(): string {
$auth = "user={$this->email}\x01auth=Bearer {$this->accessToken}\x01\x01";
return base64_encode($auth);
}
}
/** =======================================================================
* Load settings
* ======================================================================= */
$sql_settings = mysqli_query($mysqli, "SELECT config_enable_cron, config_mail_oauth_access_token,
config_mail_oauth_access_token_expires_at, config_mail_oauth_client_id,
config_mail_oauth_client_secret, config_mail_oauth_refresh_token,
config_mail_oauth_tenant_id, config_smtp_encryption, config_smtp_host,
config_smtp_password, config_smtp_port, config_smtp_provider, config_smtp_username FROM settings WHERE company_id = 1");
$row = mysqli_fetch_assoc($sql_settings);
$config_enable_cron = intval($row['config_enable_cron']);
// SMTP baseline
$config_smtp_host = $row['config_smtp_host'];
$config_smtp_username = $row['config_smtp_username'];
$config_smtp_password = $row['config_smtp_password'];
$config_smtp_port = intval($row['config_smtp_port']);
$config_smtp_encryption = $row['config_smtp_encryption'];
// SMTP provider + shared OAuth fields
$config_smtp_provider = $row['config_smtp_provider']; // 'standard_smtp' | 'google_oauth' | 'microsoft_oauth'
$config_mail_oauth_client_id = $row['config_mail_oauth_client_id'] ?? '';
$config_mail_oauth_client_secret = $row['config_mail_oauth_client_secret'] ?? '';
$config_mail_oauth_tenant_id = $row['config_mail_oauth_tenant_id'] ?? '';
$config_mail_oauth_refresh_token = $row['config_mail_oauth_refresh_token'] ?? '';
$config_mail_oauth_access_token = $row['config_mail_oauth_access_token'] ?? '';
$config_mail_oauth_access_token_expires_at = $row['config_mail_oauth_access_token_expires_at'] ?? '';
// Switched off isn't an error - Maintenance > Cron shows why it stopped
if ($config_enable_cron == 0) {
cronJobStop("Cron: is not enabled -- Quitting..");
}
// The demo sends no email - what was queued is cancelled, and still shows in Maintenance > Mail
// Queue with why (functions/demo.php)
if (demoModeOn()) {
mysqli_query($mysqli, "UPDATE email_queue SET email_status = " . MAIL_QUEUE_CANCELLED . ", email_failed_at = NOW()"
. mailQueueErrorSql("Not sent - this is the demo, which sends no email") . " WHERE email_status IN (0, 2)");
cronJobStop("Demo - no email is sent");
}
// Development mode sends every email to the test inbox (sendQueueEmail()) - with none set in
// config.php, what was queued is cancelled the same way (functions/dev_mode.php)
if (devModeOn() && devModeMailTo() === '') {
mysqli_query($mysqli, "UPDATE email_queue SET email_status = " . MAIL_QUEUE_CANCELLED . ", email_failed_at = NOW()"
. mailQueueErrorSql("Not sent - development mode, with no test inbox in config.php") . " WHERE email_status IN (0, 2)");
cronJobStop("Development mode with no test inbox - no email is sent");
}
// Nothing to send through isn't an error either - an App Logs entry every minute buried the real ones
if (empty($config_smtp_provider)) {
cronJobStop("No mail server is set up to send through - see Admin > Settings > Mail");
}
/** =======================================================================
* Mail OAuth helpers + sender function
* ======================================================================= */
function tokenIsExpired(?string $expires_at): bool {
if (empty($expires_at)) {
return true;
}
$ts = strtotime($expires_at);
if ($ts === false) {
return true;
}
return ($ts - 60) <= time();
}
function persistMailOauthTokens(string $access_token, string $expires_at, ?string $refresh_token = null): void {
global $mysqli;
$access_token_esc = mysqli_real_escape_string($mysqli, $access_token);
$expires_at_esc = mysqli_real_escape_string($mysqli, $expires_at);
$refresh_sql = '';
if (!empty($refresh_token)) {
$refresh_token_esc = mysqli_real_escape_string($mysqli, $refresh_token);
$refresh_sql = ", config_mail_oauth_refresh_token = '{$refresh_token_esc}'";
}
mysqli_query($mysqli, "UPDATE settings SET config_mail_oauth_access_token = '{$access_token_esc}', config_mail_oauth_access_token_expires_at = '{$expires_at_esc}'{$refresh_sql} WHERE company_id = 1");
// This run's copy too, so the next email uses the new token rather than fetching another
$GLOBALS['config_mail_oauth_access_token'] = $access_token;
$GLOBALS['config_mail_oauth_access_token_expires_at'] = $expires_at;
if (!empty($refresh_token)) {
$GLOBALS['config_mail_oauth_refresh_token'] = $refresh_token;
}
}
function refreshMailOauthAccessToken(string $provider, string $oauth_client_id, string $oauth_client_secret, string $oauth_tenant_id, string $oauth_refresh_token): ?array {
$result = null;
$response = null;
if (!empty($oauth_client_id) && !empty($oauth_client_secret) && !empty($oauth_refresh_token)) {
if ($provider === 'google_oauth') {
$response = httpFormPost(GOOGLE_OAUTH_TOKEN_URL, [
'client_id' => $oauth_client_id,
'client_secret' => $oauth_client_secret,
'refresh_token' => $oauth_refresh_token,
'grant_type' => 'refresh_token',
]);
} elseif ($provider === 'microsoft_oauth' && !empty($oauth_tenant_id)) {
$token_url = MICROSOFT_OAUTH_BASE_URL . rawurlencode($oauth_tenant_id) . "/oauth2/v2.0/token";
$response = httpFormPost($token_url, [
'client_id' => $oauth_client_id,
'client_secret' => $oauth_client_secret,
'refresh_token' => $oauth_refresh_token,
'grant_type' => 'refresh_token',
'scope' => MAIL_MICROSOFT_EXCHANGE_SCOPE, // the refresh token may last have been renewed for Graph (functions/mail_graph.php)
]);
}
}
if (is_array($response) && !empty($response['ok'])) {
$json = json_decode($response['body'], true);
if (is_array($json) && !empty($json['access_token'])) {
$expires_at = date('Y-m-d H:i:s', time() + (int)($json['expires_in'] ?? 3600));
$result = [
'access_token' => $json['access_token'],
'expires_at' => $expires_at,
'refresh_token' => $json['refresh_token'] ?? null,
];
}
}
return $result;
}
function resolveMailOauthAccessToken(string $provider, 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 {
if (!empty($oauth_access_token) && !tokenIsExpired($oauth_access_token_expires_at)) {
return $oauth_access_token;
}
$tokens = refreshMailOauthAccessToken($provider, $oauth_client_id, $oauth_client_secret, $oauth_tenant_id, $oauth_refresh_token);
if (!is_array($tokens) || empty($tokens['access_token']) || empty($tokens['expires_at'])) {
return null;
}
persistMailOauthTokens($tokens['access_token'], $tokens['expires_at'], $tokens['refresh_token'] ?? null);
return $tokens['access_token'];
}
/** =======================================================================
* 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'] ?? ''), 'code_ex' => trim((string) ($error['smtp_code_ex'] ?? '')),
'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);
// Development mode: to the test inbox instead, its real recipients at the front of the subject (functions/dev_mode.php)
if (devModeOn()) {
$subject = '[DEV to ' . $to_email . ($cc ? ', cc ' . implode(', ', array_column($cc, 'email')) : '') . '] ' . $subject;
$to_email = devModeMailTo();
$to_name = '';
$cc = [];
}
// 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->setFrom($from_email, $from_name);
$mail->addAddress($to_email, $to_name);
foreach ($cc as $person) {
$mail->addCC($person['email'], $person['name']);
}
$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
// Microsoft Graph as a draft goes without the last two (mailGraphSendLarge()) - its subject still finds the ticket
foreach ($headers as $name => $value) {
if ($name === 'Message-ID') {
$mail->MessageID = $value;
} else {
$mail->addCustomHeader($name, $value);
}
}
// 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;
} 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.
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']));
} else {
$mail->addAttachment($attachment_path, basename($attachment['name']));
}
}
}
}
$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
$error = $smtp->getError();
$detail = trim(preg_replace('/\s+/', ' ', (string) ($error['detail'] ?? '')));
if ($detail !== '' && strpos($e->getMessage(), $detail) === false) {
$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 ['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);
}
/** =======================================================================
* RECOVER: status = 1 (Sending) left behind by a run that died
*
* Nothing else in the codebase ever selects status 1, so without this a row
* claimed by a run that was killed mid-send stays 'Sending' forever and is never
* 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 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
* never arrives is not.
* ======================================================================= */
mysqli_query($mysqli, "UPDATE email_queue SET email_status = 2, email_failed_at = NOW(), email_attempts = email_attempts + 1"
. mailQueueErrorSql('The run sending it stopped part-way through, so it is tried again') . " WHERE email_status = 1");
$orphaned_emails = mysqli_affected_rows($mysqli);
if ($orphaned_emails > 0) {
logApp("Cron-Mail-Queue", "warning", "Recovered $orphaned_emails email(s) left in a sending state by a previous run - queued for retry.");
}
/** =======================================================================
* SEND: what is due - waiting (status 0) and failed ones whose wait is over (status 2) - at most the
* pace a minute (mailQueuePerMinute()): a password link, an invite or a shared login first, as someone
* is waiting for it, 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, ' : '') . (mailQueueHasSensitive() ? 'email_sensitive DESC, ' : '');
$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 (" . mailQueueRetryingSql() . " AND " . mailQueueRetryDueSql() . ")
ORDER BY {$bulk_order}email_queued_at, email_id LIMIT $per_minute");
$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;
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 = $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;
}
// Who the mail server said doesn't exist (mailQueueRefusedForGood()) - their contacts show Email bounced (functions/contact_bounce.php),
// and no email to them is tried again. Turned away for any other reason, it is tried again
$for_good = array_filter($result['refused'], function ($why) {
return mailQueueRefusedForGood($why['code'], $why['code_ex'] ?? '', $why['detail']);
});
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']) {
$temporary_in_a_row = 0;
// 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. About the addresses, not the server
$temporary_in_a_row = 0;
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. Two in a row is the server - a relay that won't send for ITFlow, a quota -
// and the rest wait for the next minute, the admins told (below)
$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 (++$temporary_in_a_row >= 2) {
$run['stopped'] = 'The mail server turned away two emails in a row - the rest wait for the next minute. It said: ' . mailQueueErrorText($why);
$run['stopped_soft'] = true;
break;
}
}
}
if ($mailer !== null && $mailer['graph'] === null) {
$mailer['mail']->smtpClose();
}
/** =======================================================================
* 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);
}