Drupal 7: Usage of drupal_mail() in custom module

Autor: Sven Culley am Mon, 17.11.2014 - 00:41

How to use drupal_mail() to send mails via custom module, just a short tutorial how to do this.

/**
 * Implements hook_menu().
 */
function example_menu() {
  $items = array();
  $items['example1'] = array(
    'title' => 'Test drupal_mail()',
    'page callback' => 'example_page1',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  $items['example2'] = array(
    'title' => 'Test drupal_mail()',
    'page callback' => 'example_page2',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
 
  return $items;
}
 
/**
 * Mail page 1
 */
function example_page1() {
  global $language;
  
  // Send the mail
  drupal_mail('example', 'page1', 'MAILADDRESS', $language->language);
  
  return '';
}

/**
 * Mail page 2
 */
function example_page2() {
  global $language;

  // Send the mail
  drupal_mail('example', 'page2', 'MAILADDRESS', $language->language);
  
  return '';
}
 
/**
 * Implements hook_mail().
 */
function example_mail($key, &$message, $params) {
  if ($key == 'page1') {
    $message['subject'] = t('Page 1');

    // This can also be a theme function with full html page structure
    $message['body'][] = drupal_html_to_text('<p>Your content for page 1</p>'); 
  } else if ($key == 'page2') {
    $message['subject'] = t('Page 2');

    // This can also be a theme function with full html page structure
    $message['body'][] = drupal_html_to_text('<p>Your content for page 2</p>'); 
  }
}