Submitted by Kevin Hankens on Tue, 03/24/2009 - 11:36
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