You are here

class MailgunTestEmailForm in Mailgun 8

Provides test email form with common email parameters.

Hierarchy

Expanded class hierarchy of MailgunTestEmailForm

1 string reference to 'MailgunTestEmailForm'
mailgun.routing.yml in ./mailgun.routing.yml
mailgun.routing.yml

File

src/Form/MailgunTestEmailForm.php, line 19

Namespace

Drupal\mailgun\Form
View source
class MailgunTestEmailForm extends FormBase {

  /**
   * Drupal\mailgun\MailgunHandlerInterface definition.
   *
   * @var \Drupal\mailgun\MailgunHandlerInterface
   */
  protected $mailgunHandler;

  /**
   * Current user.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $user;

  /**
   * Mail Manager.
   *
   * @var \Drupal\Core\Mail\MailManagerInterface
   */
  protected $mailManager;

  /**
   * File system.
   *
   * @var \Drupal\Core\File\FileSystemInterface
   */
  protected $fileSystem;

  /**
   * The module handler service.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

  /**
   * MailgunTestEmailForm constructor.
   */
  public function __construct(MailgunHandlerInterface $mailgun_handler, AccountProxyInterface $user, MailManagerInterface $mail_manager, FileSystemInterface $file_system, ModuleHandlerInterface $module_handler) {
    $this->mailgunHandler = $mailgun_handler;
    $this->user = $user;
    $this->mailManager = $mail_manager;
    $this->fileSystem = $file_system;
    $this->moduleHandler = $module_handler;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('mailgun.mail_handler'), $container
      ->get('current_user'), $container
      ->get('plugin.manager.mail'), $container
      ->get('file_system'), $container
      ->get('module_handler'));
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'mailgun_test_email_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $this->mailgunHandler
      ->moduleStatus(TRUE);

    // Display a warning if Mailgun is not a default mailer.
    $sender = $this
      ->config('mailsystem.settings')
      ->get('defaults.sender');
    if (!strstr($sender, 'mailgun_')) {
      $this
        ->messenger()
        ->addMessage($this
        ->t('Mailgun is not a default Mailsystem plugin. You may update settings at @link.', [
        '@link' => Link::createFromRoute($this
          ->t('here'), 'mailsystem.settings')
          ->toString(),
      ]), 'warning');
    }

    // We can test all mail systems with this form.
    $form['to'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('To'),
      '#required' => TRUE,
      '#description' => $this
        ->t('Email will be sent to this address. You can use commas to separate multiple recipients.'),
      '#default_value' => $this->user
        ->getEmail(),
    ];
    $form['body'] = [
      '#type' => 'textarea',
      '#title' => $this
        ->t('Message'),
      '#required' => TRUE,
      '#default_value' => $this
        ->t('Howdy!

If this e-mail is displayed correctly and delivered sound and safe, congrats! You have successfully configured Mailgun.'),
    ];
    $form['include_attachment'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Include attachment'),
      '#description' => $this
        ->t('If checked, an image will be included as an attachment with the test e-mail.'),
    ];
    $form['extra'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Additional parameters'),
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
      '#description' => $this
        ->t('You may test more parameters to make sure they are working.'),
    ];
    $form['extra']['reply_to'] = [
      '#type' => 'email',
      '#title' => $this
        ->t('Reply-To'),
    ];
    $form['extra']['cc'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('CC'),
      '#description' => $this
        ->t('You can use commas to separate multiple recipients.'),
    ];
    $form['extra']['bcc'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('BCC'),
      '#description' => $this
        ->t('You can use commas to separate multiple recipients.'),
    ];
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Send'),
    ];
    $form['actions']['cancel'] = [
      '#type' => 'link',
      '#title' => $this
        ->t('Cancel'),
      '#url' => Url::fromRoute('mailgun.admin_settings_form'),
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $to = $form_state
      ->getValue('to');
    $params = [
      'subject' => $this
        ->t('Mailgun works!'),
      'body' => [
        $form_state
          ->getValue('body'),
      ],
    ];
    if (!empty($form_state
      ->getValue('include_attachment'))) {
      $params['attachments'][] = [
        'filepath' => $this->fileSystem
          ->realpath('core/misc/druplicon.png'),
      ];
    }

    // Add CC / BCC values if they are set.
    if (!empty($cc = $form_state
      ->getValue('cc'))) {
      $params['cc'] = $cc;
    }
    if (!empty($bcc = $form_state
      ->getValue('bcc'))) {
      $params['bcc'] = $bcc;
    }
    $result = $this->mailManager
      ->mail('mailgun', 'test_form_email', $to, $this->user
      ->getPreferredLangcode(), $params, $form_state
      ->getValue('reply_to'), TRUE);
    if (!empty($result)) {
      $this
        ->messenger()
        ->addMessage($this
        ->t('Successfully sent message to %to.', [
        '%to' => $to,
      ]));
    }
    else {
      if ($this->moduleHandler
        ->moduleExists('dblog')) {
        $this
          ->messenger()
          ->addMessage($this
          ->t('Something went wrong. Please check @logs for details.', [
          '@logs' => Link::createFromRoute($this
            ->t('logs'), 'dblog.overview')
            ->toString(),
        ]), 'warning');
      }
      else {
        $this
          ->messenger()
          ->addMessage($this
          ->t('Something went wrong. Please check logs for details.'), 'warning');
      }
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 62
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MailgunTestEmailForm::$fileSystem protected property File system.
MailgunTestEmailForm::$mailgunHandler protected property Drupal\mailgun\MailgunHandlerInterface definition.
MailgunTestEmailForm::$mailManager protected property Mail Manager.
MailgunTestEmailForm::$moduleHandler protected property The module handler service.
MailgunTestEmailForm::$user protected property Current user.
MailgunTestEmailForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
MailgunTestEmailForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
MailgunTestEmailForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
MailgunTestEmailForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
MailgunTestEmailForm::__construct public function MailgunTestEmailForm constructor.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.