add configurable SMTP mail delivery

Add a core SMTP mailer with configurable transport, authentication, and sender settings. Route form confirmation and admin notifications through the core mailer, and add tests for SMTP delivery, failure cases, and finisher integration.
This commit is contained in:
2026-11-24 11:48:31 +01:00
parent c507618b90
commit dfe1e40e58
6 changed files with 592 additions and 11 deletions
+298
View File
@@ -0,0 +1,298 @@
<?php
namespace Plugi\Core;
class Mailer
{
private array $config;
public function __construct(?array $config = null)
{
if ($config === null) {
$configuredMail = function_exists('phpb_config') ? phpb_config('mail') : null;
$config = is_array($configuredMail) ? $configuredMail : [];
}
$this->config = $config;
}
public function send(string $to, string $subject, string $message): bool
{
$settings = $this->validatedSettings();
if ($settings === null || !$this->isValidEmail($to) || !$this->isSafeHeader($subject) || strlen($subject) > 500) {
return false;
}
$socket = $this->connect($settings);
if (!is_resource($socket)) {
return false;
}
try {
if ($this->readResponse($socket) !== 220) {
return false;
}
if ($this->sendCommand($socket, 'EHLO localhost') !== 250) {
return false;
}
if ($settings['encryption'] === 'tls') {
if ($this->sendCommand($socket, 'STARTTLS') !== 220) {
return false;
}
if (@stream_socket_enable_crypto($socket, true, STREAM_CRYPTO_METHOD_TLS_CLIENT) !== true) {
return false;
}
if ($this->sendCommand($socket, 'EHLO localhost') !== 250) {
return false;
}
}
if ($settings['username'] !== '') {
if (!$this->authenticate($socket, $settings['username'], $settings['password'])) {
return false;
}
}
if ($this->sendCommand($socket, 'MAIL FROM:<' . $settings['from_address'] . '>') !== 250) {
return false;
}
if (!in_array($this->sendCommand($socket, 'RCPT TO:<' . $to . '>'), [250, 251], true)) {
return false;
}
if ($this->sendCommand($socket, 'DATA') !== 354) {
return false;
}
$messageData = $this->buildMessage($settings, $to, $subject, $message);
if (!$this->write($socket, $messageData)) {
return false;
}
$delivered = $this->readResponse($socket) === 250;
$this->sendCommand($socket, 'QUIT');
return $delivered;
} catch (\Throwable $exception) {
return false;
} finally {
fclose($socket);
}
}
private function validatedSettings(): ?array
{
if (($this->config['transport'] ?? null) !== 'smtp') {
return null;
}
$host = $this->config['host'] ?? null;
if (!is_string($host) || $host === '' || !$this->isValidHost($host)) {
return null;
}
$port = filter_var($this->config['port'] ?? null, FILTER_VALIDATE_INT, [
'options' => ['min_range' => 1, 'max_range' => 65535],
]);
if ($port === false) {
return null;
}
$encryption = $this->config['encryption'] ?? null;
if (!is_string($encryption) || !in_array($encryption, ['tls', 'ssl', 'none'], true)) {
return null;
}
$timeout = $this->config['timeout'] ?? null;
if ((!is_int($timeout) && !is_float($timeout) && !(is_string($timeout) && is_numeric($timeout))) || !is_finite((float) $timeout) || (float) $timeout <= 0 || (float) $timeout > 300) {
return null;
}
$fromAddress = $this->config['from_address'] ?? null;
if (!is_string($fromAddress) || !$this->isValidEmail($fromAddress)) {
return null;
}
$fromName = $this->config['from_name'] ?? '';
if (!is_string($fromName) || !$this->isSafeHeader($fromName) || strlen($fromName) > 500) {
return null;
}
$username = $this->config['username'] ?? '';
$password = $this->config['password'] ?? '';
if (!is_string($username) || !is_string($password) || (($username === '') !== ($password === '')) || strlen($username) > 250 || strlen($password) > 250) {
return null;
}
if ($username !== '' && strlen(base64_encode("\0" . $username . "\0" . $password)) > 500) {
return null;
}
return [
'host' => $host,
'port' => (int) $port,
'encryption' => $encryption,
'timeout' => (float) $timeout,
'username' => $username,
'password' => $password,
'from_address' => $fromAddress,
'from_name' => $fromName,
];
}
private function isValidHost(string $host): bool
{
if (filter_var($host, FILTER_VALIDATE_IP) !== false) {
return true;
}
return preg_match('/\A(?=.{1,253}\z)(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)(?:\.(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?))*\z/', $host) === 1;
}
private function isValidEmail(string $address): bool
{
return filter_var($address, FILTER_VALIDATE_EMAIL) !== false && preg_match('/[\r\n\x00-\x1F\x7F]/', $address) !== 1;
}
private function isSafeHeader(string $value): bool
{
return preg_match('/[\r\n\x00-\x1F\x7F]/', $value) !== 1 && preg_match('//u', $value) === 1;
}
private function connect(array $settings)
{
$host = $settings['host'];
$socketHost = filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false ? '[' . $host . ']' : $host;
$scheme = $settings['encryption'] === 'ssl' ? 'ssl' : 'tcp';
$target = $scheme . '://' . $socketHost . ':' . $settings['port'];
$context = stream_context_create([
'ssl' => [
'verify_peer' => true,
'verify_peer_name' => true,
'peer_name' => $host,
'SNI_enabled' => true,
],
]);
$errno = 0;
$error = '';
$socket = @stream_socket_client(
$target,
$errno,
$error,
$settings['timeout'],
STREAM_CLIENT_CONNECT,
$context
);
if (is_resource($socket)) {
$seconds = (int) floor($settings['timeout']);
$microseconds = (int) ceil(($settings['timeout'] - $seconds) * 1000000);
if ($microseconds === 1000000) {
$seconds++;
$microseconds = 0;
}
stream_set_timeout($socket, $seconds, $microseconds);
}
return $socket;
}
private function authenticate($socket, string $username, string $password): bool
{
$response = $this->sendCommand($socket, 'AUTH PLAIN');
if ($response === 235) {
return true;
}
if ($response !== 334) {
return false;
}
$credentials = base64_encode("\0" . $username . "\0" . $password);
return $this->writeLine($socket, $credentials) && $this->readResponse($socket) === 235;
}
private function sendCommand($socket, string $command): ?int
{
if (!$this->writeLine($socket, $command)) {
return null;
}
return $this->readResponse($socket);
}
private function writeLine($socket, string $line): bool
{
if (strlen($line) > 510 || preg_match('/[\r\n\x00-\x1F\x7F]/', $line) === 1) {
return false;
}
return $this->write($socket, $line . "\r\n");
}
private function write($socket, string $data): bool
{
$length = strlen($data);
$written = 0;
while ($written < $length) {
$count = @fwrite($socket, substr($data, $written));
if ($count === false || $count === 0) {
return false;
}
$written += $count;
}
return true;
}
private function readResponse($socket): ?int
{
$responseCode = null;
for ($lineNumber = 0; $lineNumber < 100; $lineNumber++) {
$line = @fgets($socket, 515);
if (!is_string($line) || !str_ends_with($line, "\r\n") || strlen($line) > 512 || preg_match('/\A([0-9]{3})([ -])/', $line, $matches) !== 1) {
return null;
}
$code = (int) $matches[1];
if ($responseCode !== null && $responseCode !== $code) {
return null;
}
$responseCode = $code;
if ($matches[2] === ' ') {
return $responseCode;
}
}
return null;
}
private function buildMessage(array $settings, string $to, string $subject, string $message): string
{
$from = $settings['from_name'] === ''
? '<' . $settings['from_address'] . '>'
: $this->encodeHeader($settings['from_name']) . ' <' . $settings['from_address'] . '>';
$headers = [
'From: ' . $from,
'To: ' . $to,
'Subject: ' . $this->encodeHeader($subject),
'MIME-Version: 1.0',
'Content-Type: text/plain; charset=UTF-8',
'Content-Transfer-Encoding: quoted-printable',
];
$normalizedMessage = str_replace(["\r\n", "\r"], "\n", $message);
$encodedMessage = str_replace(["\r\n", "\r"], "\n", quoted_printable_encode(str_replace("\n", "\r\n", $normalizedMessage)));
$messageLines = explode("\n", $encodedMessage);
foreach ($messageLines as &$line) {
if (str_starts_with($line, '.')) {
$line = '.' . $line;
}
}
unset($line);
return implode("\r\n", $headers) . "\r\n\r\n" . implode("\r\n", $messageLines) . "\r\n.\r\n";
}
private function encodeHeader(string $value): string
{
return '=?UTF-8?B?' . base64_encode($value) . '?=';
}
}
+186
View File
@@ -0,0 +1,186 @@
<?php
require_once dirname(__DIR__) . '/src/Core/Mailer.php';
use Plugi\Core\Mailer;
function assertMailerSame($expected, $actual, string $message): void
{
if ($expected !== $actual) {
throw new RuntimeException($message . ': expected ' . var_export($expected, true) . ', got ' . var_export($actual, true));
}
}
function smtpReadLine($socket): ?string
{
$line = fgets($socket, 2048);
return is_string($line) && str_ends_with($line, "\r\n") ? substr($line, 0, -2) : null;
}
function smtpReply($socket, string $reply): bool
{
return fwrite($socket, $reply . "\r\n") === strlen($reply) + 2;
}
function runSmtpPeer(array $scenario): array
{
$server = stream_socket_server('tcp://127.0.0.1:0', $errorCode, $errorMessage);
if (!is_resource($server)) {
throw new RuntimeException('Could not start the local SMTP test peer.');
}
$address = stream_socket_get_name($server, false);
$port = (int) substr(strrchr($address, ':'), 1);
$pid = pcntl_fork();
if ($pid === -1) {
fclose($server);
throw new RuntimeException('Could not start the local SMTP test peer process.');
}
if ($pid === 0) {
$client = stream_socket_accept($server, 5);
fclose($server);
if (!is_resource($client)) {
exit(1);
}
stream_set_timeout($client, 5);
$passed = smtpReply($client, '220 local.test ESMTP');
$passed = $passed && smtpReadLine($client) === 'EHLO localhost' && smtpReply($client, '250 local.test');
if ($passed && !empty($scenario['auth'])) {
$passed = smtpReadLine($client) === 'AUTH PLAIN' && smtpReply($client, '334 ');
$credentials = smtpReadLine($client);
$expectedCredentials = base64_encode("\0test-user\0test-password");
if ($passed && empty($scenario['reject_auth'])) {
$passed = $credentials === $expectedCredentials && smtpReply($client, '235 authenticated');
} elseif ($passed) {
$passed = $credentials === $expectedCredentials && smtpReply($client, '535 authentication rejected');
$passed = $passed && smtpReadLine($client) === null;
fclose($client);
exit($passed ? 0 : 1);
}
}
if ($passed) {
$passed = smtpReadLine($client) === 'MAIL FROM:<sender@example.test>' && smtpReply($client, '250 sender accepted');
}
if ($passed) {
$passed = smtpReadLine($client) === 'RCPT TO:<recipient@example.test>';
if ($passed && !empty($scenario['reject_recipient'])) {
$passed = smtpReply($client, '550 recipient rejected') && smtpReadLine($client) === null;
fclose($client);
exit($passed ? 0 : 1);
}
$passed = $passed && smtpReply($client, '250 recipient accepted');
}
if ($passed) {
$passed = smtpReadLine($client) === 'DATA' && smtpReply($client, '354 send message');
}
$data = '';
if ($passed) {
$terminated = false;
while (($line = smtpReadLine($client)) !== null) {
if ($line === '.') {
$terminated = true;
break;
}
$data .= $line . "\r\n";
}
$passed = $terminated
&& str_contains($data, 'From: =?UTF-8?B?UGx1Z2kgVGVzdA==?= <sender@example.test>')
&& str_contains($data, 'To: recipient@example.test')
&& str_contains($data, 'Subject: =?UTF-8?B?U3RhdHVzIHVwZGF0ZQ==?=')
&& str_contains($data, "..leading dot\r\n");
}
if ($passed) {
$reply = !empty($scenario['reject_message']) ? '554 message rejected' : '250 message accepted';
$passed = smtpReply($client, $reply) && smtpReadLine($client) === 'QUIT' && smtpReply($client, '221 closing');
}
fclose($client);
exit($passed ? 0 : 1);
}
fclose($server);
$config = [
'transport' => 'smtp',
'host' => '127.0.0.1',
'port' => $port,
'encryption' => 'none',
'username' => !empty($scenario['auth']) ? 'test-user' : '',
'password' => !empty($scenario['auth']) ? 'test-password' : '',
'from_address' => 'sender@example.test',
'from_name' => 'Plugi Test',
'timeout' => 3,
];
$result = (new Mailer($config))->send('recipient@example.test', 'Status update', "First line\r\n.leading dot\r\nLast line");
pcntl_waitpid($pid, $status);
if (!pcntl_wifexited($status) || pcntl_wexitstatus($status) !== 0) {
throw new RuntimeException('The scripted SMTP peer observed an unexpected protocol exchange.');
}
return [$result, $config];
}
function baseMailerConfig(): array
{
return [
'transport' => 'smtp',
'host' => '127.0.0.1',
'port' => 587,
'encryption' => 'tls',
'username' => '',
'password' => '',
'from_address' => 'sender@example.test',
'from_name' => 'Plugi Test',
'timeout' => 1,
];
}
[$success, $config] = runSmtpPeer(['auth' => true]);
assertMailerSame(true, $success, 'Authenticated SMTP delivery must succeed');
[$authFailure] = runSmtpPeer(['auth' => true, 'reject_auth' => true]);
assertMailerSame(false, $authFailure, 'Rejected SMTP authentication must fail');
[$recipientFailure] = runSmtpPeer(['reject_recipient' => true]);
assertMailerSame(false, $recipientFailure, 'A rejected SMTP recipient must fail');
[$messageFailure] = runSmtpPeer(['reject_message' => true]);
assertMailerSame(false, $messageFailure, 'A rejected SMTP message must fail');
$invalidConfig = baseMailerConfig();
$invalidConfig['host'] = '';
assertMailerSame(false, (new Mailer($invalidConfig))->send('recipient@example.test', 'Subject', 'Body'), 'Incomplete SMTP configuration must fail safely');
$invalidConfig = baseMailerConfig();
$invalidConfig['username'] = 'only-a-username';
assertMailerSame(false, (new Mailer($invalidConfig))->send('recipient@example.test', 'Subject', 'Body'), 'Incomplete SMTP authentication settings must fail safely');
assertMailerSame(false, (new Mailer(baseMailerConfig()))->send('not-an-email', 'Subject', 'Body'), 'Invalid recipients must fail safely');
assertMailerSame(false, (new Mailer(baseMailerConfig()))->send('recipient@example.test', "Subject\r\nBcc: other@example.test", 'Body'), 'Header injection must fail safely');
$unavailableServer = stream_socket_server('tcp://127.0.0.1:0', $errorCode, $errorMessage);
if (!is_resource($unavailableServer)) {
throw new RuntimeException('Could not allocate a port for the SMTP connection-failure check.');
}
$unavailableAddress = stream_socket_get_name($unavailableServer, false);
$unavailablePort = (int) substr(strrchr($unavailableAddress, ':'), 1);
fclose($unavailableServer);
$unavailableConfig = baseMailerConfig();
$unavailableConfig['host'] = '127.0.0.1';
$unavailableConfig['port'] = $unavailablePort;
$unavailableConfig['encryption'] = 'none';
assertMailerSame(false, (new Mailer($unavailableConfig))->send('recipient@example.test', 'Subject', 'Body'), 'Connection refusal must fail safely');
$rootConfig = require dirname(__DIR__, 2) . '/config.php';
$templateConfig = require dirname(__DIR__, 2) . '/config.dist.php';
$mailKeys = ['class', 'transport', 'host', 'port', 'encryption', 'username', 'password', 'from_address', 'from_name', 'timeout'];
assertMailerSame($mailKeys, array_keys($rootConfig['mail']), 'Root SMTP settings must expose the documented keys');
assertMailerSame($mailKeys, array_keys($templateConfig['mail']), 'Template SMTP settings must expose the documented keys');
assertMailerSame(Plugi\Core\Mailer::class, $rootConfig['mail']['class'], 'Root configuration must select the core mailer');
assertMailerSame('', $templateConfig['mail']['username'], 'Template SMTP username must not contain credentials');
assertMailerSame('', $templateConfig['mail']['password'], 'Template SMTP password must not contain credentials');
fwrite(STDOUT, "Mailer tests passed.\n");