Skip to content

Add Mailer send and debug commands #43687

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

Closed
wants to merge 1 commit into from
Closed
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
1 change: 1 addition & 0 deletions src/Symfony/Bundle/FrameworkBundle/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ CHANGELOG
`Symfony\Component\Serializer\Normalizer\NormalizerInterface` or implement `NormalizerAwareInterface` instead
* Add service usages list to the `debug:container` command output
* Add service and alias deprecation message to `debug:container [<name>]` output
* Add a `mailer:send` command

6.1
---
Expand Down
127 changes: 127 additions & 0 deletions src/Symfony/Bundle/FrameworkBundle/Command/MailerSendCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
<?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\Bundle\FrameworkBundle\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;

/**
* A console command to send an email via Symfony Mailer.
*
* @author Fritz Michael Gschwantner <fmg@inspiredminds.at>
*/
final class MailerSendCommand extends Command
{
protected static $defaultName = 'mailer:send';
protected static $defaultDescription = 'Sends an email message';

private $io;
private $mailer;

public function __construct(MailerInterface $mailer)
{
parent::__construct();

$this->mailer = $mailer;
}

protected function configure()
{
$this
->addOption('from', null, InputOption::VALUE_REQUIRED, 'The sender of the message')
->addOption('to', null, InputOption::VALUE_REQUIRED, 'The recipient of the message')
->addOption('subject', null, InputOption::VALUE_REQUIRED, 'The subject of the message')
->addOption('body', null, InputOption::VALUE_REQUIRED, 'The body of the message')
->addOption('transport', null, InputOption::VALUE_OPTIONAL, 'The transport to be used')
->addOption('content-type', null, InputOption::VALUE_REQUIRED, 'The body content type of the message', 'text/plain')
->addOption('charset', null, InputOption::VALUE_REQUIRED, 'The body charset of the message', 'utf-8')
->addOption('body-source', null, InputOption::VALUE_REQUIRED, 'The source of the body [stdin|file]', 'stdin')
->setHelp(
<<<EOF
The <info>%command.name%</info> command creates and sends a simple email message.

<info>php %command.full_name% --transport=custom_transport --content-type=text/html</info>

You can get the body of a message from a file:
<info>php %command.full_name% --body-source=file --body=/path/to/file</info>

EOF
);
}

protected function execute(InputInterface $input, OutputInterface $output)
{
switch ($input->getOption('body-source')) {
case 'file':
$filename = $input->getOption('body');
$content = file_get_contents($filename);
if (false === $content) {
throw new \Exception(sprintf('Could not get contents from "%s".', $filename));
}
$input->setOption('body', $content);
break;
case 'stdin':
break;
default:
throw new \InvalidArgumentException('body-source option should be "stdin" or "file".');
}

$this->mailer->send($this->createMessage($input));
$this->io->success('Email was successfully sent.');

return Command::SUCCESS;
}

protected function initialize(InputInterface $input, OutputInterface $output)
{
$this->io = new SymfonyStyle($input, $output);
$this->io->title('Symfony Mailer\'s Interactive Email Sender');
}

protected function interact(InputInterface $input, OutputInterface $output)
{
foreach ($input->getOptions() as $option => $value) {
if (null === $value && 'transport' !== $option) {
$input->setOption($option, $this->io->ask(sprintf('%s', ucfirst($option))));
}
}
}

private function createMessage(InputInterface $input): Email
{
$contentType = $input->getOption('content-type');

if (!\in_array($contentType, ['text/plain', 'text/html'], true)) {
throw new \InvalidArgumentException(sprintf('Invalid content-type "%s", only "text/plain" and "text/html" allowed.', $contentType));
}

$type = 'text/html' === $contentType ? 'html' : 'text';

$message = (new Email())
->subject($input->getOption('subject'))
->from($input->getOption('from'))
->to($input->getOption('to'))
->{$type}($input->getOption('body'), $input->getOption('charset'))
;

if ($transport = $input->getOption('transport')) {
$message->getHeaders()->addTextHeader('X-Transport', $transport);
}

return $message;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -533,6 +533,16 @@ public function load(array $configs, ContainerBuilder $container)
}
}

if ($this->httpClientConfigEnabled = $this->isConfigEnabled($container, $config['http_client'])) {
$this->registerHttpClientConfiguration($config['http_client'], $container, $loader, $config['profiler']);
}

if ($this->mailerConfigEnabled = $this->isConfigEnabled($container, $config['mailer'])) {
$this->registerMailerConfiguration($config['mailer'], $container, $loader);
} else {
$container->removeDefinition('console.command.mailer_send');
}

// notifier depends on messenger, mailer being registered
if ($this->notifierConfigEnabled = $this->isConfigEnabled($container, $config['notifier'])) {
$this->registerNotifierConfiguration($config['notifier'], $container, $loader);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
use Symfony\Bundle\FrameworkBundle\Command\ContainerLintCommand;
use Symfony\Bundle\FrameworkBundle\Command\DebugAutowiringCommand;
use Symfony\Bundle\FrameworkBundle\Command\EventDispatcherDebugCommand;
use Symfony\Bundle\FrameworkBundle\Command\MailerSendCommand;
use Symfony\Bundle\FrameworkBundle\Command\RouterDebugCommand;
use Symfony\Bundle\FrameworkBundle\Command\RouterMatchCommand;
use Symfony\Bundle\FrameworkBundle\Command\SecretsDecryptToLocalCommand;
Expand Down Expand Up @@ -150,6 +151,12 @@
])
->tag('console.command')

->set('console.command.mailer_send', MailerSendCommand::class)
->args([
service('mailer'),
])
->tag('console.command')

->set('console.command.messenger_consume_messages', ConsumeMessagesCommand::class)
->args([
abstract_arg('Routable message bus'),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
<?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\Bundle\FrameworkBundle\Tests\Command;

use PHPUnit\Framework\TestCase;
use Symfony\Bundle\FrameworkBundle\Command\MailerSendCommand;
use Symfony\Component\Console\Tester\CommandTester;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;

/**
* @author Fritz Michael Gschwantner <fmg@inspiredminds.at>
*/
class MailerSendCommandTest extends TestCase
{
public function testSendsEmail()
{
$from = 'from@example.com';
$to = 'to@example.com';
$subject = 'Foobar';
$body = 'Lorem ipsum dolor sit amet.';

$mailer = $this->createMock(MailerInterface::class);
$mailer
->expects($this->once())
->method('send')
->with(self::callback(static function (Email $message) use ($from, $to, $subject, $body): bool {
return
$message->getFrom()[0]->getAddress() === $from &&
$message->getTo()[0]->getAddress() === $to &&
$message->getSubject() === $subject &&
$message->getTextBody() === $body
;
}))
;

$command = new MailerSendCommand($mailer);

$tester = new CommandTester($command);
$tester->execute([
'--from' => $from,
'--to' => $to,
'--subject' => $subject,
'--body' => $body,
]);
}

public function testUsesCustomTransport()
{
$transport = 'foobar';

$mailer = $this->createMock(MailerInterface::class);
$mailer
->expects($this->once())
->method('send')
->with(self::callback(static function (Email $message) use ($transport): bool {
return $message->getHeaders()->getHeaderBody('X-Transport') === $transport;
}))
;

$command = new MailerSendCommand($mailer);

$tester = new CommandTester($command);
$tester->execute([
'--from' => 'from@example.com',
'--to' => 'to@example.com',
'--subject' => 'Foobar',
'--body' => 'Lorem ipsum dolor sit amet.',
'--transport' => $transport,
]);
}
}