You are here

public function Mailer::sendTest in Simplenews 8

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

Send test version of newsletter.

Parameters

\Drupal\node\NodeInterface $node: The newsletter node to be sent.

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

Overrides MailerInterface::sendTest

File

src/Mail/Mailer.php, line 355

Class

Mailer
Default Mailer.

Namespace

Drupal\simplenews\Mail

Code

public function sendTest(NodeInterface $node, 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 = array(
    'anonymous' => array(),
    'user' => array(),
  );
  foreach ($test_addresses as $mail) {
    $mail = trim($mail);
    if (!empty($mail)) {
      $subscriber = simplenews_subscriber_load_by_mail($mail);
      if (!$subscriber) {

        // Create a stub subscriber. Use values from the user having the given
        // address, or if there is no such user, the anonymous user.
        if ($user = user_load_by_mail($mail)) {
          $subscriber = Subscriber::create()
            ->fillFromAccount($user);
        }
        else {
          $subscriber = Subscriber::create([
            'mail' => $mail,
          ]);
        }

        // Keep the current language.
        $subscriber
          ->setLangcode($this->languageManager
          ->getCurrentLanguage());
      }
      if ($subscriber
        ->getUserId()) {
        $account = $subscriber->uid->entity;
        $recipients['user'][] = $account
          ->getUserName() . ' <' . $mail . '>';
      }
      else {
        $recipients['anonymous'][] = $mail;
      }
      $mail = new MailEntity($node, $subscriber, $this->mailCache);
      $mail
        ->setKey('test');
      $this
        ->sendMail($mail);
    }
  }
  if (count($recipients['user'])) {
    $recipients_txt = implode(', ', $recipients['user']);
    $this
      ->messenger()
      ->addMessage(t('Test newsletter sent to user %recipient.', array(
      '%recipient' => $recipients_txt,
    )));
  }
  if (count($recipients['anonymous'])) {
    $recipients_txt = implode(', ', $recipients['anonymous']);
    $this
      ->messenger()
      ->addMessage(t('Test newsletter sent to anonymous %recipient.', array(
      '%recipient' => $recipients_txt,
    )));
  }
  $this->accountSwitcher
    ->switchBack();
}