function email_example_mail in Examples for Developers 6
Same name and namespace in other branches
- 8 email_example/email_example.module \email_example_mail()
- 7 email_example/email_example.module \email_example_mail()
- 3.x modules/email_example/email_example.module \email_example_mail()
Implementation of hook_mail().
This hook defines a list of possible e-mail templates that this module can send. Each e-mail is given a unique identifier, or 'key'.
$message comes in with some standard properties already set: 'to' address, 'from' address, and a set of default 'headers' from drupal_mail(). The goal of hook_mail() is to set the message's 'subject' and 'body' properties, as well as make any adjustments to the headers that are necessary.
The $params argument is an array which can hold any additional data required to build the mail subject and body; for example, user-entered form data, or some context information as to where the mail request came from.
Note that hook_mail() is not actually a hook. It is only called for a single module, the module named in the first argument of drupal_mail(). So it's a callback of a type, but not a hook.
Related topics
File
- email_example/
email_example.module, line 51 - Example of how to use Drupal's mail API.
Code
function email_example_mail($key, &$message, $params) {
global $user;
// Each message is associated with a language, which may or may not be the
// current user's selected language, depending on the type of e-mail being
// sent. This $language variable is used later in the t() calls for subject
// and body to ensure the proper translation takes effect.
$language = $message['language'];
switch ($key) {
// Send a simple message from the contact form.
case 'contact_message':
$message['subject'] = t('E-mail sent from @site-name', array(
'@site-name' => variable_get('site_name', 'Drupal'),
), $language->language);
// Note that the message body is an array, not a string.
$message['body'][] = t('@name sent you the following message:', array(
'@name' => $user->name,
), $language->language);
// Because this is just user-entered text, we do not need to translate it.
$message['body'][] = $params['message'];
break;
}
}