18.10.2016 Views

Drupal 7 Module Development

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 5<br />

As discussed earlier, it is possible for hook_mail() to handle multiple different<br />

e-mails as indicated by the key passed in from drupal_mail(). Even though we<br />

are only sending one e-mail with a key of 'warn', we still put it into a switch/case<br />

structure to make it easier to manage more mails later on if needed.<br />

Now we can get on with the real purpose of our hook implementation—adding<br />

details to the $message array that are unique to our mail. Typically this is the subject,<br />

body, and any additional headers that we might need.<br />

Our e-mail's subject and text have been set via the module's configuration page, so<br />

we retrieve them via variable_get() and set them to the $message['subject']<br />

and $message['body] properties here.<br />

Note that we do not pass the subject and body strings through t() as<br />

we have done in other contexts. These strings are supplied by the site<br />

administrator through the User Warn module's configuration form, and<br />

as such are not translatable. Only hardcoded system strings need to be<br />

passed through t().<br />

The other thing we need to do is to Bcc the site admin if that configuration setting<br />

has been set.<br />

if (variable_get('user_warn_bcc', FALSE)) {<br />

$admin_mail = variable_get('site_mail', NULL);<br />

$message['headers']['bcc'] = $admin_mail;<br />

}<br />

As with the other configuration settings, we retrieve it using variable_get(). If it is<br />

TRUE, then we need to set the site admin to be Bcc'd. Unlike the e-mail recipient, Cc<br />

and Bcc are set by adding headers to the $message array. The headers are themselves<br />

an associative array held under the 'headers' key, and we need to add a new<br />

header with the key 'Bcc'. We assign this to the site admin's e-mail in the same<br />

manner as we did in drupal_mail() while setting the mail's sender.<br />

This is all we need to do! $message is passed by reference, so we don't even need to<br />

return it. <strong>Drupal</strong> will just proceed on from here. After other modules get a chance<br />

to alter the mail through hook_mail_alter(), the $message array will be passed<br />

to drupal_mail_system() where the final mail message will be formatted and<br />

delivered (if you specified this option when you called drupal_mail()).<br />

[ 145 ]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!