исправление работы бублиотеки, смена namespace
This commit is contained in:
1 parent
8d0bdd2756
commit
94ad0f462f
8 files changed
+180
-78
No files matched your search
@@ -4,7 +4,7 @@
|
|||||||
Работает и как обычный почтовый транспорт (`config/mail.php`), и как прямой
|
Работает и как обычный почтовый транспорт (`config/mail.php`), и как прямой
|
||||||
клиент API — для статусов, шаблонов и отправки по шаблону без Laravel Mail.
|
клиент 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-письма
|
||||||
раскладываются автоматически; пользовательские заголовки (кроме служебных)
|
раскладываются автоматически; пользовательские заголовки (кроме служебных)
|
||||||
передаются как есть. Приоритет Symfony (1–5) ложится на приоритет очереди
|
передаются как есть. Приоритет Symfony (1–5) ложится на приоритет очереди
|
||||||
сервиса, обычные письма уходят с 100.
|
сервиса, обычные письма уходят с 100. Метка и метаданные письма
|
||||||
|
(`Mailable::tag()`, `Mailable::metadata()`) ложатся в поля `tag` и `meta` —
|
||||||
|
метка у письма важнее той, что задана в настройках.
|
||||||
|
|
||||||
|
Картинки внутри HTML (`$message->embed(...)`, `<img src="cid:...">`) уходят
|
||||||
|
вложениями с тем же `cid`, на который ссылается разметка, — MIME собирает
|
||||||
|
сервис.
|
||||||
|
|
||||||
Если в настройках стоит `MAILERSERVICE_SYNC=true`, транспорт дожидается
|
Если в настройках стоит `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
|
## Прямой клиент API
|
||||||
|
|
||||||
Клиент лежит в контейнере, наружу — фасад `MailService`:
|
Клиент лежит в контейнере, наружу — фасад `MailService`:
|
||||||
|
|
||||||
```php
|
```php
|
||||||
use Rsgrinko\MailService\Message;
|
use Rsgrinko\MailServiceSdk\Message;
|
||||||
|
|
||||||
// письмо по шаблону сервиса
|
// письмо по шаблону сервиса
|
||||||
$result = MailService::send(
|
$result = MailService::send(
|
||||||
@@ -124,10 +147,10 @@ Message::to('user@example.com')
|
|||||||
|
|
||||||
## Обработка ошибок
|
## Обработка ошибок
|
||||||
|
|
||||||
Все методы бросают `Rsgrinko\MailService\MailServiceException`:
|
Все методы бросают `Rsgrinko\MailServiceSdk\MailServiceException`:
|
||||||
|
|
||||||
```php
|
```php
|
||||||
use Rsgrinko\MailService\MailServiceException;
|
use Rsgrinko\MailServiceSdk\MailServiceException;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
MailService::send(Message::to('user@example.com')->subject('Привет')->text('Тело'));
|
MailService::send(Message::to('user@example.com')->subject('Привет')->text('Тело'));
|
||||||
|
|||||||
+11
-9
@@ -11,25 +11,27 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"require": {
|
"require": {
|
||||||
"php": "^8.3",
|
"php": "^8.2",
|
||||||
"illuminate/support": "^13.0",
|
"ext-json": "*",
|
||||||
"illuminate/http": "^13.0",
|
"illuminate/support": "^11.0 || ^12.0 || ^13.0",
|
||||||
"illuminate/mail": "^13.0",
|
"illuminate/http": "^11.0 || ^12.0 || ^13.0",
|
||||||
"symfony/mailer": "^7.0",
|
"illuminate/mail": "^11.0 || ^12.0 || ^13.0",
|
||||||
"symfony/mime": "^7.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": {
|
"autoload": {
|
||||||
"psr-4": {
|
"psr-4": {
|
||||||
"Rsgrinko\\MailService\\": "src/"
|
"Rsgrinko\\MailServiceSdk\\": "src/"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"extra": {
|
"extra": {
|
||||||
"laravel": {
|
"laravel": {
|
||||||
"providers": [
|
"providers": [
|
||||||
"Rsgrinko\\MailService\\MailServiceProvider"
|
"Rsgrinko\\MailServiceSdk\\MailServiceProvider"
|
||||||
],
|
],
|
||||||
"aliases": {
|
"aliases": {
|
||||||
"MailService": "Rsgrinko\\MailService\\Facades\\MailService"
|
"MailService": "Rsgrinko\\MailServiceSdk\\Facades\\MailService"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
+26
-17
@@ -2,16 +2,13 @@
|
|||||||
|
|
||||||
declare(strict_types=1);
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Rsgrinko\MailService;
|
namespace Rsgrinko\MailServiceSdk;
|
||||||
|
|
||||||
use Illuminate\Http\Client\ConnectionException;
|
use Illuminate\Http\Client\ConnectionException;
|
||||||
use Illuminate\Http\Client\Factory;
|
use Illuminate\Http\Client\Factory;
|
||||||
use Illuminate\Http\Client\PendingRequest;
|
use Illuminate\Http\Client\PendingRequest;
|
||||||
use Illuminate\Http\Client\Response;
|
use Illuminate\Http\Client\Response;
|
||||||
use Illuminate\Support\Facades\Http;
|
use Illuminate\Support\Facades\Http;
|
||||||
use Throwable;
|
|
||||||
|
|
||||||
use function retry;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* HTTP-клиент API сервиса. Каждый метод — один запрос; ошибки сервиса
|
* HTTP-клиент API сервиса. Каждый метод — один запрос; ошибки сервиса
|
||||||
@@ -86,9 +83,7 @@ class Client
|
|||||||
*/
|
*/
|
||||||
public function messages(array $filters = []): array
|
public function messages(array $filters = []): array
|
||||||
{
|
{
|
||||||
$query = $filters === [] ? '' : '?' . http_build_query($filters);
|
return $this->sendJson('GET', '/api/v1/messages', $filters);
|
||||||
|
|
||||||
return $this->sendJson('GET', '/api/v1/messages' . $query);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -133,27 +128,36 @@ class Client
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Запрос с повторами: если сервис не ответил (обрыв сети), пробуем ещё раз.
|
* Запрос с повторами: если сервис не ответил (обрыв сети), пробуем ещё раз.
|
||||||
* Ответ с ошибкой приложения не повторяется.
|
* Ответ с ошибкой приложения не повторяется — повторять 401 или 422 бессмысленно.
|
||||||
|
*
|
||||||
|
* Свой цикл, а не retry() из Http-клиента: тот повторяет и на неуспешный ответ.
|
||||||
*
|
*
|
||||||
* @param array<string, mixed>|null $payload
|
* @param array<string, mixed>|null $payload
|
||||||
* @return array<string, mixed>
|
* @return array<string, mixed>
|
||||||
*/
|
*/
|
||||||
private function sendJson(string $method, string $path, ?array $payload = null): array
|
private function sendJson(string $method, string $path, ?array $payload = null): array
|
||||||
{
|
{
|
||||||
|
$attempt = 0;
|
||||||
|
|
||||||
|
while (true) {
|
||||||
try {
|
try {
|
||||||
return retry(
|
return $this->execute($method, $path, $payload);
|
||||||
$this->retries + 1,
|
|
||||||
fn (): array => $this->execute($method, $path, $payload),
|
|
||||||
$this->retryDelay,
|
|
||||||
static fn (Throwable $e): bool => $e instanceof ConnectionException,
|
|
||||||
);
|
|
||||||
} catch (ConnectionException $e) {
|
} catch (ConnectionException $e) {
|
||||||
|
if ($attempt >= $this->retries) {
|
||||||
throw new MailServiceException('Сервис недоступен: ' . $e->getMessage(), 0, [], [], $e);
|
throw new MailServiceException('Сервис недоступен: ' . $e->getMessage(), 0, [], [], $e);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$attempt++;
|
||||||
|
|
||||||
|
if ($this->retryDelay > 0) {
|
||||||
|
usleep($this->retryDelay * 1000);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param array<string, mixed>|null $payload
|
* @param array<string, mixed>|null $payload для GET — параметры строки запроса
|
||||||
* @return array<string, mixed>
|
* @return array<string, mixed>
|
||||||
*/
|
*/
|
||||||
private function execute(string $method, string $path, ?array $payload): array
|
private function execute(string $method, string $path, ?array $payload): array
|
||||||
@@ -161,7 +165,7 @@ class Client
|
|||||||
$request = $this->pending();
|
$request = $this->pending();
|
||||||
|
|
||||||
$response = match ($method) {
|
$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),
|
'POST' => $payload === null ? $request->post($path) : $request->post($path, $payload),
|
||||||
'DELETE' => $request->delete($path),
|
'DELETE' => $request->delete($path),
|
||||||
default => throw new MailServiceException('Неподдерживаемый метод: ' . $method),
|
default => throw new MailServiceException('Неподдерживаемый метод: ' . $method),
|
||||||
@@ -201,7 +205,12 @@ class Client
|
|||||||
}
|
}
|
||||||
|
|
||||||
$decoded = is_array($decoded) ? $decoded : [];
|
$decoded = is_array($decoded) ? $decoded : [];
|
||||||
$message = (string) ($decoded['error']['message'] ?? 'Сервис ответил кодом ' . $status);
|
|
||||||
|
// 502 при sync — это не ошибка формата: письмо принято, но отправить не вышло,
|
||||||
|
// причина лежит в info, а блока error в таком ответе нет
|
||||||
|
$message = (string) ($decoded['error']['message']
|
||||||
|
?? $decoded['info']
|
||||||
|
?? 'Сервис ответил кодом ' . $status);
|
||||||
$errors = (array) ($decoded['error']['details']['errors'] ?? []);
|
$errors = (array) ($decoded['error']['details']['errors'] ?? []);
|
||||||
|
|
||||||
throw new MailServiceException($message, $status, $errors, $decoded);
|
throw new MailServiceException($message, $status, $errors, $decoded);
|
||||||
|
|||||||
@@ -2,11 +2,11 @@
|
|||||||
|
|
||||||
declare(strict_types=1);
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Rsgrinko\MailService\Facades;
|
namespace Rsgrinko\MailServiceSdk\Facades;
|
||||||
|
|
||||||
use Illuminate\Support\Facades\Facade;
|
use Illuminate\Support\Facades\Facade;
|
||||||
use Rsgrinko\MailService\Client;
|
use Rsgrinko\MailServiceSdk\Client;
|
||||||
use Rsgrinko\MailService\Message;
|
use Rsgrinko\MailServiceSdk\Message;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @method static array send(Message|array $mail)
|
* @method static array send(Message|array $mail)
|
||||||
@@ -18,7 +18,7 @@ use Rsgrinko\MailService\Message;
|
|||||||
* @method static array templates()
|
* @method static array templates()
|
||||||
* @method static array health()
|
* @method static array health()
|
||||||
*
|
*
|
||||||
* @see \Rsgrinko\MailService\Client
|
* @see \Rsgrinko\MailServiceSdk\Client
|
||||||
*/
|
*/
|
||||||
class MailService extends Facade
|
class MailService extends Facade
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
declare(strict_types=1);
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Rsgrinko\MailService;
|
namespace Rsgrinko\MailServiceSdk;
|
||||||
|
|
||||||
use RuntimeException;
|
use RuntimeException;
|
||||||
|
|
||||||
|
|||||||
@@ -2,13 +2,12 @@
|
|||||||
|
|
||||||
declare(strict_types=1);
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Rsgrinko\MailService;
|
namespace Rsgrinko\MailServiceSdk;
|
||||||
|
|
||||||
use Illuminate\Http\Client\Factory;
|
use Illuminate\Http\Client\Factory;
|
||||||
use Illuminate\Mail\MailManager;
|
|
||||||
use Illuminate\Support\Facades\Mail;
|
use Illuminate\Support\Facades\Mail;
|
||||||
use Illuminate\Support\ServiceProvider;
|
use Illuminate\Support\ServiceProvider;
|
||||||
use Rsgrinko\MailService\Transport\MailServiceTransport;
|
use Rsgrinko\MailServiceSdk\Transport\MailServiceTransport;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Регистрирует клиент API и почтовый транспорт mailerservice.
|
* Регистрирует клиент API и почтовый транспорт mailerservice.
|
||||||
@@ -46,15 +45,29 @@ class MailServiceProvider extends ServiceProvider
|
|||||||
], 'mailerservice-config');
|
], 'mailerservice-config');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// $config — настройки мейлера из config/mail.php. Метку, транспорт сервиса и
|
||||||
|
// режим отправки там можно переопределить: так заводятся несколько мейлеров
|
||||||
|
// с разными метками. Ключ transport в этом массиве занят именем драйвера,
|
||||||
|
// поэтому транспорт сервиса берётся из service_transport.
|
||||||
Mail::extend('mailerservice', function (array $config): MailServiceTransport {
|
Mail::extend('mailerservice', function (array $config): MailServiceTransport {
|
||||||
$settings = (array) $this->app['config']->get('mailerservice', []);
|
$settings = (array) $this->app['config']->get('mailerservice', []);
|
||||||
|
|
||||||
return new MailServiceTransport(
|
return new MailServiceTransport(
|
||||||
$this->app->make(Client::class),
|
$this->app->make(Client::class),
|
||||||
isset($settings['tag']) && $settings['tag'] !== '' ? (string) $settings['tag'] : null,
|
$this->text($config['tag'] ?? null) ?? $this->text($settings['tag'] ?? null),
|
||||||
isset($settings['transport']) && $settings['transport'] !== '' ? (string) $settings['transport'] : null,
|
$this->text($config['service_transport'] ?? null) ?? $this->text($settings['transport'] ?? null),
|
||||||
(bool) ($settings['sync'] ?? false),
|
(bool) ($config['sync'] ?? $settings['sync'] ?? false),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Пустая строка и null для настройки — одно и то же: «не задано».
|
||||||
|
*/
|
||||||
|
private function text(mixed $value): ?string
|
||||||
|
{
|
||||||
|
$value = is_string($value) ? trim($value) : '';
|
||||||
|
|
||||||
|
return $value !== '' ? $value : null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+1
-1
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
declare(strict_types=1);
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Rsgrinko\MailService;
|
namespace Rsgrinko\MailServiceSdk;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Письмо для прямой отправки через клиент, без Laravel Mail.
|
* Письмо для прямой отправки через клиент, без Laravel Mail.
|
||||||
|
|||||||
@@ -2,15 +2,18 @@
|
|||||||
|
|
||||||
declare(strict_types=1);
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Rsgrinko\MailService\Transport;
|
namespace Rsgrinko\MailServiceSdk\Transport;
|
||||||
|
|
||||||
use Psr\Log\LoggerInterface;
|
use Psr\Log\LoggerInterface;
|
||||||
use Rsgrinko\MailService\Client;
|
use Rsgrinko\MailServiceSdk\Client;
|
||||||
|
use Rsgrinko\MailServiceSdk\MailServiceException;
|
||||||
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
|
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
|
||||||
|
use Symfony\Component\Mailer\Exception\TransportException;
|
||||||
use Symfony\Component\Mailer\SentMessage;
|
use Symfony\Component\Mailer\SentMessage;
|
||||||
use Symfony\Component\Mailer\Transport\AbstractTransport;
|
use Symfony\Component\Mailer\Transport\AbstractTransport;
|
||||||
use Symfony\Component\Mime\Address;
|
use Symfony\Component\Mime\Address;
|
||||||
use Symfony\Component\Mime\Email;
|
use Symfony\Component\Mime\Email;
|
||||||
|
use Symfony\Component\Mime\Header\UnstructuredHeader;
|
||||||
use Symfony\Component\Mime\MessageConverter;
|
use Symfony\Component\Mime\MessageConverter;
|
||||||
use Symfony\Component\Mime\Part\DataPart;
|
use Symfony\Component\Mime\Part\DataPart;
|
||||||
|
|
||||||
@@ -32,13 +35,20 @@ class MailServiceTransport extends AbstractTransport
|
|||||||
Email::PRIORITY_LOWEST => 200,
|
Email::PRIORITY_LOWEST => 200,
|
||||||
];
|
];
|
||||||
|
|
||||||
/** Заголовки, которые сервис заполнит сам, — их не шлём */
|
/** Заголовки, которые сервис заполнит сам, — их не шлём. Имена в нижнем регистре */
|
||||||
private const SKIP_HEADERS = [
|
private const SKIP_HEADERS = [
|
||||||
'To', 'Cc', 'Bcc', 'From', 'Reply-To', 'Subject',
|
'to', 'cc', 'bcc', 'from', 'sender', 'reply-to', 'subject',
|
||||||
'Date', 'Message-ID', 'MIME-Version', 'Content-Type',
|
'date', 'message-id', 'mime-version', 'content-type',
|
||||||
'Content-Transfer-Encoding', 'Content-Disposition', 'Return-Path',
|
'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 Client $client;
|
||||||
private ?string $tag;
|
private ?string $tag;
|
||||||
private ?string $transport;
|
private ?string $transport;
|
||||||
@@ -70,21 +80,28 @@ class MailServiceTransport extends AbstractTransport
|
|||||||
|
|
||||||
$payload = $this->toPayload($original);
|
$payload = $this->toPayload($original);
|
||||||
|
|
||||||
if ($this->tag !== null && $this->tag !== '') {
|
// Метка из настроек запасная: та, что указана у самого письма, важнее
|
||||||
|
if (!isset($payload['tag']) && $this->tag !== null) {
|
||||||
$payload['tag'] = $this->tag;
|
$payload['tag'] = $this->tag;
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($this->transport !== null && $this->transport !== '') {
|
if ($this->transport !== null) {
|
||||||
$payload['transport'] = $this->transport;
|
$payload['transport'] = $this->transport;
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($this->sync) {
|
try {
|
||||||
$this->client->sendNow($payload);
|
$result = $this->sync ? $this->client->sendNow($payload) : $this->client->send($payload);
|
||||||
|
} catch (MailServiceException $e) {
|
||||||
return;
|
// 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
|
public function __toString(): string
|
||||||
@@ -137,17 +154,12 @@ class MailServiceTransport extends AbstractTransport
|
|||||||
$payload['attachments'][] = $this->attachment($part);
|
$payload['attachments'][] = $this->attachment($part);
|
||||||
}
|
}
|
||||||
|
|
||||||
$headers = $this->customHeaders($email);
|
|
||||||
if ($headers !== []) {
|
|
||||||
$payload['headers'] = $headers;
|
|
||||||
}
|
|
||||||
|
|
||||||
$priority = self::PRIORITY_MAP[$email->getPriority()] ?? 100;
|
$priority = self::PRIORITY_MAP[$email->getPriority()] ?? 100;
|
||||||
if ($priority !== 100) {
|
if ($priority !== 100) {
|
||||||
$payload['priority'] = $priority;
|
$payload['priority'] = $priority;
|
||||||
}
|
}
|
||||||
|
|
||||||
return $payload;
|
return array_merge($payload, $this->headers($email));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -168,54 +180,97 @@ class MailServiceTransport extends AbstractTransport
|
|||||||
$item = [
|
$item = [
|
||||||
'name' => $part->getFilename() ?? 'attachment',
|
'name' => $part->getFilename() ?? 'attachment',
|
||||||
'content' => base64_encode($part->getBody()),
|
'content' => base64_encode($part->getBody()),
|
||||||
|
'content_type' => $part->getContentType(),
|
||||||
];
|
];
|
||||||
|
|
||||||
if ($part->getContentType() !== 'application/octet-stream') {
|
if ($part->getDisposition() !== 'inline') {
|
||||||
$item['content_type'] = $part->getContentType();
|
return $item;
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($part->getDisposition() === 'inline') {
|
|
||||||
$item['inline'] = true;
|
$item['inline'] = true;
|
||||||
}
|
|
||||||
|
|
||||||
if ($part->hasContentId()) {
|
// В HTML картинка помечена как cid:<имя>, а на настоящий Content-ID это имя
|
||||||
$item['cid'] = $part->getContentId();
|
// меняет Symfony при сборке письма. Письмо собирает сервис, поэтому cid берём
|
||||||
}
|
// тот, на который ссылается HTML: имя части, если Content-ID не задан явно.
|
||||||
|
$item['cid'] = $part->hasContentId()
|
||||||
|
? $part->getContentId()
|
||||||
|
: ($part->getName() ?? $item['name']);
|
||||||
|
|
||||||
return $item;
|
return $item;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Пользовательские заголовки письма (X-*, кастомные) для передачи в сервис.
|
* Заголовки письма: служебные отбрасываем, метку и метаданные Laravel
|
||||||
|
* (Mailable::tag() и Mailable::metadata()) переносим в поля API.
|
||||||
*
|
*
|
||||||
* @return array<string, string>
|
* @return array<string, mixed>
|
||||||
*/
|
*/
|
||||||
private function customHeaders(Email $email): array
|
private function headers(Email $email): array
|
||||||
{
|
{
|
||||||
|
$result = [];
|
||||||
$headers = [];
|
$headers = [];
|
||||||
|
$meta = [];
|
||||||
|
|
||||||
foreach ($email->getHeaders()->all() as $header) {
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
$value = $header->getBodyAsString();
|
|
||||||
if ($value !== '') {
|
|
||||||
$headers[$name] = $value;
|
$headers[$name] = $value;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if ($headers !== []) {
|
||||||
|
$result['headers'] = $headers;
|
||||||
}
|
}
|
||||||
|
|
||||||
return $headers;
|
if ($meta !== []) {
|
||||||
|
$result['meta'] = $meta;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return $result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Тело письма Symfony держит строкой или потоком.
|
||||||
|
*/
|
||||||
private function asString(mixed $body): string
|
private function asString(mixed $body): string
|
||||||
{
|
{
|
||||||
if ($body === null) {
|
if ($body === null) {
|
||||||
return '';
|
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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user