|
<?php |
|
|
|
declare(strict_types=1); |
|
|
|
namespace Drupal\test_email\Form; |
|
|
|
use Drupal\Core\Form\FormBase; |
|
use Drupal\Core\Form\FormStateInterface; |
|
use Drupal\Core\Mail\MailManagerInterface; |
|
use Drupal\Core\State\StateInterface; |
|
use Symfony\Component\DependencyInjection\ContainerInterface; |
|
|
|
/** |
|
* Form for testing email sending. |
|
*/ |
|
class TestEmailForm extends FormBase { |
|
|
|
public function __construct( |
|
protected MailManagerInterface $mailManager, |
|
protected StateInterface $state, |
|
) {} |
|
|
|
/** |
|
* {@inheritdoc} |
|
*/ |
|
public static function create(ContainerInterface $container): static { |
|
return new static( |
|
$container->get('plugin.manager.mail'), |
|
$container->get('state'), |
|
); |
|
} |
|
|
|
/** |
|
* {@inheritdoc} |
|
*/ |
|
public function getFormId(): string { |
|
return 'test_email_form'; |
|
} |
|
|
|
/** |
|
* {@inheritdoc} |
|
*/ |
|
public function buildForm(array $form, FormStateInterface $form_state): array { |
|
$form['recipient'] = [ |
|
'#type' => 'email', |
|
'#title' => $this->t('Recipient'), |
|
'#required' => TRUE, |
|
'#default_value' => $this->state->get('test_email.recipient', ''), |
|
]; |
|
|
|
$form['subject'] = [ |
|
'#type' => 'textfield', |
|
'#title' => $this->t('Subject'), |
|
'#required' => TRUE, |
|
'#default_value' => $this->state->get('test_email.subject', 'Test Email'), |
|
]; |
|
|
|
$form['body'] = [ |
|
'#type' => 'textarea', |
|
'#title' => $this->t('Body'), |
|
'#required' => TRUE, |
|
'#default_value' => 'This is a test email sent from Drupal.', |
|
]; |
|
|
|
$form['actions'] = [ |
|
'#type' => 'actions', |
|
]; |
|
|
|
$form['actions']['submit'] = [ |
|
'#type' => 'submit', |
|
'#value' => $this->t('Send Test Email'), |
|
]; |
|
|
|
return $form; |
|
} |
|
|
|
/** |
|
* {@inheritdoc} |
|
*/ |
|
public function submitForm(array &$form, FormStateInterface $form_state): void { |
|
$recipient = $form_state->getValue('recipient'); |
|
$subject = $form_state->getValue('subject'); |
|
$body = $form_state->getValue('body'); |
|
|
|
// Store values for next time. |
|
$this->state->set('test_email.recipient', $recipient); |
|
$this->state->set('test_email.subject', $subject); |
|
|
|
$params = [ |
|
'subject' => $subject, |
|
'body' => $body, |
|
]; |
|
|
|
$result = $this->mailManager->mail( |
|
'test_email', |
|
'test', |
|
$recipient, |
|
$this->currentUser()->getPreferredLangcode(), |
|
$params, |
|
); |
|
|
|
if ($result['result']) { |
|
$this->messenger()->addStatus($this->t('Test email sent to @recipient.', ['@recipient' => $recipient])); |
|
} |
|
else { |
|
$this->messenger()->addError($this->t('Failed to send test email.')); |
|
} |
|
} |
|
|
|
} |