You are here

public function HTMLMailSystem::format in HTML Mail 8

Same name and namespace in other branches
  1. 8.3 src/Plugin/Mail/HtmlMailSystem.php \Drupal\htmlmail\Plugin\Mail\HtmlMailSystem::format()

Format emails according to module settings.

Parses the message headers and body into a MailMIME object. If another module subsequently modifies the body, then format() should be called again before sending. This is safe because the $message['body'] is not modified.

Parameters

array $message: An associative array with at least the following parts:

  • headers: An array of (name => value) email headers.
  • body: The text/plain or text/html message part.

Return value

array The formatted $message, ready for sending.

Overrides MailInterface::format

File

src/Plugin/Mail/HTMLMailSystem.php, line 158

Class

HTMLMailSystem
Modify the Drupal mail system to use HTMLMail when sending emails.

Namespace

Drupal\htmlmail\Plugin\Mail

Code

public function format(array $message) {
  $eol = $this->siteSettings
    ->get('mail_line_endings', PHP_EOL);
  $default_from = $this
    ->getDefaultFromMail();
  $force_plain = $this->configVariables
    ->get('htmlmail_html_with_plain');
  if (!empty($message['headers']['From']) && $message['headers']['From'] == $default_from && $this->emailValidator
    ->isValid($default_from)) {
    $message['headers']['From'] = '"' . str_replace('"', '', $this
      ->getDefaultSiteName()) . '" <' . $default_from . '>';
  }

  // Collapse the message body array.
  if ($this->configVariables
    ->get('htmlmail_use_mime_mail')) {
    $body = $this
      ->formatMailMime($message);
    $plain = $message['MailMIME']
      ->getTXTBody();
  }
  else {

    // Collapse the message body array.
    if (is_array($message['body'])) {

      // Join the body array into one string.
      $message['body'] = implode("{$eol}{$eol}", $message['body']);

      // Convert any HTML to plain-text.
      $message['body'] = MailFormatHelper::htmlToText($message['body']);

      // Wrap the mail body for sending.
      $message['body'] = MailFormatHelper::wrapMail($message['body']);
    }
    $theme = [
      '#theme' => HtmlMailHelper::getThemeNames($message),
      '#message' => $message,
    ];
    $body = $this->renderer
      ->render($theme);
    if ($message['body'] && !$body) {
      $this
        ->getLogger()
        ->warning('The %theme function did not return any text.  Please check your template file for errors.', [
        '%theme' => "Drupal::service('renderer')->render([\$theme])",
      ]);
      $body = $message['body'];
    }
    $plain = MailFormatHelper::htmlToText($body);
    if ($body && !$plain) {
      $this
        ->getLogger()
        ->warning('The %convert function did not return any text. Please report this error to the %mailsystem issue queue.', [
        '%convert' => 'MailFormatHelper::htmlToText()',
        '%mailsystem' => 'Mail system',
      ]);
    }
  }

  // Check to see whether recipient allows non-plaintext.
  if ($body && HtmlMailHelper::htmlMailIsAllowed($message['to']) && !$force_plain) {

    // Optionally apply the selected web theme.
    if ($this->moduleHandler
      ->moduleExists('echo') && ($theme = HtmlMailHelper::getSelectedTheme($message))) {
      $themed_body = echo_themed_page($message['subject'], $body, $theme);
      if ($themed_body) {
        $body = $themed_body;
      }
      else {
        $this
          ->getLogger()
          ->warning('The %echo function did not return any text. Please check the page template of your %theme theme for errors.', [
          '%echo' => 'echo_themed_page()',
          '%theme' => $theme,
        ]);
      }
    }

    // Optionally apply the selected output filter.
    if ($filter = $this->configVariables
      ->get('htmlmail_postfilter')) {
      $filtered_body = check_markup($body, $filter);
      if ($filtered_body) {
        $body = $filtered_body;
      }
      else {
        $this
          ->getLogger()
          ->warning('The %check function did not return any text. Please check your %filter output filter for errors.', [
          '%check' => 'check_markup()',
          '%filter' => $filter,
        ]);
      }
    }

    // Store the fully-themed HTML body.
    if (isset($message['MailMIME'])) {
      $mime =& $message['MailMIME'];
      $mime
        ->setHTMLBody($body);
      if (isset($message['params']['attachments'])) {
        foreach ($message['params']['attachments'] as $attachment) {
          $mime
            ->addAttachment($this->fileSystem
            ->realpath($attachment['uri']), $attachment['filemime'], $attachment['filename'], TRUE, 'base64', 'attachment', 'UTF-8', '', '');
        }
      }
      list($message['headers'], $message['body']) = $mime
        ->toEmail($message['headers']);
      if (!$message['body']) {
        $this
          ->getLogger()
          ->warning('The %toemail function did not return any text. Please report this error to the %mailmime issue queue.', [
          '%toemail' => 'HTMLMailMime::toEmail()',
          '%mailmime' => 'Mail MIME',
        ]);
      }
    }
    else {
      $message['headers']['Content-Type'] = 'text/html; charset=utf-8';
      $message['body'] = $body;
      if ($this->configVariables
        ->get('htmlmail_html_with_plain')) {
        $boundary = uniqid('np');
        $message['headers']['Content-Type'] = 'multipart/alternative;boundary="' . $boundary . '"';
        $html = $message['body'];
        $raw_message = 'This is a MIME encoded message.';
        $raw_message .= $eol . $eol . "--" . $boundary . $eol;
        $raw_message .= "Content-Type: text/plain;charset=utf-8" . $eol . $eol;
        $raw_message .= MailFormatHelper::htmlToText($html);
        $raw_message .= $eol . $eol . "--" . $boundary . $eol;
        $raw_message .= "Content-Type: text/html;charset=utf-8" . $eol . $eol;
        $raw_message .= $html;
        $raw_message .= $eol . $eol . "--" . $boundary . "--";
        $message['body'] = $raw_message;
      }
    }
  }
  else {
    if (isset($message['MailMIME'])) {
      $mime =& $message['MailMIME'];
      $mime
        ->setHTMLBody('');
      $mime
        ->setContentType('text/plain', [
        'charset' => 'utf-8',
      ]);
      if (isset($message['params']['attachments'])) {
        foreach ($message['params']['attachments'] as $attachment) {
          $mime
            ->addAttachment($this->fileSystem
            ->realpath($attachment['uri']), $attachment['filemime'], $attachment['filename'], TRUE, 'base64', 'attachment', 'UTF-8', '', '');
        }
      }
      list($message['headers'], $message['body']) = $mime
        ->toEmail($message['headers']);
      if (!$message['body']) {
        $this
          ->getLogger()
          ->warning('The %toemail function did not return any text. Please report this error to the %mailmime issue queue.', [
          '%toemail' => 'HTMLMailMime::toEmail()',
          '%mailmime' => 'Mail MIME',
        ]);
      }
    }
    else {
      $message['body'] = $plain;
      $message['headers']['Content-Type'] = 'text/plain; charset=utf-8';
    }
  }
  return $message;
}