<About />

My name is Kevin. I am a web professional living in Massachusetts. I build websites mostly using Drupal and jQuery. I use Vim even when I don't need to. When I'm not on the computer, I'm usually hanging with my wife, Melissa.

<Search />

Alter Drupal Email Messages

I just had a requirement to add some text to the body of Drupal's outgoing emails. Turns out it's not too tough using hook_mail_alter(). I started out by using var_export() and drupal_set_message() to find out more information about the array that Drupal creates for the message:

<?php
/**
* Implementation of hook_mail_alter().
*/
function your_module_mail_alter(&$message) {
 
// For example, submit the contact form and you
  // will be able to see the $message array

 
$v = var_export($message, true);
 
drupal_set_message("message: " . $v);
}
?>

The email text is constructed from an array of elements, so adding a new element to the email body is just a matter of adding an element to the body array:

<?php
/**
* Implementation of hook_mail_alter().
*/
function your_module_mail_alter(&$message) {
 
// Add a link to the user's profile in the message body
  // when you submit the site wide contact form:

 
switch ($message['id']) {
    case
'contact_page_mail':
      global
$user;
      if (
$user->uid != 0) {
       
$message['body'][] = 'Profile: [your-site-address]/user/' . $user->uid;
      }
    break;
  }

}
?>

You could just as easily use this for a variety of other cases. For example, you could add conditional recipients, do custom logging, or even use the message content as a conditional trigger. Lots of good stuff there.

amber

thanks for the code, it's awesome amber

You might want to use url()

You might want to use url() instead of hardcoding the path to the user page so that your code will work regardless of the site (say for example on your staging site).

http://api.drupal.org/api/function/url/6

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <span> <a>
  • Lines and paragraphs break automatically.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.

More information about formatting options

Mollom CAPTCHA (play audio CAPTCHA)
Type the characters you see in the picture above; if you can't read them, submit the form and a new image will be generated.