Mean in green
I'm Kevin. I live in Salem, Mass with my wife and little boy and I build software.

Alter Drupal Email Messages

Tuesday Mar 24, 2009

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.