Alter an email message created with the drupal_mail() function.
hook_mail_alter() allows modification of email messages created and sent with drupal_mail(). Usage examples include adding and/or changing message text, message fields, and message headers.
Email messages sent using functions other than drupal_mail() will not invoke hook_mail_alter(). For example, a contributed module directly calling the drupal_mail_system()->mail() or PHP mail() function will not invoke this hook. All core modules use drupal_mail() for messaging, it is best practice but not mandatory in contributed modules.
$message: An array containing the message data. Keys in this array include:
Note: this list is generated by pattern matching, so it may include some functions that are not actually implementations of this hook.
function hook_mail_alter(&$message) {
if ($message['id'] == 'modulename_messagekey') {
if (!example_notifications_optin($message['to'], $message['id'])) {
// If the recipient has opted to not receive such messages, cancel
// sending.
$message['send'] = FALSE;
return;
}
$message['body'][] = "--\nMail sent out from " . config('system.site')
->get('name');
}
}