From 8d0bdd27567e6bb796644ed011e034d4d6a87c14 Mon Sep 17 00:00:00 2001 From: rsgrinko Date: Thu, 20 Aug 2026 00:49:21 +0300 Subject: [PATCH] first commit --- README.md | 144 +++++++++++++++ composer.json | 41 +++++ config/mailerservice.php | 32 ++++ src/Client.php | 209 ++++++++++++++++++++++ src/Facades/MailService.php | 29 +++ src/MailServiceException.php | 31 ++++ src/MailServiceProvider.php | 60 +++++++ src/Message.php | 236 +++++++++++++++++++++++++ src/Transport/MailServiceTransport.php | 221 +++++++++++++++++++++++ 9 files changed, 1003 insertions(+) create mode 100644 README.md create mode 100644 composer.json create mode 100644 config/mailerservice.php create mode 100644 src/Client.php create mode 100644 src/Facades/MailService.php create mode 100644 src/MailServiceException.php create mode 100644 src/MailServiceProvider.php create mode 100644 src/Message.php create mode 100644 src/Transport/MailServiceTransport.php diff --git a/README.md b/README.md new file mode 100644 index 0000000..bd7f8da --- /dev/null +++ b/README.md @@ -0,0 +1,144 @@ +# Laravel Mailerservice SDK + +Пакет для Laravel: отправляет почту через сервис рассылки по его HTTP API. +Работает и как обычный почтовый транспорт (`config/mail.php`), и как прямой +клиент API — для статусов, шаблонов и отправки по шаблону без Laravel Mail. + +Требования: PHP 8.3+, Laravel 13, Symfony Mailer 7 (тянется Laravel'ом). + +## Установка + +``` +composer require rsgrinko/laravel-mailerservice-sdk +``` + +Провайдер и алиас `MailService` подхватываются автоматически. Для публикации +конфига: + +``` +php artisan vendor:publish --tag=mailerservice-config +``` + +## Настройка + +Переменные окружения (ключи совпадают с `config/mailerservice.php`): + +``` +MAILERSERVICE_URL=http://mail.internal +MAILERSERVICE_KEY=mlr_ваш_ключ +MAILERSERVICE_TIMEOUT=10 +MAILERSERVICE_RETRIES=2 +MAILERSERVICE_RETRY_DELAY=200 +MAILERSERVICE_TAG= # метка, по которой письма видны в панели +MAILERSERVICE_TRANSPORT= # транспорт сервиса, если не тот, что у проекта по умолчанию +MAILERSERVICE_SYNC=false +MAILERSERVICE_VERIFY=true +``` + +Ключ проекта выдаётся на стороне сервиса: `php bin/mailer key:create`. + +### Почтовый транспорт + +В `config/mail.php` добавить драйвер и переключить default: + +```php +'mailerservice' => [ + 'transport' => 'mailerservice', +], + +'default' => env('MAIL_MAILER', 'mailerservice'), +``` + +Дальше почта шлётся как обычно: + +```php +Mail::to($user->email)->send(new OrderShipped($order)); +``` + +Письмо принимается сервисом в очередь, доставкой занимается его воркер — +запрос из приложения быстрый и не зависит от состояния почтового сервера. +Тема, отправитель, получатели, копии, тела и вложения из Symfony-письма +раскладываются автоматически; пользовательские заголовки (кроме служебных) +передаются как есть. Приоритет Symfony (1–5) ложится на приоритет очереди +сервиса, обычные письма уходят с 100. + +Если в настройках стоит `MAILERSERVICE_SYNC=true`, транспорт дожидается +фактической отправки: медленнее, зато ошибка доставки падает прямо в +`Mail::send()`. + +## Прямой клиент API + +Клиент лежит в контейнере, наружу — фасад `MailService`: + +```php +use Rsgrinko\MailService\Message; + +// письмо по шаблону сервиса +$result = MailService::send( + Message::to($user->email) + ->template('welcome', ['name' => $user->name]) + ->tag('регистрация') +); + +// проверка статуса +$status = MailService::status($result['id']); + +// всё остальное +MailService::messages(['status' => 'failed', 'per_page' => 50]); +MailService::retry($result['id']); +MailService::cancel($result['id']); +MailService::templates(); +MailService::health(); +``` + +Методы клиента: + +| Метод | Что делает | +|-------|------------| +| `send($mail)` | ставит письмо в очередь | +| `sendNow($mail)` | отправляет сразу и ждёт результата | +| `status($id)` | состояние письма и его история | +| `messages($filters)` | список писем проекта | +| `retry($id)` | вернуть письмо в очередь | +| `cancel($id)` | отменить письмо | +| `templates()` | список шаблонов | +| `health()` | состояние сервиса | + +Письмо `Message` собирается цепочкой (без Laravel Mail, напрямую в API): + +```php +Message::to('user@example.com') + ->from('noreply@example.com', 'Интернет-магазин') + ->cc(['manager@example.com']) + ->replyTo('support@example.com') + ->subject('Заказ №1024 оформлен') + ->html('

Спасибо за заказ!

') + ->text('Спасибо за заказ!') + ->attachFile(storage_path('app/order.pdf')) + ->meta(['order_id' => 1024]); +``` + +Доступны также `text()`, `template($name, $data)`, `inlineImage($cid, $path)`, +`header()`, `transport($name)`, `priority($n)`, `sendAt($when)`, +`idempotencyKey($key)`, `sync()`. + +## Обработка ошибок + +Все методы бросают `Rsgrinko\MailService\MailServiceException`: + +```php +use Rsgrinko\MailService\MailServiceException; + +try { + MailService::send(Message::to('user@example.com')->subject('Привет')->text('Тело')); +} catch (MailServiceException $e) { + // $e->getMessage() — что не так + // $e->getCode() — код ответа сервиса (401, 422, 429 …) + // $e->errors — список ошибок валидации + // $e->response — полный ответ сервиса +} +``` + +Если сервис не ответил по сети, запрос повторяется (настройка `retries`, +пауза `retry_delay`), после чего бросается исключение с причиной. Ошибка +самого сервиса (неверный ключ, невалидное письмо, 502 при sync) не повторяется. \ No newline at end of file diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..c3db493 --- /dev/null +++ b/composer.json @@ -0,0 +1,41 @@ +{ + "name": "rsgrinko/laravel-mailerservice-sdk", + "description": "SDK сервиса отправки почты для Laravel: клиент API и почтовый транспорт", + "type": "library", + "license": "MIT", + "keywords": ["laravel", "mail", "mailer", "smtp", "queue", "mailerservice"], + "authors": [ + { + "name": "Роман Гринько", + "email": "rsgrinko@gmail.com" + } + ], + "require": { + "php": "^8.3", + "illuminate/support": "^13.0", + "illuminate/http": "^13.0", + "illuminate/mail": "^13.0", + "symfony/mailer": "^7.0", + "symfony/mime": "^7.0" + }, + "autoload": { + "psr-4": { + "Rsgrinko\\MailService\\": "src/" + } + }, + "extra": { + "laravel": { + "providers": [ + "Rsgrinko\\MailService\\MailServiceProvider" + ], + "aliases": { + "MailService": "Rsgrinko\\MailService\\Facades\\MailService" + } + } + }, + "config": { + "sort-packages": true + }, + "minimum-stability": "stable", + "prefer-stable": true +} diff --git a/config/mailerservice.php b/config/mailerservice.php new file mode 100644 index 0000000..d549f9b --- /dev/null +++ b/config/mailerservice.php @@ -0,0 +1,32 @@ + env('MAILERSERVICE_URL', 'http://127.0.0.1:8080'), + + // Ключ проекта: php bin/mailer key:create на стороне сервиса + 'key' => env('MAILERSERVICE_KEY', ''), + + // Сколько ждать ответа сервиса, секунды + 'timeout' => (int) env('MAILERSERVICE_TIMEOUT', 10), + + // Сколько раз повторить запрос, если сервис не ответил (0 — не повторять) + 'retries' => (int) env('MAILERSERVICE_RETRIES', 2), + + // Пауза между повторами, миллисекунды + 'retry_delay' => (int) env('MAILERSERVICE_RETRY_DELAY', 200), + + // Метка, с которой уходят письма приложения: по ней их видно в панели + 'tag' => env('MAILERSERVICE_TAG'), + + // Транспорт сервиса, если нужен не тот, что у проекта по умолчанию + 'transport' => env('MAILERSERVICE_TRANSPORT'), + + // Ждать ли отправки вместо постановки в очередь. Медленнее, зато сразу видно ошибку + 'sync' => (bool) env('MAILERSERVICE_SYNC', false), + + // Проверять ли сертификат при работе по https + 'verify' => (bool) env('MAILERSERVICE_VERIFY', true), +]; \ No newline at end of file diff --git a/src/Client.php b/src/Client.php new file mode 100644 index 0000000..d237dcd --- /dev/null +++ b/src/Client.php @@ -0,0 +1,209 @@ + $options Ключи: timeout, retries, retry_delay, verify + */ + public function __construct(string $baseUrl, string $apiKey, array $options = [], ?Factory $http = null) + { + $this->baseUrl = rtrim($baseUrl, '/'); + $this->apiKey = $apiKey; + $this->timeout = (int) ($options['timeout'] ?? 10); + $this->retries = max(0, (int) ($options['retries'] ?? 2)); + $this->retryDelay = (int) ($options['retry_delay'] ?? 200); + $this->verify = (bool) ($options['verify'] ?? true); + $this->http = $http ?? (Http::getFacadeRoot() ?? new Factory()); + } + + /** + * Отправляет письмо: ставит в очередь сервиса и отвечает сразу. + * + * @param Message|array $mail + * @return array ответ сервиса: id, status и прочее + */ + public function send(Message|array $mail): array + { + $payload = $mail instanceof Message ? $mail->toArray() : $mail; + + return $this->sendJson('POST', '/api/v1/messages', $payload); + } + + /** + * Отправляет письмо и ждёт результата отправки (sync-режим). + * + * @param Message|array $mail + * @return array + */ + public function sendNow(Message|array $mail): array + { + $payload = $mail instanceof Message ? $mail->toArray() : $mail; + $payload['sync'] = true; + + return $this->sendJson('POST', '/api/v1/messages', $payload); + } + + /** + * Состояние письма по его идентификатору. + * + * @return array + */ + public function status(string $id): array + { + return $this->sendJson('GET', '/api/v1/messages/' . rawurlencode($id)); + } + + /** + * Список писем проекта. + * + * @param array $filters status, tag, search, page, per_page + * @return array + */ + public function messages(array $filters = []): array + { + $query = $filters === [] ? '' : '?' . http_build_query($filters); + + return $this->sendJson('GET', '/api/v1/messages' . $query); + } + + /** + * Повторить неудачное письмо. + * + * @return array + */ + public function retry(string $id): array + { + return $this->sendJson('POST', '/api/v1/messages/' . rawurlencode($id) . '/retry'); + } + + /** + * Отменить письмо, пока оно в очереди. + * + * @return array + */ + public function cancel(string $id): array + { + return $this->sendJson('DELETE', '/api/v1/messages/' . rawurlencode($id)); + } + + /** + * Доступные шаблоны писем. + * + * @return array + */ + public function templates(): array + { + return $this->sendJson('GET', '/api/v1/templates'); + } + + /** + * Состояние сервиса. + * + * @return array + */ + public function health(): array + { + return $this->sendJson('GET', '/api/v1/health'); + } + + /** + * Запрос с повторами: если сервис не ответил (обрыв сети), пробуем ещё раз. + * Ответ с ошибкой приложения не повторяется. + * + * @param array|null $payload + * @return array + */ + private function sendJson(string $method, string $path, ?array $payload = null): array + { + try { + return retry( + $this->retries + 1, + fn (): array => $this->execute($method, $path, $payload), + $this->retryDelay, + static fn (Throwable $e): bool => $e instanceof ConnectionException, + ); + } catch (ConnectionException $e) { + throw new MailServiceException('Сервис недоступен: ' . $e->getMessage(), 0, [], [], $e); + } + } + + /** + * @param array|null $payload + * @return array + */ + private function execute(string $method, string $path, ?array $payload): array + { + $request = $this->pending(); + + $response = match ($method) { + 'GET' => $request->get($path), + 'POST' => $payload === null ? $request->post($path) : $request->post($path, $payload), + 'DELETE' => $request->delete($path), + default => throw new MailServiceException('Неподдерживаемый метод: ' . $method), + }; + + return $this->handle($response); + } + + private function pending(): PendingRequest + { + $request = $this->http + ->baseUrl($this->baseUrl) + ->acceptJson() + ->asJson() + ->withToken($this->apiKey) + ->timeout($this->timeout); + + if (!$this->verify) { + $request = $request->withoutVerifying(); + } + + return $request; + } + + /** + * Разбирает ответ и превращает ошибку сервиса в исключение. + * + * @return array + */ + private function handle(Response $response): array + { + $status = $response->status(); + $decoded = $response->json(); + + if ($status >= 200 && $status < 300) { + return is_array($decoded) ? $decoded : []; + } + + $decoded = is_array($decoded) ? $decoded : []; + $message = (string) ($decoded['error']['message'] ?? 'Сервис ответил кодом ' . $status); + $errors = (array) ($decoded['error']['details']['errors'] ?? []); + + throw new MailServiceException($message, $status, $errors, $decoded); + } +} \ No newline at end of file diff --git a/src/Facades/MailService.php b/src/Facades/MailService.php new file mode 100644 index 0000000..c636243 --- /dev/null +++ b/src/Facades/MailService.php @@ -0,0 +1,29 @@ + Ошибки валидации, если сервис их прислал */ + public array $errors = []; + + /** @var array Полный ответ сервиса */ + public array $response = []; + + /** + * @param array $errors + * @param array $response + */ + public function __construct(string $message, int $code = 0, array $errors = [], array $response = [], ?\Throwable $previous = null) + { + parent::__construct($message, $code, $previous); + + $this->errors = $errors; + $this->response = $response; + } +} diff --git a/src/MailServiceProvider.php b/src/MailServiceProvider.php new file mode 100644 index 0000000..4b9d309 --- /dev/null +++ b/src/MailServiceProvider.php @@ -0,0 +1,60 @@ +mergeConfigFrom(__DIR__ . '/../config/mailerservice.php', 'mailerservice'); + + $this->app->singleton(Client::class, function ($app): Client { + $config = (array) $app['config']->get('mailerservice', []); + + return new Client( + (string) ($config['url'] ?? ''), + (string) ($config['key'] ?? ''), + [ + 'timeout' => (int) ($config['timeout'] ?? 10), + 'retries' => (int) ($config['retries'] ?? 2), + 'retry_delay' => (int) ($config['retry_delay'] ?? 200), + 'verify' => (bool) ($config['verify'] ?? true), + ], + $app->bound(Factory::class) ? $app->make(Factory::class) : null + ); + }); + + $this->app->alias(Client::class, 'mailerservice'); + } + + public function boot(): void + { + if ($this->app->runningInConsole()) { + $this->publishes([ + __DIR__ . '/../config/mailerservice.php' => $this->app->configPath('mailerservice.php'), + ], 'mailerservice-config'); + } + + Mail::extend('mailerservice', function (array $config): MailServiceTransport { + $settings = (array) $this->app['config']->get('mailerservice', []); + + return new MailServiceTransport( + $this->app->make(Client::class), + isset($settings['tag']) && $settings['tag'] !== '' ? (string) $settings['tag'] : null, + isset($settings['transport']) && $settings['transport'] !== '' ? (string) $settings['transport'] : null, + (bool) ($settings['sync'] ?? false), + ); + }); + } +} \ No newline at end of file diff --git a/src/Message.php b/src/Message.php new file mode 100644 index 0000000..e1ef85b --- /dev/null +++ b/src/Message.php @@ -0,0 +1,236 @@ +subject('Привет')->html('

Текст

'). + */ +class Message +{ + /** @var array */ + private array $data = []; + + /** + * Начало письма: один или несколько получателей. + * + * @param string|array $to + */ + public static function to(string|array $to): self + { + $mail = new self(); + $mail->data['to'] = $to; + + return $mail; + } + + /** + * Отправитель. Имя необязательно. + */ + public function from(string $email, string $name = ''): self + { + $this->data['from'] = $name === '' ? $email : ['email' => $email, 'name' => $name]; + + return $this; + } + + /** + * @param string|array $cc + */ + public function cc(string|array $cc): self + { + $this->data['cc'] = $cc; + + return $this; + } + + /** + * @param string|array $bcc + */ + public function bcc(string|array $bcc): self + { + $this->data['bcc'] = $bcc; + + return $this; + } + + public function replyTo(string $email): self + { + $this->data['reply_to'] = $email; + + return $this; + } + + public function subject(string $subject): self + { + $this->data['subject'] = $subject; + + return $this; + } + + public function text(string $text): self + { + $this->data['text'] = $text; + + return $this; + } + + public function html(string $html): self + { + $this->data['html'] = $html; + + return $this; + } + + /** + * Письмо по шаблону из сервиса. + * + * @param array $data + */ + public function template(string $name, array $data = []): self + { + $this->data['template'] = $name; + $this->data['template_data'] = $data; + + return $this; + } + + /** + * Вложение из данных в памяти. + */ + public function attach(string $fileName, string $content, string $contentType = ''): self + { + $attachment = [ + 'name' => $fileName, + 'content' => base64_encode($content), + ]; + + if ($contentType !== '') { + $attachment['content_type'] = $contentType; + } + + $this->data['attachments'][] = $attachment; + + return $this; + } + + /** + * Вложение из файла на диске. + */ + public function attachFile(string $path, string $fileName = ''): self + { + if (!is_file($path)) { + throw new MailServiceException('Файл вложения не найден: ' . $path); + } + + return $this->attach($fileName !== '' ? $fileName : basename($path), (string) file_get_contents($path)); + } + + /** + * Картинка внутри HTML. В теле письма ссылаться так: + */ + public function inlineImage(string $cid, string $path, string $fileName = ''): self + { + if (!is_file($path)) { + throw new MailServiceException('Файл картинки не найден: ' . $path); + } + + $this->data['attachments'][] = [ + 'name' => $fileName !== '' ? $fileName : basename($path), + 'content' => base64_encode((string) file_get_contents($path)), + 'inline' => true, + 'cid' => $cid, + ]; + + return $this; + } + + public function header(string $name, string $value): self + { + $this->data['headers'][$name] = $value; + + return $this; + } + + /** + * Метка — по ней потом удобно искать письма в панели. + */ + public function tag(string $tag): self + { + $this->data['tag'] = $tag; + + return $this; + } + + /** + * Произвольные данные, которые вернутся в вебхуке. + * + * @param array $meta + */ + public function meta(array $meta): self + { + $this->data['meta'] = $meta; + + return $this; + } + + /** + * Отправить конкретным транспортом (имя из панели). + */ + public function transport(string $name): self + { + $this->data['transport'] = $name; + + return $this; + } + + /** + * Меньше число — выше приоритет в очереди. По умолчанию 100. + */ + public function priority(int $priority): self + { + $this->data['priority'] = $priority; + + return $this; + } + + /** + * Отложенная отправка: '2026-01-01 10:00:00' или '+2 hours'. + */ + public function sendAt(string $when): self + { + $this->data['send_at'] = $when; + + return $this; + } + + /** + * Защита от повторной отправки при ретраях на стороне приложения. + */ + public function idempotencyKey(string $key): self + { + $this->data['idempotency_key'] = $key; + + return $this; + } + + /** + * Дождаться отправки вместо постановки в очередь. + */ + public function sync(bool $sync = true): self + { + $this->data['sync'] = $sync; + + return $this; + } + + /** + * @return array + */ + public function toArray(): array + { + return $this->data; + } +} \ No newline at end of file diff --git a/src/Transport/MailServiceTransport.php b/src/Transport/MailServiceTransport.php new file mode 100644 index 0000000..71168b7 --- /dev/null +++ b/src/Transport/MailServiceTransport.php @@ -0,0 +1,221 @@ + 1, + Email::PRIORITY_HIGH => 2, + Email::PRIORITY_NORMAL => 100, + Email::PRIORITY_LOW => 150, + Email::PRIORITY_LOWEST => 200, + ]; + + /** Заголовки, которые сервис заполнит сам, — их не шлём */ + private const SKIP_HEADERS = [ + 'To', 'Cc', 'Bcc', 'From', 'Reply-To', 'Subject', + 'Date', 'Message-ID', 'MIME-Version', 'Content-Type', + 'Content-Transfer-Encoding', 'Content-Disposition', 'Return-Path', + ]; + + private Client $client; + private ?string $tag; + private ?string $transport; + private bool $sync; + + public function __construct( + Client $client, + ?string $tag = null, + ?string $transport = null, + bool $sync = false, + ?EventDispatcherInterface $dispatcher = null, + ?LoggerInterface $logger = null + ) { + parent::__construct($dispatcher, $logger); + + $this->client = $client; + $this->tag = $tag; + $this->transport = $transport; + $this->sync = $sync; + } + + protected function doSend(SentMessage $message): void + { + $original = $message->getOriginalMessage(); + + if (!$original instanceof Email) { + $original = MessageConverter::toEmail($original); + } + + $payload = $this->toPayload($original); + + if ($this->tag !== null && $this->tag !== '') { + $payload['tag'] = $this->tag; + } + + if ($this->transport !== null && $this->transport !== '') { + $payload['transport'] = $this->transport; + } + + if ($this->sync) { + $this->client->sendNow($payload); + + return; + } + + $this->client->send($payload); + } + + public function __toString(): string + { + return 'mailerservice'; + } + + /** + * Письмо из Symfony в формат API сервиса. + * + * @return array + */ + private function toPayload(Email $email): array + { + $payload = ['subject' => (string) $email->getSubject()]; + + $from = $email->getFrom(); + if ($from !== []) { + $payload['from'] = $this->address($from[0]); + } + + if ($email->getTo() !== []) { + $payload['to'] = array_map([$this, 'address'], $email->getTo()); + } + + if ($email->getCc() !== []) { + $payload['cc'] = array_map([$this, 'address'], $email->getCc()); + } + + if ($email->getBcc() !== []) { + $payload['bcc'] = array_map([$this, 'address'], $email->getBcc()); + } + + $replyTo = $email->getReplyTo(); + if ($replyTo !== []) { + $payload['reply_to'] = $this->address($replyTo[0]); + } + + $text = $this->asString($email->getTextBody()); + if ($text !== '') { + $payload['text'] = $text; + } + + $html = $this->asString($email->getHtmlBody()); + if ($html !== '') { + $payload['html'] = $html; + } + + foreach ($email->getAttachments() as $part) { + $payload['attachments'][] = $this->attachment($part); + } + + $headers = $this->customHeaders($email); + if ($headers !== []) { + $payload['headers'] = $headers; + } + + $priority = self::PRIORITY_MAP[$email->getPriority()] ?? 100; + if ($priority !== 100) { + $payload['priority'] = $priority; + } + + return $payload; + } + + /** + * Адрес: строкой, если без имени, иначе массивом для API. + */ + private function address(Address $address): array|string + { + return $address->getName() === '' + ? $address->getAddress() + : ['email' => $address->getAddress(), 'name' => $address->getName()]; + } + + /** + * @return array + */ + private function attachment(DataPart $part): array + { + $item = [ + 'name' => $part->getFilename() ?? 'attachment', + 'content' => base64_encode($part->getBody()), + ]; + + if ($part->getContentType() !== 'application/octet-stream') { + $item['content_type'] = $part->getContentType(); + } + + if ($part->getDisposition() === 'inline') { + $item['inline'] = true; + } + + if ($part->hasContentId()) { + $item['cid'] = $part->getContentId(); + } + + return $item; + } + + /** + * Пользовательские заголовки письма (X-*, кастомные) для передачи в сервис. + * + * @return array + */ + private function customHeaders(Email $email): array + { + $headers = []; + + foreach ($email->getHeaders()->all() as $header) { + $name = $header->getName(); + + if (in_array($name, self::SKIP_HEADERS, true) || str_starts_with($name, 'X-Symfony')) { + continue; + } + + $value = $header->getBodyAsString(); + if ($value !== '') { + $headers[$name] = $value; + } + } + + return $headers; + } + + private function asString(mixed $body): string + { + if ($body === null) { + return ''; + } + + return is_string($body) ? $body : (string) stream_get_contents($body); + } +} \ No newline at end of file