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) . '?='; } }