Drupal 7: Mit drupal_mail() HTML E-Mails versenden

Autor: Sven am Mon, 30.09.2013 - 21:36

In diesem Tutorial möchte ich Euch zeigen, wie man aus einem Custom Modul Mails über drupal_mail() als HTML versendet. Drupal veschickt standardmäßig als Plaintext und dieses kann auch nicht ohne Weiteres umgangen werden, außer durch die Installation zusätzlicher Module.

testhtml.install

/**
 * Implements hook_enable()
 */
function testhtml_enable() {
  $current = variable_get('mail_system', array('default-system' => 'DefaultMailSystem'));
  $addition = array('testhtml' => 'TestHMTLMailSystem');
  variable_set('mail_system', array_merge($current, $addition));
}

/**
 * Implements hook_disable()
 */
function testhtml_disable() {
  $mail_system = variable_get('mail_system', array('default-system' => 'DefaultMailSystem'));
  unset($mail_system['testhtml']);
  variable_set('mail_system', $mail_system);
}

testhtml.module

/**
 * Modify the drupal mail system to send HTML emails.
 */
class TestHTMLMailSystem extends DefaultMailSystem {
  /**
   * Concatenate and wrap the e-mail body for plain-text mails.
   *
   * @param $message
   *   A message array, as described in hook_mail_alter().
   *
   * @return
   *   The formatted $message.
   */
  public function format(array $message) {
    $message['body'] = implode("\n\n", $message['body']);
    $message['body'] = drupal_wrap_mail($message['body']);
    return $message;
  }
}

/**
 * Implements hook_menu()
 */
function testhtml_menu() {
  $items = array();
  $items['testhtml'] = array(
    'title' => 'Test HTML',
    'page callback' => 'testhtml_page',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  return $items;
}

/**
 * Mail page
 */
function testhtml_page() {
  global $language;
  drupal_mail('testhtml', '', 'MAILADRESSE', $language->language);
}

/**
 * Implements hook_mail()
 */
function testhtml_mail($key, &$message, $params) {
  // HTML mail, this is required to set HTML als default header
  $message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed';

  $message['subject'] = t('Order');
  $message['body'][] = 'Your HTML content'; // This can also be a theme function with full html page structure
}