You are here

public function HTMLMailMailSystem::format in HTML Mail 7

Format emails according to module settings.

Overrides MailSystemInterface::format

File

./htmlmail.mail.inc, line 12
Implementation of MailSystemInterface.

Class

HTMLMailMailSystem
@file Implementation of MailSystemInterface.

Code

public function format(array $message) {

  // Collapse the message body array.
  $message['body'] = is_array($message['body']) ? implode("\n\n", $message['body']) : $message['body'];

  // Optionally apply an input filter.
  if (isset($message['format']) && ($filter = $message['format']) || ($filter = variable_get('htmlmail_prefilter'))) {
    $message['body'] = check_markup($message['body'], $filter);
  }

  // Use the theme template to add header, footer and optional debug text.
  $message['body'] = theme('htmlmail', $message);

  // Store a plaintext version.
  $message['plaintext'] = drupal_html_to_text($message['body']);

  // Send plaintext-only if the recipient prefers it.
  $recipient = user_load_by_mail($message['to']);
  if ($recipient && !empty($recipient->data['htmlmail_plaintext'])) {
    $message['headers']['Content-Type'] = 'text/plain; charset=UTF-8; format=flowed';
    $message['body'] = $message['plaintext'];
    return $message;
  }

  // Optionally apply the selected theme via internal http request.
  if ($theme = htmlmail_get_selected_theme($message['theme'])) {
    $url = url('admin/config/system/htmlmail/email', array(
      'absolute' => TRUE,
    ));
    $data = 'body=' . rawurlencode($message['body']) . '&subject=' . rawurlencode($message['subject']) . '&theme=' . rawurlencode($theme);
    $options = array(
      'method' => 'POST',
      'data' => $data,
      'headers' => array(
        'Content-Type' => 'application/x-www-form-urlencoded',
      ),
    );
    $response = drupal_http_request($url, $options);

    // Strip javascript as it doesn't work through email anyway.
    $message['body'] = preg_replace('@<script type="text/javascript".*</script>@Usi', '', $response->data);
  }

  // Optionally apply the selected output filter.
  if ($filter = variable_get('htmlmail_postfilter')) {
    $message['body'] = check_markup($message['body'], $filter);
  }

  // Store both plaintext and html versions.
  $boundary = uniqid(time(), 1);
  $message['headers']['Content-Type'] = "multipart/alternative; charset=utf-8; boundary=\"{$boundary}\"";
  $message['headers']['Content-Transfer-Encoding'] = '8bit';
  $message['headers']['MIME-Version'] = '1.0';
  $message['body'] = "This is a multi-part message in MIME format.\n--{$boundary}\nContent-Type: text/plain; charset=utf-8; format=flowed\nContent-Transfer-Encoding: 8bit\n\n" . $message['plaintext'] . "\n\n--{$boundary}\nContent-Type: text/html; charset=UTF-8; format=flowed\nContent-Transfer-Encoding: 8bit\n\n" . $message['body'] . "\n\n--{$boundary}--\n";
  return $message;
}