diff --git a/README.md b/README.md
index bd7f8da..ed50bac 100644
--- a/README.md
+++ b/README.md
@@ -4,7 +4,7 @@
Работает и как обычный почтовый транспорт (`config/mail.php`), и как прямой
клиент API — для статусов, шаблонов и отправки по шаблону без Laravel Mail.
-Требования: PHP 8.3+, Laravel 13, Symfony Mailer 7 (тянется Laravel'ом).
+Требования: PHP 8.2+, Laravel 11, 12 или 13, Symfony Mailer 6.4+ (тянется Laravel'ом).
## Установка
@@ -60,18 +60,41 @@ Mail::to($user->email)->send(new OrderShipped($order));
Тема, отправитель, получатели, копии, тела и вложения из Symfony-письма
раскладываются автоматически; пользовательские заголовки (кроме служебных)
передаются как есть. Приоритет Symfony (1–5) ложится на приоритет очереди
-сервиса, обычные письма уходят с 100.
+сервиса, обычные письма уходят с 100. Метка и метаданные письма
+(`Mailable::tag()`, `Mailable::metadata()`) ложатся в поля `tag` и `meta` —
+метка у письма важнее той, что задана в настройках.
+
+Картинки внутри HTML (`$message->embed(...)`, `
`) уходят
+вложениями с тем же `cid`, на который ссылается разметка, — MIME собирает
+сервис.
Если в настройках стоит `MAILERSERVICE_SYNC=true`, транспорт дожидается
фактической отправки: медленнее, зато ошибка доставки падает прямо в
-`Mail::send()`.
+`Mail::send()`. Ошибка сервиса приходит как
+`Symfony\Component\Mailer\Exception\TransportException`, поэтому штатный
+`failover` Laravel переключается на запасной мейлер.
+
+Идентификатор письма в сервисе доступен приложению в событии `MessageSent`
+(`$event->sent->getMessageId()`) — по нему письмо ищется в панели.
+
+Настройки можно задать и на отдельный мейлер — так заводятся несколько
+мейлеров с разными метками:
+
+```php
+'billing' => [
+ 'transport' => 'mailerservice', // драйвер пакета
+ 'tag' => 'billing',
+ 'service_transport' => 'yandex', // транспорт на стороне сервиса
+ 'sync' => false,
+],
+```
## Прямой клиент API
Клиент лежит в контейнере, наружу — фасад `MailService`:
```php
-use Rsgrinko\MailService\Message;
+use Rsgrinko\MailServiceSdk\Message;
// письмо по шаблону сервиса
$result = MailService::send(
@@ -124,10 +147,10 @@ Message::to('user@example.com')
## Обработка ошибок
-Все методы бросают `Rsgrinko\MailService\MailServiceException`:
+Все методы бросают `Rsgrinko\MailServiceSdk\MailServiceException`:
```php
-use Rsgrinko\MailService\MailServiceException;
+use Rsgrinko\MailServiceSdk\MailServiceException;
try {
MailService::send(Message::to('user@example.com')->subject('Привет')->text('Тело'));
diff --git a/composer.json b/composer.json
index c3db493..b9cf63b 100644
--- a/composer.json
+++ b/composer.json
@@ -11,25 +11,27 @@
}
],
"require": {
- "php": "^8.3",
- "illuminate/support": "^13.0",
- "illuminate/http": "^13.0",
- "illuminate/mail": "^13.0",
- "symfony/mailer": "^7.0",
- "symfony/mime": "^7.0"
+ "php": "^8.2",
+ "ext-json": "*",
+ "illuminate/support": "^11.0 || ^12.0 || ^13.0",
+ "illuminate/http": "^11.0 || ^12.0 || ^13.0",
+ "illuminate/mail": "^11.0 || ^12.0 || ^13.0",
+ "psr/log": "^1.1 || ^2.0 || ^3.0",
+ "symfony/mailer": "^6.4 || ^7.0 || ^8.0",
+ "symfony/mime": "^6.4 || ^7.0 || ^8.0"
},
"autoload": {
"psr-4": {
- "Rsgrinko\\MailService\\": "src/"
+ "Rsgrinko\\MailServiceSdk\\": "src/"
}
},
"extra": {
"laravel": {
"providers": [
- "Rsgrinko\\MailService\\MailServiceProvider"
+ "Rsgrinko\\MailServiceSdk\\MailServiceProvider"
],
"aliases": {
- "MailService": "Rsgrinko\\MailService\\Facades\\MailService"
+ "MailService": "Rsgrinko\\MailServiceSdk\\Facades\\MailService"
}
}
},
diff --git a/src/Client.php b/src/Client.php
index d237dcd..23db631 100644
--- a/src/Client.php
+++ b/src/Client.php
@@ -2,16 +2,13 @@
declare(strict_types=1);
-namespace Rsgrinko\MailService;
+namespace Rsgrinko\MailServiceSdk;
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 сервиса. Каждый метод — один запрос; ошибки сервиса
@@ -86,9 +83,7 @@ class Client
*/
public function messages(array $filters = []): array
{
- $query = $filters === [] ? '' : '?' . http_build_query($filters);
-
- return $this->sendJson('GET', '/api/v1/messages' . $query);
+ return $this->sendJson('GET', '/api/v1/messages', $filters);
}
/**
@@ -133,27 +128,36 @@ class Client
/**
* Запрос с повторами: если сервис не ответил (обрыв сети), пробуем ещё раз.
- * Ответ с ошибкой приложения не повторяется.
+ * Ответ с ошибкой приложения не повторяется — повторять 401 или 422 бессмысленно.
+ *
+ * Свой цикл, а не retry() из Http-клиента: тот повторяет и на неуспешный ответ.
*
* @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);
+ $attempt = 0;
+
+ while (true) {
+ try {
+ return $this->execute($method, $path, $payload);
+ } catch (ConnectionException $e) {
+ if ($attempt >= $this->retries) {
+ throw new MailServiceException('Сервис недоступен: ' . $e->getMessage(), 0, [], [], $e);
+ }
+
+ $attempt++;
+
+ if ($this->retryDelay > 0) {
+ usleep($this->retryDelay * 1000);
+ }
+ }
}
}
/**
- * @param array|null $payload
+ * @param array|null $payload для GET — параметры строки запроса
* @return array
*/
private function execute(string $method, string $path, ?array $payload): array
@@ -161,7 +165,7 @@ class Client
$request = $this->pending();
$response = match ($method) {
- 'GET' => $request->get($path),
+ 'GET' => $payload === null || $payload === [] ? $request->get($path) : $request->get($path, $payload),
'POST' => $payload === null ? $request->post($path) : $request->post($path, $payload),
'DELETE' => $request->delete($path),
default => throw new MailServiceException('Неподдерживаемый метод: ' . $method),
@@ -201,8 +205,13 @@ class Client
}
$decoded = is_array($decoded) ? $decoded : [];
- $message = (string) ($decoded['error']['message'] ?? 'Сервис ответил кодом ' . $status);
- $errors = (array) ($decoded['error']['details']['errors'] ?? []);
+
+ // 502 при sync — это не ошибка формата: письмо принято, но отправить не вышло,
+ // причина лежит в info, а блока error в таком ответе нет
+ $message = (string) ($decoded['error']['message']
+ ?? $decoded['info']
+ ?? 'Сервис ответил кодом ' . $status);
+ $errors = (array) ($decoded['error']['details']['errors'] ?? []);
throw new MailServiceException($message, $status, $errors, $decoded);
}
diff --git a/src/Facades/MailService.php b/src/Facades/MailService.php
index c636243..5212131 100644
--- a/src/Facades/MailService.php
+++ b/src/Facades/MailService.php
@@ -2,11 +2,11 @@
declare(strict_types=1);
-namespace Rsgrinko\MailService\Facades;
+namespace Rsgrinko\MailServiceSdk\Facades;
use Illuminate\Support\Facades\Facade;
-use Rsgrinko\MailService\Client;
-use Rsgrinko\MailService\Message;
+use Rsgrinko\MailServiceSdk\Client;
+use Rsgrinko\MailServiceSdk\Message;
/**
* @method static array send(Message|array $mail)
@@ -18,7 +18,7 @@ use Rsgrinko\MailService\Message;
* @method static array templates()
* @method static array health()
*
- * @see \Rsgrinko\MailService\Client
+ * @see \Rsgrinko\MailServiceSdk\Client
*/
class MailService extends Facade
{
diff --git a/src/MailServiceException.php b/src/MailServiceException.php
index a08ba63..2ae2278 100644
--- a/src/MailServiceException.php
+++ b/src/MailServiceException.php
@@ -2,7 +2,7 @@
declare(strict_types=1);
-namespace Rsgrinko\MailService;
+namespace Rsgrinko\MailServiceSdk;
use RuntimeException;
diff --git a/src/MailServiceProvider.php b/src/MailServiceProvider.php
index 4b9d309..283d9f1 100644
--- a/src/MailServiceProvider.php
+++ b/src/MailServiceProvider.php
@@ -2,13 +2,12 @@
declare(strict_types=1);
-namespace Rsgrinko\MailService;
+namespace Rsgrinko\MailServiceSdk;
use Illuminate\Http\Client\Factory;
-use Illuminate\Mail\MailManager;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\ServiceProvider;
-use Rsgrinko\MailService\Transport\MailServiceTransport;
+use Rsgrinko\MailServiceSdk\Transport\MailServiceTransport;
/**
* Регистрирует клиент API и почтовый транспорт mailerservice.
@@ -46,15 +45,29 @@ class MailServiceProvider extends ServiceProvider
], 'mailerservice-config');
}
+ // $config — настройки мейлера из config/mail.php. Метку, транспорт сервиса и
+ // режим отправки там можно переопределить: так заводятся несколько мейлеров
+ // с разными метками. Ключ transport в этом массиве занят именем драйвера,
+ // поэтому транспорт сервиса берётся из service_transport.
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),
+ $this->text($config['tag'] ?? null) ?? $this->text($settings['tag'] ?? null),
+ $this->text($config['service_transport'] ?? null) ?? $this->text($settings['transport'] ?? null),
+ (bool) ($config['sync'] ?? $settings['sync'] ?? false),
);
});
}
-}
\ No newline at end of file
+
+ /**
+ * Пустая строка и null для настройки — одно и то же: «не задано».
+ */
+ private function text(mixed $value): ?string
+ {
+ $value = is_string($value) ? trim($value) : '';
+
+ return $value !== '' ? $value : null;
+ }
+}
diff --git a/src/Message.php b/src/Message.php
index e1ef85b..d6cda43 100644
--- a/src/Message.php
+++ b/src/Message.php
@@ -2,7 +2,7 @@
declare(strict_types=1);
-namespace Rsgrinko\MailService;
+namespace Rsgrinko\MailServiceSdk;
/**
* Письмо для прямой отправки через клиент, без Laravel Mail.
diff --git a/src/Transport/MailServiceTransport.php b/src/Transport/MailServiceTransport.php
index 71168b7..3c577ce 100644
--- a/src/Transport/MailServiceTransport.php
+++ b/src/Transport/MailServiceTransport.php
@@ -2,15 +2,18 @@
declare(strict_types=1);
-namespace Rsgrinko\MailService\Transport;
+namespace Rsgrinko\MailServiceSdk\Transport;
use Psr\Log\LoggerInterface;
-use Rsgrinko\MailService\Client;
+use Rsgrinko\MailServiceSdk\Client;
+use Rsgrinko\MailServiceSdk\MailServiceException;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
+use Symfony\Component\Mailer\Exception\TransportException;
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\Header\UnstructuredHeader;
use Symfony\Component\Mime\MessageConverter;
use Symfony\Component\Mime\Part\DataPart;
@@ -32,13 +35,20 @@ class MailServiceTransport extends AbstractTransport
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',
+ 'to', 'cc', 'bcc', 'from', 'sender', 'reply-to', 'subject',
+ 'date', 'message-id', 'mime-version', 'content-type',
+ 'content-transfer-encoding', 'content-disposition', 'content-length',
+ 'return-path', 'dkim-signature',
];
+ /** Метка письма: Mailable::tag() кладёт её в этот заголовок */
+ private const TAG_HEADER = 'x-tag';
+
+ /** Произвольные данные: Mailable::metadata() кладёт их в X-Metadata-<ключ> */
+ private const META_PREFIX = 'x-metadata-';
+
private Client $client;
private ?string $tag;
private ?string $transport;
@@ -70,21 +80,28 @@ class MailServiceTransport extends AbstractTransport
$payload = $this->toPayload($original);
- if ($this->tag !== null && $this->tag !== '') {
+ // Метка из настроек запасная: та, что указана у самого письма, важнее
+ if (!isset($payload['tag']) && $this->tag !== null) {
$payload['tag'] = $this->tag;
}
- if ($this->transport !== null && $this->transport !== '') {
+ if ($this->transport !== null) {
$payload['transport'] = $this->transport;
}
- if ($this->sync) {
- $this->client->sendNow($payload);
-
- return;
+ try {
+ $result = $this->sync ? $this->client->sendNow($payload) : $this->client->send($payload);
+ } catch (MailServiceException $e) {
+ // Symfony и Laravel ждут от транспорта именно TransportExceptionInterface:
+ // иначе failover и round-robin не переключатся на следующий транспорт
+ throw new TransportException($e->getMessage(), $e->getCode(), $e);
}
- $this->client->send($payload);
+ // Идентификатор письма в сервисе: по нему письмо ищется в панели,
+ // приложению он приходит в событии MessageSent
+ if (isset($result['id']) && is_string($result['id'])) {
+ $message->setMessageId($result['id']);
+ }
}
public function __toString(): string
@@ -137,17 +154,12 @@ class MailServiceTransport extends AbstractTransport
$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;
+ return array_merge($payload, $this->headers($email));
}
/**
@@ -166,56 +178,99 @@ class MailServiceTransport extends AbstractTransport
private function attachment(DataPart $part): array
{
$item = [
- 'name' => $part->getFilename() ?? 'attachment',
- 'content' => base64_encode($part->getBody()),
+ 'name' => $part->getFilename() ?? 'attachment',
+ 'content' => base64_encode($part->getBody()),
+ 'content_type' => $part->getContentType(),
];
- if ($part->getContentType() !== 'application/octet-stream') {
- $item['content_type'] = $part->getContentType();
+ if ($part->getDisposition() !== 'inline') {
+ return $item;
}
- if ($part->getDisposition() === 'inline') {
- $item['inline'] = true;
- }
+ $item['inline'] = true;
- if ($part->hasContentId()) {
- $item['cid'] = $part->getContentId();
- }
+ // В HTML картинка помечена как cid:<имя>, а на настоящий Content-ID это имя
+ // меняет Symfony при сборке письма. Письмо собирает сервис, поэтому cid берём
+ // тот, на который ссылается HTML: имя части, если Content-ID не задан явно.
+ $item['cid'] = $part->hasContentId()
+ ? $part->getContentId()
+ : ($part->getName() ?? $item['name']);
return $item;
}
/**
- * Пользовательские заголовки письма (X-*, кастомные) для передачи в сервис.
+ * Заголовки письма: служебные отбрасываем, метку и метаданные Laravel
+ * (Mailable::tag() и Mailable::metadata()) переносим в поля API.
*
- * @return array
+ * @return array
*/
- private function customHeaders(Email $email): array
+ private function headers(Email $email): array
{
+ $result = [];
$headers = [];
+ $meta = [];
foreach ($email->getHeaders()->all() as $header) {
- $name = $header->getName();
+ $name = $header->getName();
+ $lower = strtolower($name);
- if (in_array($name, self::SKIP_HEADERS, true) || str_starts_with($name, 'X-Symfony')) {
+ if (in_array($lower, self::SKIP_HEADERS, true) || str_starts_with($lower, 'x-symfony')) {
continue;
}
- $value = $header->getBodyAsString();
- if ($value !== '') {
- $headers[$name] = $value;
+ // getBodyAsString() отдаёт значение уже закодированным (=?utf-8?Q?…?=),
+ // а кодировать заголовки — дело сервиса, ему нужен исходный текст
+ $value = $header instanceof UnstructuredHeader ? $header->getBody() : $header->getBodyAsString();
+ if ($value === '') {
+ continue;
}
+
+ if ($lower === self::TAG_HEADER) {
+ $result['tag'] = $value;
+ continue;
+ }
+
+ if (str_starts_with($lower, self::META_PREFIX)) {
+ $meta[substr($name, strlen(self::META_PREFIX))] = $value;
+ continue;
+ }
+
+ $headers[$name] = $value;
}
- return $headers;
+ if ($headers !== []) {
+ $result['headers'] = $headers;
+ }
+
+ if ($meta !== []) {
+ $result['meta'] = $meta;
+ }
+
+ return $result;
}
+ /**
+ * Тело письма Symfony держит строкой или потоком.
+ */
private function asString(mixed $body): string
{
if ($body === null) {
return '';
}
- return is_string($body) ? $body : (string) stream_get_contents($body);
+ if (is_string($body)) {
+ return $body;
+ }
+
+ if (!is_resource($body)) {
+ return '';
+ }
+
+ if (stream_get_meta_data($body)['seekable']) {
+ rewind($body);
+ }
+
+ return (string) stream_get_contents($body);
}
-}
\ No newline at end of file
+}