v1.0.1
AtheraStudio Database
- <?php
- declare(strict_types=1);
-
- namespace Athera;
-
- defined('ATHERA') || exit;
-
- final class Mailer
- {
- public static string $lastError = '';
-
- public static function send(string $to, string $subject, string $body): bool
- {
- self::$lastError = '';
- $to = trim($to);
- if (!filter_var($to, FILTER_VALIDATE_EMAIL) || preg_match('/[\r\n,;]/', $to)) {
- self::$lastError = 'Invalid recipient';
- return false;
- }
- $subject = trim(preg_replace('/[\r\n\t]+/', ' ', $subject));
- $from = self::from();
- $body = str_replace(["\r\n", "\r"], "\n", $body);
- try {
- return Config::get('SMTP_HOST') !== '' ? self::smtp($to, $from, $subject, $body) : self::native($to, $from, $subject, $body);
- } catch (\Throwable $e) {
- self::$lastError = $e->getMessage();
- return false;
- }
- }
-
- private static function from(): string
- {
- $from = Config::get('MAIL_FROM');
- if (filter_var($from, FILTER_VALIDATE_EMAIL) && !preg_match('/[\r\n]/', $from)) return $from;
- $host = strtolower((string)($_SERVER['SERVER_NAME'] ?? $_SERVER['HTTP_HOST'] ?? 'localhost'));
- $host = preg_replace('/:\d+$/', '', $host);
- $host = preg_replace('/^www\./', '', $host);
- if (!preg_match('/^[a-z0-9.\-]+\.[a-z]{2,}$/', $host)) $host = 'localhost.localdomain';
- return 'no-reply@' . $host;
- }
-
- private static function headers(string $from, string $subject, bool $withSubject, string $to = ''): array
- {
- $domain = substr(strrchr($from, '@'), 1);
- $h = [
- 'Date: ' . date('r'),
- 'From: AtheraStudio Database <' . $from . '>',
- 'Message-ID: <' . bin2hex(random_bytes(12)) . '@' . $domain . '>',
- 'MIME-Version: 1.0',
- 'Content-Type: text/plain; charset=UTF-8',
- 'Content-Transfer-Encoding: base64',
- 'X-Auto-Response-Suppress: All',
- 'Auto-Submitted: auto-generated',
- ];
- if ($withSubject) {
- array_unshift($h, 'To: <' . $to . '>');
- array_unshift($h, 'Subject: ' . self::encode($subject));
- }
- return $h;
- }
-
- private static function encode(string $s): string
- {
- return preg_match('/[^\x20-\x7E]/', $s) ? '=?UTF-8?B?' . base64_encode($s) . '?=' : $s;
- }
-
- private static function native(string $to, string $from, string $subject, string $body): bool
- {
- if (!function_exists('mail')) {
- self::$lastError = 'mail() is disabled on this server';
- return false;
- }
- $headers = implode("\r\n", self::headers($from, $subject, false));
- $payload = rtrim(chunk_split(base64_encode($body), 76, "\r\n"));
- $ok = false;
- if (Config::get('MAIL_FROM') !== '') {
- $ok = @mail($to, self::encode($subject), $payload, $headers, '-f' . $from);
- }
- if (!$ok) $ok = @mail($to, self::encode($subject), $payload, $headers);
- if (!$ok) self::$lastError = 'mail() returned false';
- return $ok;
- }
-
- private static function smtp(string $to, string $from, string $subject, string $body): bool
- {
- $host = Config::get('SMTP_HOST');
- $port = Config::int('SMTP_PORT', 1, 65535);
- $secure = strtolower(Config::get('SMTP_SECURE'));
- $ctx = stream_context_create(['ssl' => ['verify_peer' => true, 'verify_peer_name' => true, 'peer_name' => $host]]);
- $target = ($secure === 'ssl' ? 'ssl://' : 'tcp://') . $host . ':' . $port;
- $s = @stream_socket_client($target, $errno, $errstr, 15, STREAM_CLIENT_CONNECT, $ctx);
- if (!$s) throw new \RuntimeException('SMTP connect failed: ' . $errstr);
- stream_set_timeout($s, 20);
- $read = function () use ($s): array {
- $text = '';
- while (($line = fgets($s, 1024)) !== false) {
- $text .= $line;
- if (strlen($line) < 4 || $line[3] !== '-') break;
- }
- return [(int)substr($text, 0, 3), trim($text)];
- };
- $cmd = function (string $c, array $ok) use ($s, $read): array {
- fwrite($s, $c . "\r\n");
- $r = $read();
- if (!in_array($r[0], $ok, true)) throw new \RuntimeException('SMTP: ' . preg_replace('/\s+/', ' ', $r[1]));
- return $r;
- };
- try {
- $r = $read();
- if ($r[0] !== 220) throw new \RuntimeException('SMTP: ' . $r[1]);
- $ehlo = preg_replace('/[^a-z0-9.\-]/i', '', (string)($_SERVER['SERVER_NAME'] ?? 'localhost')) ?: 'localhost';
- $r = $cmd('EHLO ' . $ehlo, [250]);
- if ($secure === 'tls') {
- $cmd('STARTTLS', [220]);
- if (!stream_socket_enable_crypto($s, true, STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT | (defined('STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT') ? STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT : 0))) {
- throw new \RuntimeException('SMTP: TLS negotiation failed');
- }
- $cmd('EHLO ' . $ehlo, [250]);
- }
- if (Config::get('SMTP_USER') !== '') {
- $cmd('AUTH LOGIN', [334]);
- $cmd(base64_encode(Config::get('SMTP_USER')), [334]);
- $cmd(base64_encode(Config::get('SMTP_PASS')), [235]);
- }
- $cmd('MAIL FROM:<' . $from . '>', [250]);
- $cmd('RCPT TO:<' . $to . '>', [250, 251]);
- $cmd('DATA', [354]);
- $msg = implode("\r\n", self::headers($from, $subject, true, $to)) . "\r\n\r\n" . chunk_split(base64_encode($body), 76, "\r\n");
- fwrite($s, $msg . ".\r\n");
- $r = $read();
- if ($r[0] !== 250) throw new \RuntimeException('SMTP: ' . $r[1]);
- fwrite($s, "QUIT\r\n");
- return true;
- } finally {
- fclose($s);
- }
- }
- }
-