56 lines
2.2 KiB
PHP
56 lines
2.2 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Command;
|
|
|
|
use Symfony\Component\Console\Attribute\AsCommand;
|
|
use Symfony\Component\Console\Command\Command;
|
|
use Symfony\Component\Console\Input\InputArgument;
|
|
use Symfony\Component\Console\Input\InputInterface;
|
|
use Symfony\Component\Console\Input\InputOption;
|
|
use Symfony\Component\Console\Output\OutputInterface;
|
|
use Symfony\Component\Mailer\MailerInterface;
|
|
use Symfony\Component\Mime\Address;
|
|
use Symfony\Component\Mime\Email;
|
|
|
|
#[AsCommand(
|
|
name: 'app:mail:test',
|
|
description: 'Sends a simple test email using the configured mail transport (Mailgun in prod).'
|
|
)]
|
|
final class TestEmailCommand extends Command
|
|
{
|
|
public function __construct(private readonly MailerInterface $mailer)
|
|
{
|
|
parent::__construct();
|
|
}
|
|
|
|
protected function configure(): void
|
|
{
|
|
$this
|
|
->addArgument('to', InputArgument::REQUIRED, 'Recipient email address')
|
|
->addOption('subject', null, InputOption::VALUE_REQUIRED, 'Email subject', 'EscapePage mailer test')
|
|
->addOption('from', null, InputOption::VALUE_REQUIRED, 'Sender email address (defaults to MAILER_FROM if set)')
|
|
->addOption('from-name', null, InputOption::VALUE_REQUIRED, 'Sender name', 'EscapePage');
|
|
}
|
|
|
|
protected function execute(InputInterface $input, OutputInterface $output): int
|
|
{
|
|
$to = (string) $input->getArgument('to');
|
|
$subject = (string) $input->getOption('subject');
|
|
$fromEmail = (string) ($input->getOption('from') ?? ($_ENV['MAILER_FROM'] ?? $_SERVER['MAILER_FROM'] ?? 'no-reply@example.com'));
|
|
$fromName = (string) $input->getOption('from-name');
|
|
|
|
$email = (new Email())
|
|
->from(new Address($fromEmail, $fromName))
|
|
->to($to)
|
|
->subject($subject)
|
|
->html('<p>This is a test email sent at ' . date('c') . '.</p><p>If you see this, your mailer setup works.</p>')
|
|
->text('This is a test email sent at ' . date('c') . ". If you see this, your mailer setup works.");
|
|
|
|
$this->mailer->send($email);
|
|
|
|
$output->writeln('<info>Test email sent to ' . $to . '.</info>');
|
|
return Command::SUCCESS;
|
|
}
|
|
}
|