SendMail via SMTP

This commit is contained in:
Flatlogic Bot 2026-04-12 08:05:33 +00:00
parent 6d14698c6c
commit f46cba2560

View File

@ -15,14 +15,21 @@ class MailService
$cfg = self::loadConfig();
$transport = strtolower((string)($cfg['transport'] ?? 'smtp'));
if ($transport === 'smtp') {
if (!self::ensurePHPMailerLoaded()) {
return [ 'success' => false, 'error' => 'PHPMailer not available for SMTP transport' ];
}
return self::sendSmtpMail($cfg, $to, $subject, $htmlBody, $textBody, $opts);
if ($transport !== 'smtp') {
return [
'success' => false,
'error' => 'MAIL_TRANSPORT must be set to smtp. Native mail() transport is disabled.',
];
}
return self::sendNativeMail($cfg, $to, $subject, $htmlBody, $textBody, $opts);
if (!self::ensurePHPMailerLoaded()) {
return [
'success' => false,
'error' => 'SMTP transport requires PHPMailer. Install it via Composer or make the system PHPMailer package available in include_path.',
];
}
return self::sendSmtpMail($cfg, $to, $subject, $htmlBody, $textBody, $opts);
}
private static function loadConfig(): array
@ -116,6 +123,25 @@ class MailService
return null;
}
private static function validateSmtpConfig(array $cfg): ?string
{
$required = [
'smtp_host' => 'SMTP_HOST',
'smtp_port' => 'SMTP_PORT',
'smtp_user' => 'SMTP_USER',
'smtp_pass' => 'SMTP_PASS',
];
foreach ($required as $key => $envName) {
$value = $cfg[$key] ?? null;
if ($value === null || $value === '') {
return sprintf('Missing SMTP configuration: %s', $envName);
}
}
return null;
}
private static function buildRecipientList($to): array
{
if ($to) {
@ -137,6 +163,11 @@ class MailService
private static function sendSmtpMail(array $cfg, $to, string $subject, string $htmlBody, ?string $textBody, array $opts): array
{
$configError = self::validateSmtpConfig($cfg);
if ($configError !== null) {
return [ 'success' => false, 'error' => $configError ];
}
$mail = new PHPMailer\PHPMailer\PHPMailer(true);
try {
@ -259,30 +290,30 @@ class MailService
$headers[] = 'Bcc: ' . implode(', ', $bccList);
}
$message = "--{$boundary}
$message = "--{$boundary}
"
. "Content-Type: text/plain; charset=UTF-8
. "Content-Type: text/plain; charset=UTF-8
"
. "Content-Transfer-Encoding: 8bit
. "Content-Transfer-Encoding: 8bit
"
. $textBody . "
. $textBody . "
"
. "--{$boundary}
. "--{$boundary}
"
. "Content-Type: text/html; charset=UTF-8
. "Content-Type: text/html; charset=UTF-8
"
. "Content-Transfer-Encoding: 8bit
. "Content-Transfer-Encoding: 8bit
"
. $htmlBody . "
. $htmlBody . "
"
. "--{$boundary}--
. "--{$boundary}--
";
$ok = @mail(implode(', ', $validTo), $encodedSubject, $message, implode("
$ok = @mail(implode(', ', $validTo), $encodedSubject, $message, implode("
", $headers));
if (!$ok) {
return [ 'success' => false, 'error' => 'Native mail() failed' ];