MailerTestCommand.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Mailer\Command;
  11. use Symfony\Component\Console\Attribute\AsCommand;
  12. use Symfony\Component\Console\Command\Command;
  13. use Symfony\Component\Console\Input\InputArgument;
  14. use Symfony\Component\Console\Input\InputInterface;
  15. use Symfony\Component\Console\Input\InputOption;
  16. use Symfony\Component\Console\Output\OutputInterface;
  17. use Symfony\Component\Mailer\Transport\TransportInterface;
  18. use Symfony\Component\Mime\Email;
  19. /**
  20. * A console command to test Mailer transports.
  21. */
  22. #[AsCommand(name: 'mailer:test', description: 'Test Mailer transports by sending an email')]
  23. final class MailerTestCommand extends Command
  24. {
  25. public function __construct(private TransportInterface $transport)
  26. {
  27. parent::__construct();
  28. }
  29. protected function configure(): void
  30. {
  31. $this
  32. ->addArgument('to', InputArgument::REQUIRED, 'The recipient of the message')
  33. ->addOption('from', null, InputOption::VALUE_OPTIONAL, 'The sender of the message', 'from@example.org')
  34. ->addOption('subject', null, InputOption::VALUE_OPTIONAL, 'The subject of the message', 'Testing transport')
  35. ->addOption('body', null, InputOption::VALUE_OPTIONAL, 'The body of the message', 'Testing body')
  36. ->addOption('transport', null, InputOption::VALUE_OPTIONAL, 'The transport to be used')
  37. ->setHelp(<<<'EOF'
  38. The <info>%command.name%</info> command tests a Mailer transport by sending a simple email message:
  39. <info>php %command.full_name% to@example.com</info>
  40. You can also specify a specific transport:
  41. <info>php %command.full_name% to@example.com --transport=transport_name</info>
  42. Note that this command bypasses the Messenger bus if configured.
  43. EOF
  44. );
  45. }
  46. protected function execute(InputInterface $input, OutputInterface $output): int
  47. {
  48. $message = (new Email())
  49. ->to($input->getArgument('to'))
  50. ->from($input->getOption('from'))
  51. ->subject($input->getOption('subject'))
  52. ->text($input->getOption('body'))
  53. ;
  54. if ($transport = $input->getOption('transport')) {
  55. $message->getHeaders()->addTextHeader('X-Transport', $transport);
  56. }
  57. $this->transport->send($message);
  58. return 0;
  59. }
  60. }