Error message

Deprecated function: implode(): Passing glue string after array is deprecated. Swap the parameters in drupal_get_feeds() (line 394 of /home1/tylerfra/public_html/includes/common.inc).

Drupal - Send an E-mail with Custom Module Code

Category: 

Here is how to send an e-mail with some custom code in your module and by utilizing hook_mail.

Add this example code snippet to your custom module where you would like to have an e-mail sent. For example, maybe you want to send an e-mail about a node when one of your module's forms are submitted.

// Set hook_mail parameters.
$my_node = node_load(123);
$params = array(
  'subject' => $my_node->title,
  'body' => "<p>Hello World</p>",
);

// Send out the e-mail.
drupal_mail('my_module', 'my_module_mail_example', "example@example.com", language_default(), $params);
drupal_set_message("Sent e-mail to example@example.com");

Add this example hook_mail implementation to your module...

/**
 * Implementation of hook_mail().
 */
function my_module_mail($key, &$message, $params){

  // Set the mail content type to html to send an html e-mail (optional).
  $message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed';

  // Grab the subject and body from params and add it to the message.
  $message['subject'] = $params['subject'];
  $message['body'][] = $params['body']; // Drupal 7
  //$message['body'] = $params['body']; // Drupal 6, I think

  switch ($key) {
    case "my_module_mail_example":
      // Make other changes here if desired...
      break;
  }

}

There you go, enjoy sending some e-mails through Drupal. Don't spam anybody, or else. Or else what? That's what.

Comments

Thanks for the demo. It helps :)

 

There is one minor change in the code.

From

$message['body'] = $params['body'];

TO

$message['body'][] = $params['body'];

 

tyler's picture

Thanks, you're correct! I've updated the code.