You are here

public function EmailHandler::sendEmail in Easy Email 8

Same name and namespace in other branches
  1. 2.0.x src/Service/EmailHandler.php \Drupal\easy_email\Service\EmailHandler::sendEmail()

@inheritDoc

Overrides EmailHandlerInterface::sendEmail

File

src/Service/EmailHandler.php, line 152

Class

EmailHandler

Namespace

Drupal\easy_email\Service

Code

public function sendEmail(EasyEmailInterface $email, $params = [], $send_duplicate = FALSE) {
  if ($email
    ->isSent()) {
    return FALSE;
  }
  if (!$send_duplicate && $this
    ->duplicateExists($email)) {
    return FALSE;
  }
  $this->renderer
    ->executeInRenderContext(new RenderContext(), function () use ($email) {
    return $this->tokenEvaluator
      ->evaluateTokens($email);
  });
  $this->userEvaluator
    ->evaluateUsers($email);
  $params = $this
    ->generateEmailParams($email, $params);

  /** @var \Drupal\easy_email\Entity\EasyEmailTypeInterface $email_type */
  $email_type = $this->emailTypeStorage
    ->load($email
    ->bundle());
  $save_attachments_to = FALSE;
  if ($email_type
    ->getSaveAttachment()) {
    $save_attachments_to = $email_type
      ->getAttachmentScheme() . '://' . $this->tokenEvaluator
      ->replaceTokens($email, $email_type
      ->getAttachmentDirectory());
  }
  $this->attachmentEvaluator
    ->evaluateAttachments($email, $save_attachments_to);
  $params['files'] = $email
    ->getEvaluatedAttachments();
  $reply = $email
    ->getReplyToAddress();
  $recipient_emails = $email
    ->getRecipientAddresses();
  $default_langcode = $this->languageManager
    ->getDefaultLanguage()
    ->getId();
  if ($this->tokenEvaluator
    ->containsUnsafeTokens($email)) {

    // We need to send to each recipient individually and make sure they only have their own unsafe token evaluated.
    $emails_to_send = $this
      ->createUnsafeEmailsForRecipients($email, $params);
  }
  else {
    $emails_to_send = [
      [
        'to' => implode(', ', $recipient_emails),
        'email' => $email,
        'params' => $params,
      ],
    ];
  }
  foreach ($emails_to_send as $email_info) {
    if (!empty($email_info['to'])) {
      $this->eventDispatcher
        ->dispatch(EasyEmailEvents::EMAIL_PRESEND, new EasyEmailEvent($email));
      $message = $this->mailManager
        ->mail('easy_email', $email_info['email']
        ->bundle(), $email_info['to'], $default_langcode, $email_info['params'], $reply, TRUE);
    }
    if (!empty($message['result'])) {
      $this->eventDispatcher
        ->dispatch(EasyEmailEvents::EMAIL_SENT, new EasyEmailEvent($email));
      $email_info['email']
        ->setSentTime($this->time
        ->getCurrentTime())
        ->save();
    }
  }
  return !empty($message['result']) ? $message['result'] : FALSE;
}