first commit
This commit is contained in:
commit
8d0bdd2756
9 files changed
+1003
No files matched your search
@@ -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('<p>Спасибо за заказ!</p>')
|
||||||
|
->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) не повторяется.
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
return [
|
||||||
|
// Адрес сервиса, без /api/v1
|
||||||
|
'url' => 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),
|
||||||
|
];
|
||||||
+209
@@ -0,0 +1,209 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Rsgrinko\MailService;
|
||||||
|
|
||||||
|
use Illuminate\Http\Client\ConnectionException;
|
||||||
|
use Illuminate\Http\Client\Factory;
|
||||||
|
use Illuminate\Http\Client\PendingRequest;
|
||||||
|
use Illuminate\Http\Client\Response;
|
||||||
|
use Illuminate\Support\Facades\Http;
|
||||||
|
use Throwable;
|
||||||
|
|
||||||
|
use function retry;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* HTTP-клиент API сервиса. Каждый метод — один запрос; ошибки сервиса
|
||||||
|
* прилетают как MailServiceException, недоступность сети лечится повторами.
|
||||||
|
*/
|
||||||
|
class Client
|
||||||
|
{
|
||||||
|
private string $baseUrl;
|
||||||
|
private string $apiKey;
|
||||||
|
private int $timeout;
|
||||||
|
private int $retries;
|
||||||
|
private int $retryDelay;
|
||||||
|
private bool $verify;
|
||||||
|
private Factory $http;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<string, mixed> $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<string, mixed> $mail
|
||||||
|
* @return array<string, mixed> ответ сервиса: 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<string, mixed> $mail
|
||||||
|
* @return array<string, mixed>
|
||||||
|
*/
|
||||||
|
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<string, mixed>
|
||||||
|
*/
|
||||||
|
public function status(string $id): array
|
||||||
|
{
|
||||||
|
return $this->sendJson('GET', '/api/v1/messages/' . rawurlencode($id));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Список писем проекта.
|
||||||
|
*
|
||||||
|
* @param array<string, string|int> $filters status, tag, search, page, per_page
|
||||||
|
* @return array<string, mixed>
|
||||||
|
*/
|
||||||
|
public function messages(array $filters = []): array
|
||||||
|
{
|
||||||
|
$query = $filters === [] ? '' : '?' . http_build_query($filters);
|
||||||
|
|
||||||
|
return $this->sendJson('GET', '/api/v1/messages' . $query);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Повторить неудачное письмо.
|
||||||
|
*
|
||||||
|
* @return array<string, mixed>
|
||||||
|
*/
|
||||||
|
public function retry(string $id): array
|
||||||
|
{
|
||||||
|
return $this->sendJson('POST', '/api/v1/messages/' . rawurlencode($id) . '/retry');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Отменить письмо, пока оно в очереди.
|
||||||
|
*
|
||||||
|
* @return array<string, mixed>
|
||||||
|
*/
|
||||||
|
public function cancel(string $id): array
|
||||||
|
{
|
||||||
|
return $this->sendJson('DELETE', '/api/v1/messages/' . rawurlencode($id));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Доступные шаблоны писем.
|
||||||
|
*
|
||||||
|
* @return array<string, mixed>
|
||||||
|
*/
|
||||||
|
public function templates(): array
|
||||||
|
{
|
||||||
|
return $this->sendJson('GET', '/api/v1/templates');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Состояние сервиса.
|
||||||
|
*
|
||||||
|
* @return array<string, mixed>
|
||||||
|
*/
|
||||||
|
public function health(): array
|
||||||
|
{
|
||||||
|
return $this->sendJson('GET', '/api/v1/health');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Запрос с повторами: если сервис не ответил (обрыв сети), пробуем ещё раз.
|
||||||
|
* Ответ с ошибкой приложения не повторяется.
|
||||||
|
*
|
||||||
|
* @param array<string, mixed>|null $payload
|
||||||
|
* @return array<string, mixed>
|
||||||
|
*/
|
||||||
|
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<string, mixed>|null $payload
|
||||||
|
* @return array<string, mixed>
|
||||||
|
*/
|
||||||
|
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<string, mixed>
|
||||||
|
*/
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Rsgrinko\MailService\Facades;
|
||||||
|
|
||||||
|
use Illuminate\Support\Facades\Facade;
|
||||||
|
use Rsgrinko\MailService\Client;
|
||||||
|
use Rsgrinko\MailService\Message;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @method static array send(Message|array $mail)
|
||||||
|
* @method static array sendNow(Message|array $mail)
|
||||||
|
* @method static array status(string $id)
|
||||||
|
* @method static array messages(array $filters = [])
|
||||||
|
* @method static array retry(string $id)
|
||||||
|
* @method static array cancel(string $id)
|
||||||
|
* @method static array templates()
|
||||||
|
* @method static array health()
|
||||||
|
*
|
||||||
|
* @see \Rsgrinko\MailService\Client
|
||||||
|
*/
|
||||||
|
class MailService extends Facade
|
||||||
|
{
|
||||||
|
protected static function getFacadeAccessor(): string
|
||||||
|
{
|
||||||
|
return Client::class;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Rsgrinko\MailService;
|
||||||
|
|
||||||
|
use RuntimeException;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ошибка при обращении к сервису: сеть не ответила либо API вернуло ошибку.
|
||||||
|
*/
|
||||||
|
class MailServiceException extends RuntimeException
|
||||||
|
{
|
||||||
|
/** @var array<int, string> Ошибки валидации, если сервис их прислал */
|
||||||
|
public array $errors = [];
|
||||||
|
|
||||||
|
/** @var array<string, mixed> Полный ответ сервиса */
|
||||||
|
public array $response = [];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<int, string> $errors
|
||||||
|
* @param array<string, mixed> $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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Rsgrinko\MailService;
|
||||||
|
|
||||||
|
use Illuminate\Http\Client\Factory;
|
||||||
|
use Illuminate\Mail\MailManager;
|
||||||
|
use Illuminate\Support\Facades\Mail;
|
||||||
|
use Illuminate\Support\ServiceProvider;
|
||||||
|
use Rsgrinko\MailService\Transport\MailServiceTransport;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Регистрирует клиент API и почтовый транспорт mailerservice.
|
||||||
|
*/
|
||||||
|
class MailServiceProvider extends ServiceProvider
|
||||||
|
{
|
||||||
|
public function register(): void
|
||||||
|
{
|
||||||
|
$this->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),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
+236
@@ -0,0 +1,236 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Rsgrinko\MailService;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Письмо для прямой отправки через клиент, без Laravel Mail.
|
||||||
|
* Собирается по цепочке: Message::to('user@example.com')->subject('Привет')->html('<p>Текст</p>').
|
||||||
|
*/
|
||||||
|
class Message
|
||||||
|
{
|
||||||
|
/** @var array<string, mixed> */
|
||||||
|
private array $data = [];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Начало письма: один или несколько получателей.
|
||||||
|
*
|
||||||
|
* @param string|array<int, string> $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<int, string> $cc
|
||||||
|
*/
|
||||||
|
public function cc(string|array $cc): self
|
||||||
|
{
|
||||||
|
$this->data['cc'] = $cc;
|
||||||
|
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string|array<int, string> $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<string, mixed> $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. В теле письма ссылаться так: <img src="cid:идентификатор">
|
||||||
|
*/
|
||||||
|
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<string, mixed> $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<string, mixed>
|
||||||
|
*/
|
||||||
|
public function toArray(): array
|
||||||
|
{
|
||||||
|
return $this->data;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,221 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Rsgrinko\MailService\Transport;
|
||||||
|
|
||||||
|
use Psr\Log\LoggerInterface;
|
||||||
|
use Rsgrinko\MailService\Client;
|
||||||
|
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
|
||||||
|
use Symfony\Component\Mailer\SentMessage;
|
||||||
|
use Symfony\Component\Mailer\Transport\AbstractTransport;
|
||||||
|
use Symfony\Component\Mime\Address;
|
||||||
|
use Symfony\Component\Mime\Email;
|
||||||
|
use Symfony\Component\Mime\MessageConverter;
|
||||||
|
use Symfony\Component\Mime\Part\DataPart;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Почтовый транспорт: письмо из Laravel Mail раскладывается на JSON
|
||||||
|
* и уходит в сервис через его HTTP API. В очереди доставкой занимается воркер.
|
||||||
|
*/
|
||||||
|
class MailServiceTransport extends AbstractTransport
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Приоритет Symfony (1 — самый важный) в приоритет очереди сервиса
|
||||||
|
* (меньше число — выше приоритет, обычные письма идут с 100).
|
||||||
|
*/
|
||||||
|
private const PRIORITY_MAP = [
|
||||||
|
Email::PRIORITY_HIGHEST => 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<string, mixed>
|
||||||
|
*/
|
||||||
|
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<string, mixed>
|
||||||
|
*/
|
||||||
|
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<string, string>
|
||||||
|
*/
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user