You are here

public function Mailer::sendTest in Simplenews 3.x

Same name and namespace in other branches
  1. 8.2 src/Mail/Mailer.php \Drupal\simplenews\Mail\Mailer::sendTest()
  2. 8 src/Mail/Mailer.php \Drupal\simplenews\Mail\Mailer::sendTest()

Send test version of newsletter.

Parameters

\Drupal\Core\Entity\ContentEntityInterface $issue: The newsletter issue to be sent.

array $test_addresses: List of addresses to send the newsletter to.

Overrides MailerInterface::sendTest

File

src/Mail/Mailer.php, line 366

Class

Mailer
Default Mailer.

Namespace

Drupal\simplenews\Mail

Code

public function sendTest(ContentEntityInterface $issue, array $test_addresses) {

  // Force the current user to anonymous to ensure consistent permissions.
  $this->accountSwitcher
    ->switchTo(new AnonymousUserSession());

  // Send the test newsletter to the test address(es) specified in the node.
  // Build array of test email addresses.
  // Send newsletter to test addresses.
  // Emails are send direct, not using the spool.
  $recipients = [
    'anonymous' => [],
    'user' => [],
  ];
  foreach ($test_addresses as $mail) {
    $mail = trim($mail);
    if (!empty($mail)) {
      $subscriber = Subscriber::loadByMail($mail, 'create', $this->languageManager
        ->getCurrentLanguage());
      if ($account = $subscriber
        ->getUser()) {
        $recipients['user'][] = $account
          ->getDisplayName() . ' <' . $mail . '>';
      }
      else {
        $recipients['anonymous'][] = $mail;
      }
      $mail = new MailEntity($issue, $subscriber, $this->mailCache);
      $mail
        ->setKey('test');
      $this
        ->sendMail($mail);
    }
  }
  if (count($recipients['user'])) {
    $recipients_txt = implode(', ', $recipients['user']);
    $this
      ->messenger()
      ->addMessage($this
      ->t('Test newsletter sent to user %recipient.', [
      '%recipient' => $recipients_txt,
    ]));
  }
  if (count($recipients['anonymous'])) {
    $recipients_txt = implode(', ', $recipients['anonymous']);
    $this
      ->messenger()
      ->addMessage($this
      ->t('Test newsletter sent to anonymous %recipient.', [
      '%recipient' => $recipients_txt,
    ]));
  }
  $this->accountSwitcher
    ->switchBack();
}