Skip to content

Instantly share code, notes, and snippets.

@MaximePinot
Last active July 21, 2022 08:42
Show Gist options
  • Save MaximePinot/85ef21d21f06ada31c097709769eb084 to your computer and use it in GitHub Desktop.
Save MaximePinot/85ef21d21f06ada31c097709769eb084 to your computer and use it in GitHub Desktop.
Add the `mail_settings` field to the payload when using `symfony/sendgrid-mailer`
framework:
http_client:
scoped_clients:
sendgrid.client:
base_uri: 'https://api.sendgrid.com'
<?php
declare(strict_types=1);
namespace App;
use App\HttpClient\SendgridHttpClient;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;
final class Kernel extends BaseKernel implements CompilerPassInterface
{
use MicroKernelTrait;
public function process(ContainerBuilder $container)
{
// Injects the `SendgridHttpClient` decorator instead of the default HTTP Client.
// It adds the `mail_settings` field to the payload.
// @see: App\HttpClient\SendgridHttpClient
$container
->getDefinition('mailer.transport_factory.sendgrid')
->setArgument('$client', $container->getDefinition(SendgridHttpClient::class))
;
}
}
<?php
declare(strict_types=1);
namespace App\HttpClient;
use Symfony\Component\DependencyInjection\Attribute\AsDecorator;
use Symfony\Component\DependencyInjection\Attribute\MapDecorated;
use Symfony\Component\Mailer\Bridge\Sendgrid\Transport\SendgridApiTransport;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\HttpClient\ResponseInterface;
use Symfony\Contracts\HttpClient\ResponseStreamInterface;
use function json_encode;
/**
* Decorates the Sendgrid scoped client to add the `mail_settings` field to the payload.
*
* @see SendgridApiTransport
*/
#[AsDecorator('sendgrid.client')]
class SendgridHttpClient implements HttpClientInterface
{
public function __construct(#[MapDecorated] private readonly HttpClientInterface $inner)
{
}
public function request(string $method, string $url, array $options = []): ResponseInterface
{
$options['json']['mail_settings'] = [
'bypass_unsubscribe_management' => ['enable' => true],
];
return $this->inner->request($method, $url, $options);
}
public function stream(iterable|ResponseInterface $responses, ?float $timeout = null): ResponseStreamInterface
{
return $this->inner->stream($responses, $timeout);
}
public function withOptions(array $options): static
{
return new self($this->inner->withOptions($options));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment