You are here

public function ContactEmailer::sendEmails in Contact Emails 8

Send the emails.

Throws

\Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException

\Drupal\Component\Plugin\Exception\PluginNotFoundException

File

src/ContactEmailer.php, line 115

Class

ContactEmailer
Class ContactEmailer.

Namespace

Drupal\contact_emails

Code

public function sendEmails() {

  /** @var \Drupal\contact_emails\ContactEmailStorageInterface $storage */
  $storage = \Drupal::entityTypeManager()
    ->getStorage('contact_email');
  $contact_emails = $storage
    ->loadValid($this->contactForm, TRUE);
  if ($contact_emails) {
    foreach ($contact_emails as $email) {
      $module = 'contact_emails';
      $key = 'contact_emails';
      $to = $this
        ->getTo($email);
      $reply_to = $email
        ->getReplyTo($this->contactMessage);

      // Stop here if we don't know who to send to.
      if (!$to) {
        $error = $this
          ->t('Unable to determine who to send the message to for for email id @id', [
          '@id' => $email
            ->id(),
        ]);
        $this->messenger
          ->addWarning($error);
        continue;
      }
      $params['subject'] = $email
        ->getSubject($this->contactMessage);
      $params['format'] = $email
        ->getFormat($this->contactMessage);
      $params['message'] = $email
        ->getBody($this->contactMessage);
      $params['contact_message'] = $this->contactMessage;
      $params['contact_email'] = $email;

      // Final prep and send.
      $language_code = $this->currentUser
        ->getPreferredLangcode();
      $this->mailManager
        ->mail($module, $key, $to, $language_code, $params, $reply_to, TRUE);
    }
  }
}