You are here

public function ConnectionTester::testConnection in SMTP Authentication Support 8

Test SMTP connection.

File

src/ConnectionTester/ConnectionTester.php, line 102

Class

ConnectionTester
Allows testing the SMTP connection.

Namespace

Drupal\smtp\ConnectionTester

Code

public function testConnection() {
  if (!$this
    ->configurePhpMailer()) {
    $this->severity = self::REQUIREMENT_ERROR;
    $this->value = $this
      ->t('Unable to initialize PHPMailer.');
    return FALSE;
  }
  $smtp_enabled = $this->smtpConfig
    ->get('smtp_on');

  // Check to see if MailSystem is enabled and is using SMTPMailSystem.
  if (\Drupal::moduleHandler()
    ->moduleExists('mailsystem')) {
    $mailsystem_defaults = $this->configFactory
      ->get('mailsystem.settings')
      ->get('defaults');
    $smtp_enabled = in_array('SMTPMailSystem', $mailsystem_defaults);
  }
  if (!$smtp_enabled) {
    $this->severity = self::REQUIREMENT_OK;
    $this->value = $this
      ->t('SMTP module is enabled but turned off.');
    return FALSE;
  }
  try {
    if ($this->phpMailer
      ->smtpConnect()) {
      $this->severity = self::REQUIREMENT_OK;
      $this->value = $this
        ->t('SMTP module is enabled, turned on, and connection is valid.');
      return TRUE;
    }
    $this->severity = REQUIREMENT_ERROR;
    $this->value = $this
      ->t('SMTP module is enabled, turned on, but SmtpConnect() returned FALSE.');
    return FALSE;
  } catch (PHPMailerException $e) {
    $this->value = $this
      ->t('SMTP module is enabled, turned on, but SmtpConnect() threw exception @e', [
      '@e' => $e
        ->getMessage(),
    ]);
    $this->severity = self::REQUIREMENT_ERROR;
  } catch (\Exception $e) {
    $this->value = $this
      ->t('SMTP module is enabled, turned on, but SmtpConnect() threw an unexpected exception');
    $this->severity = self::REQUIREMENT_ERROR;
  }
  return FALSE;
}