I recently worked on an issue with a custom built notification system sending emails and sms messages after certain events. Some of the e-mail messages were delivering successfully and others were not. Review of the code revealed the usage of drupal_mail_send, with improperly built custom headers, was causing the emails to deliver incorrectly.
By simply refactoring the code to use an implementation of the drupal_mail function, I resolved the issue. Let’s take a look at the code.
Original implementation:
foreach ($emails as $email) {
$message = array(
'to' => $email,
'subject' => t('‘Notification Message'),
'body' => 'This message was sent from example.com:' . "\n\n" . $_POST['message'] . $spam_filter_message, 'headers' => array('From' => 'noreply@example.com'),
);
drupal_mail_send($message);
}
VS:
foreach ($emails as $email) {
$params = array(
'subject' => t('SchoolTeam Message'),
'body' => 'This message was sent from SchoolTeam.com:' . "\n\n" . $_POST['emailmessage'] . $spam_filter_message,
);
drupal_mail('example_module', 'custom_sms', $email, $language, $params);
}
In the second sample we are calling drupal_mail and invoking the hook in our custom module (‘example_module’). Here is what the hook looks like.
function example_module_mail($key, &$message, $params) {
switch($key) {
case 'custom_sms':
$message['subject'] = $params['subject'];
$message['body'][] = $params['body'];
break;
}
}
Using drupal_mail may take a little bit longer then just using drupal_mail_send, but the benefit of generating correctly formatted e-mail headers outweighs the time spent on having to create and reference the hook. By correctly using drupal_mail, you can ensure quality headers while allowing other modules using hook_mail to work correctly with your custom module. Looking ahead, drupal_mail is implemented the same in Drupal 7 as it is in Drupal 6. However, drupal_mail_send has been removed from the Drupal 7 API so if you havent already, now is a good time to start using drupal_mail.