Skip to content

[Mailer] Add support for multiple mailers #33409

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 2, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -1555,8 +1555,17 @@ private function addMailerSection(ArrayNodeDefinition $rootNode)
->arrayNode('mailer')
->info('Mailer configuration')
->{!class_exists(FullStack::class) && class_exists(Mailer::class) ? 'canBeDisabled' : 'canBeEnabled'}()
->validate()
->ifTrue(function ($v) { return isset($v['dsn']) && \count($v['transports']); })
->thenInvalid('"dsn" and "transports" cannot be used together.')
->end()
->fixXmlConfig('transport')
->children()
->scalarNode('dsn')->defaultValue('smtp://null')->end()
->scalarNode('dsn')->defaultNull()->end()
->arrayNode('transports')
->useAttributeAsKey('name')
->prototype('scalar')->end()
->end()
->arrayNode('envelope')
->info('Mailer Envelope configuration')
->children()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1977,7 +1977,12 @@ private function registerMailerConfiguration(array $config, ContainerBuilder $co

$loader->load('mailer.xml');
$loader->load('mailer_transports.xml');
$container->getDefinition('mailer.default_transport')->setArgument(0, $config['dsn']);
if (!\count($config['transports']) && null === $config['dsn']) {
$config['dsn'] = 'smtp://null';
}
$transports = $config['dsn'] ? ['main' => $config['dsn']] : $config['transports'];
$container->getDefinition('mailer.transports')->setArgument(0, $transports);
$container->getDefinition('mailer.default_transport')->setArgument(0, current($transports));

$classToServices = [
SesTransportFactory::class => 'mailer.transport_factory.amazon',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,18 @@

<services>
<service id="mailer.mailer" class="Symfony\Component\Mailer\Mailer">
<argument type="service" id="mailer.default_transport" />
<argument type="service" id="mailer.transports" />
<argument type="service" id="messenger.default_bus" on-invalid="ignore" />
<argument type="service" id="event_dispatcher" on-invalid="ignore" />
</service>
<service id="mailer" alias="mailer.mailer" />
<service id="Symfony\Component\Mailer\MailerInterface" alias="mailer.mailer" />

<service id="mailer.transports" class="Symfony\Component\Mailer\Transports">
<factory service="mailer.transport_factory" method="fromStrings" />
<argument type="collection" /> <!-- transports -->
</service>

<service id="mailer.transport_factory" class="Symfony\Component\Mailer\Transport">
<argument type="tagged_iterator" tag="mailer.transport_factory" />
</service>
Expand All @@ -24,7 +29,7 @@
<service id="Symfony\Component\Mailer\Transport\TransportInterface" alias="mailer.default_transport" />

<service id="mailer.messenger.message_handler" class="Symfony\Component\Mailer\Messenger\MessageHandler">
<argument type="service" id="mailer.default_transport" />
<argument type="service" id="mailer.transports" />
<tag name="messenger.message_handler" />
</service>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -369,7 +369,8 @@ class_exists(SemaphoreStore::class) && SemaphoreStore::isSupported() ? 'semaphor
'scoped_clients' => [],
],
'mailer' => [
'dsn' => 'smtp://null',
'dsn' => null,
'transports' => [],
'enabled' => !class_exists(FullStack::class) && class_exists(Mailer::class),
],
];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ protected function doSend(SentMessage $message): void
}
};

$mailer = new Mailer($testTransport, null);
$mailer = new Mailer($testTransport);

$message = (new Email())
->subject('Test subject')
Expand Down
1 change: 1 addition & 0 deletions src/Symfony/Component/Mailer/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ CHANGELOG
4.4.0
-----

* added support for multiple transports on a `Mailer` instance
* [BC BREAK] removed the `auth_mode` DSN option (it is now always determined automatically)
* STARTTLS cannot be enabled anymore (it is used automatically if TLS is disabled and the server supports STARTTLS)
* [BC BREAK] Removed the `encryption` DSN option (use `smtps` instead)
Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Component/Mailer/Mailer.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
/**
* @author Fabien Potencier <fabien@symfony.com>
*/
class Mailer implements MailerInterface
final class Mailer implements MailerInterface
{
private $transport;
private $bus;
Expand Down
18 changes: 18 additions & 0 deletions src/Symfony/Component/Mailer/Transport.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
use Symfony\Component\Mailer\Transport\Smtp\EsmtpTransportFactory;
use Symfony\Component\Mailer\Transport\TransportFactoryInterface;
use Symfony\Component\Mailer\Transport\TransportInterface;
use Symfony\Component\Mailer\Transport\Transports;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;

Expand Down Expand Up @@ -54,6 +55,13 @@ public static function fromDsn(string $dsn, EventDispatcherInterface $dispatcher
return $factory->fromString($dsn);
}

public static function fromDsns(array $dsns, EventDispatcherInterface $dispatcher = null, HttpClientInterface $client = null, LoggerInterface $logger = null): TransportInterface
{
$factory = new self(iterator_to_array(self::getDefaultFactories($dispatcher, $client, $logger)));

return $factory->fromStrings($dsns);
}

/**
* @param TransportFactoryInterface[] $factories
*/
Expand All @@ -62,6 +70,16 @@ public function __construct(iterable $factories)
$this->factories = $factories;
}

public function fromStrings(array $dsns): Transports
{
$transports = [];
foreach ($dsns as $name => $dsn) {
$transports[$name] = $this->fromString($dsn);
}

return new Transports($transports);
}

public function fromString(string $dsn): TransportInterface
{
$dsns = preg_split('/\s++\|\|\s++/', $dsn);
Expand Down
69 changes: 69 additions & 0 deletions src/Symfony/Component/Mailer/Transport/Transports.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Mailer\Transport;

use Symfony\Component\Mailer\Exception\InvalidArgumentException;
use Symfony\Component\Mailer\Exception\LogicException;
use Symfony\Component\Mailer\SentMessage;
use Symfony\Component\Mailer\SmtpEnvelope;
use Symfony\Component\Mime\Message;
use Symfony\Component\Mime\RawMessage;

/**
* @author Fabien Potencier <fabien@symfony.com>
*/
class Transports implements TransportInterface
{
private $transports;
private $default;

/**
* @param TransportInterface[] $transports
*/
public function __construct(iterable $transports)
{
$this->transports = [];
foreach ($transports as $name => $transport) {
if (null === $this->default) {
$this->default = $transport;
}
$this->transports[$name] = $transport;
}

if (!$this->transports) {
throw new LogicException(sprintf('"%s" must have at least one transport configured.', __CLASS__));
}
}

public function send(RawMessage $message, SmtpEnvelope $envelope = null): ?SentMessage
{
/** @var Message $message */
if (RawMessage::class === \get_class($message) || !$message->getHeaders()->has('X-Transport')) {
return $this->default->send($message, $envelope);
}

$headers = $message->getHeaders();
$transport = $headers->get('X-Transport');
$headers->remove('X-Transport');

if (!isset($this->transports[$transport])) {
throw new InvalidArgumentException(sprintf('The "%s" transport does not exist.', $transport));
}

return $this->transports[$transport]->send($message, $envelope);
}

public function __toString(): string
{
return 'all';
}
}