initial commit

This commit is contained in:
rsgrinko committed 2026-09-12 23:55:44 +03:00
commit 3f64f4a49a
221 files changed
+26665

No files matched your search

@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Mail\Drivers;
use Rsgrinko\Proton\Mail\Message;
/**
* Способ доставки письма. Новый драйвер — класс с этими двумя методами
* и строка в реестре Mail::DRIVERS (либо подмена через событие mail.driver).
*/
interface DriverInterface
{
/**
* Отправляет письмо. Не смог — бросает исключение: молча терять письмо нельзя.
*/
public function send(Message $message): void;
/**
* Короткое имя для логов и страницы состояния.
*/
public function name(): string;
}
+36
View File
@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Mail\Drivers;
use Rsgrinko\Proton\Mail\Message;
use Rsgrinko\Proton\Mail\Mime;
use Rsgrinko\Proton\Support\Config;
/**
* Письмо не уходит никуда, а сохраняется файлом .eml в var/log/mail.
*
* Режим для разработки: письмо со ссылкой подтверждения можно открыть в любом
* почтовом клиенте и нажать кнопку, ничего никому не отправив.
*/
final class LogDriver implements DriverInterface
{
public function send(Message $message): void
{
$dir = (string) Config::get('paths.log', APP_ROOT . '/var/log') . '/mail';
if (!is_dir($dir)) {
@mkdir($dir, 0775, true);
}
$name = date('Ymd-His') . '-' . bin2hex(random_bytes(4)) . '.eml';
@file_put_contents($dir . '/' . $name, Mime::build($message));
}
public function name(): string
{
return 'log';
}
}
+60
View File
@@ -0,0 +1,60 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Mail\Drivers;
use Rsgrinko\Proton\Mail\Message;
use Rsgrinko\Proton\Mail\Mime;
use Rsgrinko\Proton\Support\ProtonException;
/**
* Отправка через встроенную функцию mail() — то есть через sendmail хостинга.
*
* Драйвер по умолчанию: работает везде и не требует настроек. Очереди и повторов
* у него нет, ошибку он показывает одним булевым значением — для рабочего проекта
* лучше SMTP или почтовый сервис, но для старта этого достаточно.
*/
final class MailDriver implements DriverInterface
{
public function send(Message $message): void
{
$body = Mime::body($message);
$headers = array_merge(Mime::headers($message, false), $body['headers']);
// Получателей mail() принимает отдельным аргументом, в заголовках их быть
// не должно — иначе адресат увидит себя дважды
if ($message->copies() !== []) {
$headers['Cc'] = implode(', ', $message->copies());
}
if ($message->blindCopies() !== []) {
$headers['Bcc'] = implode(', ', $message->blindCopies());
}
$lines = [];
foreach ($headers as $name => $value) {
$lines[] = $name . ': ' . $value;
}
// Пятый аргумент задаёт обратный адрес конверта: без него письма уходят
// от пользователя веб-сервера и часто попадают в спам
$sent = @mail(
implode(', ', $message->recipients()),
Mime::encodeHeader($message->subjectLine()),
$body['body'],
implode("\r\n", $lines),
'-f' . $message->senderEmail()
);
if (!$sent) {
throw new ProtonException('Функция mail() не приняла письмо. Проверьте sendmail_path в php.ini');
}
}
public function name(): string
{
return 'mail';
}
}
@@ -0,0 +1,138 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Mail\Drivers;
use Rsgrinko\Proton\Mail\Message;
use Rsgrinko\Proton\Support\Config;
use Rsgrinko\Proton\Support\ProtonException;
use Rsgrinko\Proton\Support\RequestId;
/**
* Отправка через внешний почтовый сервис по HTTP API.
*
* Письмо уходит одним запросом POST /api/v1/messages с ключом проекта в
* заголовке Authorization. Очередь, повторы, стоп-лист, DKIM и отчёты о доставке
* остаются на стороне сервиса — приложению нужно только отдать письмо.
*
* Адрес и ключ задаются настройками MAIL_SERVICE_URL и MAIL_SERVICE_KEY.
* curl не обязателен: если расширения нет, запрос уходит потоками.
*/
final class MailerServiceDriver implements DriverInterface
{
public function send(Message $message): void
{
$url = rtrim((string) Config::get('mail.service.url', ''), '/');
$key = (string) Config::get('mail.service.key', '');
if ($url === '' || $key === '') {
throw new ProtonException('Для драйвера mailer нужны MAIL_SERVICE_URL и MAIL_SERVICE_KEY');
}
$payload = $message->toArray();
// Сервис ждёт получателей строкой или списком — отдаём список,
// а пустые поля не шлём вовсе, чтобы не спорить с его валидацией
$body = array_filter([
'to' => $payload['to'],
'cc' => $payload['cc'],
'bcc' => $payload['bcc'],
'from' => $payload['from'],
'from_name' => $payload['from_name'],
'reply_to' => $payload['reply_to'],
'subject' => $payload['subject'],
'text' => $payload['text'],
'html' => $payload['html'],
'headers' => $payload['headers'],
'attachments' => $payload['attachments'],
], static fn (mixed $value): bool => $value !== '' && $value !== []);
$response = $this->post(
$url . '/api/v1/messages',
(string) json_encode($body, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
[
'Content-Type: application/json',
'Authorization: Bearer ' . $key,
// Своя цепочка запросов доезжает до сервиса и находится в его логах
RequestId::HEADER . ': ' . RequestId::current(),
]
);
if ($response['status'] < 200 || $response['status'] >= 300) {
$decoded = json_decode($response['body'], true);
$detail = is_array($decoded) ? (string) ($decoded['error']['message'] ?? '') : '';
throw new ProtonException(
'Почтовый сервис ответил ' . $response['status']
. ($detail !== '' ? ': ' . $detail : '')
);
}
}
public function name(): string
{
return 'mailer';
}
/**
* @param array<int, string> $headers
*
* @return array{status: int, body: string}
*/
private function post(string $url, string $body, array $headers): array
{
$timeout = max(2, (int) Config::get('mail.service.timeout', 10));
if (function_exists('curl_init')) {
$curl = curl_init($url);
curl_setopt_array($curl, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $body,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => $timeout,
]);
$response = curl_exec($curl);
$status = (int) curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
$error = curl_error($curl);
curl_close($curl);
if ($response === false) {
throw new ProtonException('Почтовый сервис недоступен: ' . $error);
}
return ['status' => $status, 'body' => (string) $response];
}
$context = stream_context_create([
'http' => [
'method' => 'POST',
'header' => implode("\r\n", $headers),
'content' => $body,
'timeout' => $timeout,
// Нужен ответ, а не исключение: код разбираем сами
'ignore_errors' => true,
],
]);
$response = @file_get_contents($url, false, $context);
if ($response === false) {
throw new ProtonException('Почтовый сервис недоступен: ' . $url);
}
$status = 0;
foreach ($http_response_header ?? [] as $header) {
if (preg_match('#^HTTP/\S+\s+(\d{3})#', $header, $matches) === 1) {
$status = (int) $matches[1];
}
}
return ['status' => $status, 'body' => $response];
}
}
+24
View File
@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Mail\Drivers;
use Rsgrinko\Proton\Mail\Message;
/**
* Заглушка: письмо никуда не идёт и нигде не сохраняется.
* Нужна тестам — проверить, что письмо собралось, можно через Mail::sent().
*/
final class NullDriver implements DriverInterface
{
public function send(Message $message): void
{
// Ничего не делаем: письмо считается отправленным
}
public function name(): string
{
return 'null';
}
}
+259
View File
@@ -0,0 +1,259 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Mail\Drivers;
use Rsgrinko\Proton\Mail\Message;
use Rsgrinko\Proton\Mail\Mime;
use Rsgrinko\Proton\Support\Config;
use Rsgrinko\Proton\Support\ProtonException;
/**
* Свой SMTP-клиент на потоках: ни composer, ни расширений, кроме openssl.
*
* Понимает голое соединение, SSL (порт 465) и STARTTLS (587), вход LOGIN и PLAIN —
* выбирается тот способ, который сервер объявил в ответе на EHLO. Соединение
* живёт от письма к письму: перед каждым следующим идёт RSET, он же проверка,
* что сервер не закрыл связь.
*/
final class SmtpDriver implements DriverInterface
{
/** @var resource|null */
private $socket = null;
/** @var array<int, string> Что сервер объявил в ответе на EHLO */
private array $capabilities = [];
private int $sentInSession = 0;
public function send(Message $message): void
{
$this->connect();
try {
$this->deliver($message);
} catch (ProtonException $e) {
// Сессию после ошибки не переиспользуем: состояние диалога уже неясно
$this->close();
throw $e;
}
$this->sentInSession++;
$limit = (int) Config::get('mail.smtp.session_limit', 100);
if ($limit > 0 && $this->sentInSession >= $limit) {
$this->close();
}
}
public function name(): string
{
return 'smtp';
}
public function __destruct()
{
$this->close();
}
/**
* Закрывает сессию — воркер зовёт это, когда очередь опустела.
*/
public function close(): void
{
if (is_resource($this->socket)) {
@fwrite($this->socket, "QUIT\r\n");
@fclose($this->socket);
}
$this->socket = null;
$this->capabilities = [];
$this->sentInSession = 0;
}
private function deliver(Message $message): void
{
$this->command('MAIL FROM:<' . $this->assertAddress($message->senderEmail()) . '>', [250]);
foreach ($message->envelopeRecipients() as $recipient) {
$this->command('RCPT TO:<' . $this->assertAddress($recipient) . '>', [250, 251]);
}
$this->command('DATA', [354]);
// Точка в начале строки — конец письма для SMTP, поэтому её удваивают
$body = preg_replace('/^\./m', '..', Mime::build($message)) ?? '';
$this->write($body . "\r\n.\r\n");
$this->expect([250]);
}
/**
* Поднимает соединение, если его ещё нет или сервер его закрыл.
*/
private function connect(): void
{
if (is_resource($this->socket)) {
// RSET заодно проверяет, жива ли связь
try {
$this->command('RSET', [250]);
return;
} catch (ProtonException) {
$this->close();
}
}
$host = (string) Config::get('mail.smtp.host', '127.0.0.1');
$port = (int) Config::get('mail.smtp.port', 25);
$encryption = strtolower((string) Config::get('mail.smtp.encryption', ''));
$timeout = max(5, (int) Config::get('mail.smtp.timeout', 30));
$address = ($encryption === 'ssl' ? 'ssl://' : 'tcp://') . $host . ':' . $port;
$context = stream_context_create([
'ssl' => [
'verify_peer' => (bool) Config::get('mail.smtp.verify_peer', true),
'verify_peer_name' => (bool) Config::get('mail.smtp.verify_peer', true),
'allow_self_signed' => !(bool) Config::get('mail.smtp.verify_peer', true),
],
]);
$socket = @stream_socket_client($address, $code, $error, $timeout, STREAM_CLIENT_CONNECT, $context);
if ($socket === false) {
throw new ProtonException('Не удалось подключиться к SMTP ' . $address . ': ' . $error . ' (' . $code . ')');
}
stream_set_timeout($socket, $timeout);
$this->socket = $socket;
$this->expect([220]);
$this->hello();
if ($encryption === 'tls') {
$this->command('STARTTLS', [220]);
if (!@stream_socket_enable_crypto($socket, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
$last = error_get_last();
$this->close();
// Причина обычно не в сервере, а в самом PHP: не собран openssl.cafile
throw new ProtonException('Не удалось установить TLS: ' . (string) ($last['message'] ?? 'причина неизвестна'));
}
// После STARTTLS список возможностей объявляется заново
$this->hello();
}
$this->authenticate();
}
private function hello(): void
{
$name = (string) Config::get('mail.smtp.helo', '') ?: (string) (gethostname() ?: 'localhost');
$response = $this->command('EHLO ' . $name, [250], true);
$this->capabilities = array_map('strtoupper', explode("\n", $response));
}
private function authenticate(): void
{
$user = (string) Config::get('mail.smtp.username', '');
$password = (string) Config::get('mail.smtp.password', '');
if ($user === '') {
return;
}
$supports = static fn (array $lines, string $needle): bool => array_filter(
$lines,
static fn (string $line): bool => str_contains($line, $needle)
) !== [];
if ($supports($this->capabilities, 'AUTH') && $supports($this->capabilities, 'PLAIN')) {
$this->command('AUTH PLAIN ' . base64_encode("\0" . $user . "\0" . $password), [235]);
return;
}
$this->command('AUTH LOGIN', [334]);
$this->command(base64_encode($user), [334]);
$this->command(base64_encode($password), [235]);
}
/**
* Отправляет команду и проверяет код ответа.
*
* @param array<int, int> $expected
*/
private function command(string $command, array $expected, bool $multiline = false): string
{
$this->write($command . "\r\n");
return $this->expect($expected, $multiline);
}
private function write(string $data): void
{
if (!is_resource($this->socket) || @fwrite($this->socket, $data) === false) {
throw new ProtonException('Соединение с SMTP-сервером потеряно');
}
}
/**
* Читает ответ сервера и сверяет код.
*
* @param array<int, int> $expected
*/
private function expect(array $expected, bool $multiline = false): string
{
if (!is_resource($this->socket)) {
throw new ProtonException('Соединение с SMTP-сервером не открыто');
}
$lines = [];
do {
$line = fgets($this->socket, 1024);
if ($line === false) {
throw new ProtonException('SMTP-сервер закрыл соединение');
}
$lines[] = trim($line);
// Многострочный ответ: у всех строк, кроме последней, после кода стоит дефис
$more = strlen($line) > 3 && $line[3] === '-';
} while ($more);
$last = end($lines) ?: '';
$code = (int) substr($last, 0, 3);
if (!in_array($code, $expected, true)) {
throw new ProtonException('SMTP ответил «' . $last . '», ожидался код ' . implode(' или ', $expected));
}
return $multiline ? implode("\n", $lines) : $last;
}
/**
* Адрес конверта не должен содержать пробелов, скобок и управляющих символов:
* иначе в команду SMTP уезжает вторая строка.
*/
private function assertAddress(string $address): string
{
$address = trim($address);
if ($address === '' || preg_match('/^[^\s<>(),;:"\\\\\x00-\x1f]+@[^\s<>(),;:"\\\\\x00-\x1f]+$/', $address) !== 1) {
throw new ProtonException('Недопустимый адрес для SMTP: ' . $address);
}
return $address;
}
}
+165
View File
@@ -0,0 +1,165 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Mail;
use Rsgrinko\Proton\Events\Events;
use Rsgrinko\Proton\Mail\Drivers\DriverInterface;
use Rsgrinko\Proton\Mail\Drivers\LogDriver;
use Rsgrinko\Proton\Mail\Drivers\MailDriver;
use Rsgrinko\Proton\Mail\Drivers\MailerServiceDriver;
use Rsgrinko\Proton\Mail\Drivers\NullDriver;
use Rsgrinko\Proton\Mail\Drivers\SmtpDriver;
use Rsgrinko\Proton\Queue\Queue;
use Rsgrinko\Proton\Support\Config;
use Rsgrinko\Proton\Support\Logger;
use Rsgrinko\Proton\Support\ProtonException;
use Throwable;
/**
* Отправка писем. Драйвер выбирается настройкой mail.driver:
*
* mail — функция mail() (по умолчанию: работает везде, ничего не настраивая);
* smtp — свой SMTP-клиент;
* mailer — почтовый сервис по HTTP API (очередь, ретраи и отчёты на его стороне);
* log — письмо пишется в var/log и никуда не уходит (разработка);
* null — письмо просто выбрасывается (тесты).
*
* Драйвер можно подменить и не трогая конфиг: событие-фильтр mail.driver
* получает готовый объект и может вернуть свой. Так проект переезжает на чужую
* рассылку, не переписывая ни строчки в местах отправки.
*/
final class Mail
{
/** @var array<string, class-string<DriverInterface>> */
private const DRIVERS = [
'mail' => MailDriver::class,
'smtp' => SmtpDriver::class,
'mailer' => MailerServiceDriver::class,
'log' => LogDriver::class,
'null' => NullDriver::class,
];
/** Подменённый драйвер — тесты и ручная настройка */
private static ?DriverInterface $driver = null;
/** @var array<int, Message> Письма, отправленные при подменённом драйвере-заглушке */
private static array $sent = [];
/**
* Отправляет письмо прямо сейчас.
*/
public static function send(Message $message): bool
{
if ($message->recipients() === []) {
throw new ProtonException('У письма нет получателей');
}
if ($message->senderEmail() === '') {
throw new ProtonException('Не задан отправитель: заполните MAIL_FROM в .env');
}
// Событие «письмо уходит»: слушатель может дописать заголовки или
// отменить отправку, вернув false
$allowed = Events::fire('mail.sending', ['message' => $message]);
if (in_array(false, $allowed, true)) {
return false;
}
$driver = self::driver();
try {
$driver->send($message);
} catch (Throwable $e) {
(new Logger('mail'))->error('Письмо не отправлено', [
'to' => implode(', ', $message->recipients()),
'driver' => $driver->name(),
'error' => $e->getMessage(),
]);
Events::fire('mail.failed', ['message' => $message, 'error' => $e->getMessage()]);
throw $e;
}
self::$sent[] = $message;
(new Logger('mail'))->info('Письмо отправлено', [
'to' => implode(', ', $message->recipients()),
'subject' => $message->subjectLine(),
'driver' => $driver->name(),
]);
Events::fire('mail.sent', ['message' => $message]);
return true;
}
/**
* Кладёт письмо в очередь: страница не ждёт SMTP, отправкой займётся воркер.
*/
public static function queue(Message $message, int $delaySeconds = 0): int
{
return Queue::push(SendMailJob::class, $message->toArray(), $delaySeconds);
}
/**
* Текущий драйвер.
*/
public static function driver(): DriverInterface
{
if (self::$driver !== null) {
return self::$driver;
}
$name = (string) Config::get('mail.driver', 'mail');
$class = self::DRIVERS[$name] ?? null;
if ($class === null) {
throw new ProtonException('Неизвестный драйвер почты: ' . $name);
}
/** @var DriverInterface $driver */
$driver = new $class();
// Последнее слово — за приложением: фильтр может вернуть свой драйвер
$filtered = Events::filter('mail.driver', $driver);
return $filtered instanceof DriverInterface ? $filtered : $driver;
}
/**
* Подменить драйвер — тесты и разовые задачи.
*/
public static function setDriver(?DriverInterface $driver): void
{
self::$driver = $driver;
}
/**
* Письма, отправленные за этот процесс — нужно тестам.
*
* @return array<int, Message>
*/
public static function sent(): array
{
return self::$sent;
}
public static function forget(): void
{
self::$sent = [];
}
/**
* Список доступных драйверов — показывает состояние и справка.
*
* @return array<int, string>
*/
public static function drivers(): array
{
return array_keys(self::DRIVERS);
}
}
+352
View File
@@ -0,0 +1,352 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Mail;
use Rsgrinko\Proton\Support\Config;
use Rsgrinko\Proton\Support\ProtonException;
use Rsgrinko\Proton\Support\Str;
use Rsgrinko\Proton\Support\Validator;
use Rsgrinko\Proton\View\View;
/**
* Письмо. Собирается цепочкой и уходит в Mail::send().
*
* Message::to('user@example.com')
* ->subject('Подтверждение почты')
* ->view('mail/verify', ['link' => $link])
* ->send();
*/
final class Message
{
/** @var array<int, string> */
private array $to = [];
/** @var array<int, string> */
private array $cc = [];
/** @var array<int, string> */
private array $bcc = [];
private string $fromEmail = '';
private string $fromName = '';
private string $replyTo = '';
private string $subject = '';
private string $text = '';
private string $html = '';
/** @var array<string, string> Дополнительные заголовки */
private array $headers = [];
/** @var array<int, array{name: string, content: string, mime: string}> */
private array $attachments = [];
public static function to(string ...$addresses): self
{
$message = new self();
foreach ($addresses as $address) {
$message->addTo($address);
}
return $message;
}
public function addTo(string $address): self
{
$address = trim($address);
if (!Validator::isEmail($address)) {
throw new ProtonException('Неверный адрес получателя: ' . $address);
}
$this->to[] = $address;
return $this;
}
public function copy(string $address): self
{
$this->cc[] = trim($address);
return $this;
}
public function blindCopy(string $address): self
{
$this->bcc[] = trim($address);
return $this;
}
public function from(string $email, string $name = ''): self
{
$this->fromEmail = trim($email);
$this->fromName = trim($name);
return $this;
}
public function replyTo(string $email): self
{
$this->replyTo = trim($email);
return $this;
}
public function subject(string $subject): self
{
$this->subject = trim($subject);
return $this;
}
public function text(string $text): self
{
$this->text = $text;
return $this;
}
public function html(string $html): self
{
$this->html = $html;
// Текстовую часть считаем сама, если её не задали: письмо без text
// некоторые клиенты и спам-фильтры любят меньше
if ($this->text === '') {
$this->text = Str::htmlToText($html);
}
return $this;
}
/**
* Тело письма из шаблона resources/views.
*
* @param array<string, mixed> $data
*/
public function view(string $template, array $data = []): self
{
return $this->html(View::partial($template, $data));
}
public function header(string $name, string $value): self
{
// Перевод строки в заголовке дописывает в письмо посторонние заголовки —
// отсюда и рассылка мимо стоп-листа, и подделка отправителя
if (preg_match('/^[A-Za-z0-9-]+$/', $name) !== 1) {
throw new ProtonException('Недопустимое имя заголовка: ' . $name);
}
$this->headers[$name] = trim(str_replace(["\r", "\n"], '', $value));
return $this;
}
/**
* Вложение из строки в памяти.
*/
public function attach(string $fileName, string $content, string $mime = 'application/octet-stream'): self
{
$this->attachments[] = ['name' => $fileName, 'content' => $content, 'mime' => $mime];
return $this;
}
/**
* Вложение из файла на диске.
*/
public function attachFile(string $path, string $fileName = ''): self
{
if (!is_file($path)) {
throw new ProtonException('Файл вложения не найден: ' . $path);
}
return $this->attach(
$fileName !== '' ? $fileName : basename($path),
(string) file_get_contents($path)
);
}
/**
* Отправить прямо сейчас.
*/
public function send(): bool
{
return Mail::send($this);
}
/**
* Поставить в очередь — письмо уйдёт воркером, а страница не будет ждать SMTP.
*/
public function queue(int $delaySeconds = 0): int
{
return Mail::queue($this, $delaySeconds);
}
// --- Чтение --------------------------------------------------------------
/**
* @return array<int, string>
*/
public function recipients(): array
{
return $this->to;
}
/**
* @return array<int, string>
*/
public function copies(): array
{
return $this->cc;
}
/**
* @return array<int, string>
*/
public function blindCopies(): array
{
return $this->bcc;
}
/**
* Все адреса конверта — им и доставляем.
*
* @return array<int, string>
*/
public function envelopeRecipients(): array
{
return array_values(array_unique(array_merge($this->to, $this->cc, $this->bcc)));
}
public function senderEmail(): string
{
return $this->fromEmail !== '' ? $this->fromEmail : (string) Config::get('mail.from_email', '');
}
public function senderName(): string
{
return $this->fromName !== '' ? $this->fromName : (string) Config::get('mail.from_name', '');
}
public function replyAddress(): string
{
return $this->replyTo;
}
public function subjectLine(): string
{
return $this->subject;
}
public function textBody(): string
{
return $this->text;
}
public function htmlBody(): string
{
return $this->html;
}
/**
* @return array<string, string>
*/
public function extraHeaders(): array
{
return $this->headers;
}
/**
* @return array<int, array{name: string, content: string, mime: string}>
*/
public function attachments(): array
{
return $this->attachments;
}
/**
* Письмо в виде массива — так его кладут в очередь и отправляют по API.
*
* @return array<string, mixed>
*/
public function toArray(): array
{
return [
'to' => $this->to,
'cc' => $this->cc,
'bcc' => $this->bcc,
'from' => $this->senderEmail(),
'from_name' => $this->senderName(),
'reply_to' => $this->replyTo,
'subject' => $this->subject,
'text' => $this->text,
'html' => $this->html,
'headers' => $this->headers,
'attachments' => array_map(
static fn (array $file): array => [
'name' => $file['name'],
'mime' => $file['mime'],
'content' => base64_encode($file['content']),
],
$this->attachments
),
];
}
/**
* Обратная сборка — из очереди письмо приходит массивом.
*
* @param array<string, mixed> $data
*/
public static function fromArray(array $data): self
{
$message = new self();
foreach ((array) ($data['to'] ?? []) as $address) {
$message->addTo((string) $address);
}
foreach ((array) ($data['cc'] ?? []) as $address) {
$message->copy((string) $address);
}
foreach ((array) ($data['bcc'] ?? []) as $address) {
$message->blindCopy((string) $address);
}
$message->from((string) ($data['from'] ?? ''), (string) ($data['from_name'] ?? ''));
$message->subject((string) ($data['subject'] ?? ''));
$message->text((string) ($data['text'] ?? ''));
if (($data['html'] ?? '') !== '') {
$message->html((string) $data['html']);
}
if (($data['reply_to'] ?? '') !== '') {
$message->replyTo((string) $data['reply_to']);
}
foreach ((array) ($data['headers'] ?? []) as $name => $value) {
$message->header((string) $name, (string) $value);
}
foreach ((array) ($data['attachments'] ?? []) as $file) {
$message->attach(
(string) ($file['name'] ?? 'file'),
(string) base64_decode((string) ($file['content'] ?? ''), true),
(string) ($file['mime'] ?? 'application/octet-stream')
);
}
return $message;
}
}
+178
View File
@@ -0,0 +1,178 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Mail;
/**
* Сборка письма в MIME: заголовки и тело.
*
* Русские темы и имена кодируются base64 (=?UTF-8?B?…?=) — иначе почтовые
* серверы получают восьмибитные байты в заголовке и портят их. Тело идёт
* quoted-printable, вложения — base64 кусками по 76 символов, как требует
* стандарт.
*/
final class Mime
{
/**
* Заголовки письма без тела.
*
* @return array<string, string>
*/
public static function headers(Message $message, bool $withRecipients = true): array
{
$headers = [];
if ($withRecipients) {
$headers['To'] = implode(', ', $message->recipients());
if ($message->copies() !== []) {
$headers['Cc'] = implode(', ', $message->copies());
}
}
$headers['From'] = self::address($message->senderEmail(), $message->senderName());
if ($message->replyAddress() !== '') {
$headers['Reply-To'] = $message->replyAddress();
}
$headers['Subject'] = self::encodeHeader($message->subjectLine());
$headers['Date'] = date('r');
$headers['Message-ID'] = '<' . bin2hex(random_bytes(12)) . '@' . self::hostname($message->senderEmail()) . '>';
$headers['MIME-Version'] = '1.0';
foreach ($message->extraHeaders() as $name => $value) {
$headers[$name] = self::encodeHeader($value);
}
return $headers;
}
/**
* Тело письма вместе с заголовками Content-Type.
*
* @return array{headers: array<string, string>, body: string}
*/
public static function body(Message $message): array
{
$text = $message->textBody();
$html = $message->htmlBody();
$attachments = $message->attachments();
// Простое письмо без второй части и вложений
if ($attachments === [] && ($html === '' || $text === '')) {
$single = $html !== '' ? $html : $text;
return [
'headers' => [
'Content-Type' => ($html !== '' ? 'text/html' : 'text/plain') . '; charset=UTF-8',
'Content-Transfer-Encoding' => 'quoted-printable',
],
'body' => quoted_printable_encode($single),
];
}
$alternative = 'alt-' . bin2hex(random_bytes(8));
$mixed = 'mix-' . bin2hex(random_bytes(8));
$parts = '';
if ($text !== '' && $html !== '') {
$parts .= '--' . $alternative . "\r\n"
. "Content-Type: text/plain; charset=UTF-8\r\n"
. "Content-Transfer-Encoding: quoted-printable\r\n\r\n"
. quoted_printable_encode($text) . "\r\n"
. '--' . $alternative . "\r\n"
. "Content-Type: text/html; charset=UTF-8\r\n"
. "Content-Transfer-Encoding: quoted-printable\r\n\r\n"
. quoted_printable_encode($html) . "\r\n"
. '--' . $alternative . "--\r\n";
}
if ($attachments === []) {
return [
'headers' => ['Content-Type' => 'multipart/alternative; boundary="' . $alternative . '"'],
'body' => $parts,
];
}
$body = '--' . $mixed . "\r\n";
if ($parts !== '') {
$body .= 'Content-Type: multipart/alternative; boundary="' . $alternative . "\"\r\n\r\n" . $parts;
} else {
$single = $html !== '' ? $html : $text;
$body .= 'Content-Type: ' . ($html !== '' ? 'text/html' : 'text/plain') . "; charset=UTF-8\r\n"
. "Content-Transfer-Encoding: quoted-printable\r\n\r\n"
. quoted_printable_encode($single) . "\r\n";
}
foreach ($attachments as $file) {
$body .= '--' . $mixed . "\r\n"
. 'Content-Type: ' . $file['mime'] . '; name="' . self::encodeHeader($file['name']) . "\"\r\n"
. "Content-Transfer-Encoding: base64\r\n"
. 'Content-Disposition: attachment; filename="' . self::encodeHeader($file['name']) . "\"\r\n\r\n"
. chunk_split(base64_encode($file['content']), 76, "\r\n");
}
$body .= '--' . $mixed . "--\r\n";
return [
'headers' => ['Content-Type' => 'multipart/mixed; boundary="' . $mixed . '"'],
'body' => $body,
];
}
/**
* Письмо целиком: заголовки и тело одной строкой — так его принимает SMTP.
*/
public static function build(Message $message): string
{
$body = self::body($message);
$headers = array_merge(self::headers($message), $body['headers']);
$lines = '';
foreach ($headers as $name => $value) {
$lines .= $name . ': ' . $value . "\r\n";
}
return $lines . "\r\n" . $body['body'];
}
/**
* «Имя <адрес>» с кодировкой имени.
*/
public static function address(string $email, string $name = ''): string
{
return $name === '' ? $email : self::encodeHeader($name) . ' <' . $email . '>';
}
/**
* Заголовок с русским текстом. Латиница остаётся как есть — так письмо
* читаемо и в сыром виде.
*/
public static function encodeHeader(string $value): string
{
$value = trim(str_replace(["\r", "\n"], ' ', $value));
if ($value === '' || preg_match('/^[\x20-\x7E]*$/', $value) === 1) {
return $value;
}
return '=?UTF-8?B?' . base64_encode($value) . '?=';
}
/**
* Домен для Message-ID: свой, а не чужой — иначе письмо выглядит подделкой.
*/
private static function hostname(string $fromEmail): string
{
$domain = substr(strrchr($fromEmail, '@') ?: '', 1);
return $domain !== '' ? $domain : (string) (gethostname() ?: 'localhost');
}
}
+29
View File
@@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Mail;
use Rsgrinko\Proton\Queue\Job;
/**
* Отправка письма из очереди: сюда попадает всё, что ушло через Mail::queue().
*
* Ради этого письма и стоит очередь: SMTP чужого провайдера отвечает секундами,
* а страница регистрации не должна их ждать.
*/
final class SendMailJob extends Job
{
public function attempts(): int
{
return 5;
}
/**
* @param array<string, mixed> $payload
*/
public function handle(array $payload): void
{
Mail::send(Message::fromArray($payload));
}
}