background image
HomeRecent PostsDrupalSearchTagsRSSContactAboutAccount
Eric.London's picture

In this code snippet, I'll explain how you can create a module that emails log entries of a defined severity to a list of users.

The first step is to create an admin setting page that allows the admin to define the email recipients.

<?php
/**
* Implements hook_perm()
*/
function logemail_perm() {
  return array(
   
'administer log email',
  );
}

/**
* Implements hook_menu()
*/
function logemail_menu() {

 
$items = array();

 
// admin settings page callback
 
$items['admin/settings/log-email'] = array(
   
'title' => t('Log Email'),
   
'description' => t('Configure Log Email settings'),
   
'page callback' => 'drupal_get_form',
   
'page arguments' => array('logemail_callback_admin_settings'),
   
'access arguments' => array('administer log email'),
  );
 
  return
$items;
}

/**
* Implements form page callback for module admin settings page
*/
function logemail_callback_admin_settings() {
 
 
$form = array();
 
 
$form['logemail_recipients'] = array(
   
'#type' => 'textfield',
   
'#title' => t('Email Recipients'),
   
'#default_value' => variable_get('logemail_recipients', ''),
   
'#description' => t('Enter email addresses comma separated.'),
   
'#required' => TRUE,
  );
 
  return
system_settings_form($form);
}

/**
* Implements validation callback for admin settings form
*/
function logemail_callback_admin_settings_validate($form, &$form_state) {
 
 
// explode email addresses on comma
 
$emails = explode(',', trim($form_state['values']['logemail_recipients']));
 
  if (!
count($emails) || !is_array($emails)) {
   
form_set_error('logemail_recipients', t('Invalid email addresses.'));
    return;
  }
 
 
// loop through each email address and validate
 
foreach ($emails as $key => $value) {

   
// validate email address
   
$validate_result = valid_email_address(trim($value));

    if (
$validate_result !== 1) {
     
form_set_error('logemail_recipients', t('Invalid email addresses.'));
      return;
    }
    else {
     
// trim email addresses
     
$emails[$key] = trim($value);
    }
  }
 
 
// set trimmed values
 
$form_state['values']['logemail_recipients'] = implode(',', $emails);
}
?>

The above code creates an admin setting page that allows the admin to define the recipients list, and implements validation to ensure the email addresses exist and are valid.

Log Email Admin Settings

The next two functions implement hook_mail() and hook_watchdog() to check the severity of the log entry, compose the email message, and send it.

<?php
/**
* Implements hook_watchdog()
*/
function logemail_watchdog($log_entry) {
 
 
// check severity of log entry
 
if ($log_entry['severity']<5) {

   
// define parameters for drupal_mail
   
$module = 'logemail';
   
$key = 'watchdog';
   
$to = variable_get('logemail_recipients', '');
   
$language = language_default();
   
$params = array(
     
'log_entry' => $log_entry,
    );

   
// send email using drupal_mail
   
drupal_mail($module, $key, $to, $language, $params);
  }
}

/**
* Implements hook_mail()
*/
function logemail_mail($key, &$message, $params) {
  switch (
$key) {
    case
'watchdog':
     
// set email subject
     
$message['subject'] = t("Log Email Watchdog") . ": " . $params['log_entry']['type'];

     
// define email body - start
     
      // process variables using t()
     
$email_body = t($params['log_entry']['message'], $params['log_entry']['variables']);

     
// decode html special characters
     
$email_body = htmlspecialchars_decode($email_body);

     
// remove html tags
     
$email_body = strip_tags($email_body);
     
     
// define email body - end
     
      // set email body
     
$message['body'] = $email_body;
     
      break;
  }
}
?>

Now, when log entries are created that match the defined severity, they are emailed to the recipient list.

Eric.London's picture

For my blog, I thought it would be great if I was notified when a comment was submitted. Like most of my articles, I try to explain how to accomplish something by implementing your own module hooks. In this article, I'll explain how I modified the comment form using a form_alter hook, and added an additional submit handler to send an email using drupal_mail.

First, I defined a form_alter hook to modify the comment form submit handlers

<?php
function MYMODULE_form_alter(&$form, $form_state, $form_id) {
 
// test for comment form
 
if ($form_id == 'comment_form') {
   
// add an additional submit handler
   
$form['#submit'][] = '_MYMODULE_comment_form_submit';
  }
}
?>

Next, I created the submit handler function

<?php
function _MYMODULE_comment_form_submit($form, &$form_state) {

 
// create an array of parameters
 
$params = array(
   
// NOTE: I tried using l() here,
    // but links don't work very well in text emails
       
    // this link will send me back to the node with an anchor to the comment
   
'commentLink' => 'http://' . $_SERVER['HTTP_HOST'] . base_path() .
     
$form_state['redirect'][0] . '#' . $form_state['redirect'][2]
  );
   
 
// call mail function and send email
 
drupal_mail('MYMODULE', 'comment_submitted',
   
variable_get('site_mail','MYDEFAULTEMAIL'), language_default(), $params);

}
?>

Lastly, I defined the mail hook

<?php
function MYMODULE_mail($key, &$message, $params) {
 
$language = $message['language'];
  switch(
$key) {
    case
'comment_submitted':
           
     
// create an array of variables from the parameters argument
     
$variables = array(
       
'!commentLink' => $params['commentLink'],
      );
           
     
// define subject and body
     
$message['subject'] = t("A comment has been submitted");
     
$message['body'] = t("!commentLink", $variables, $language->language);
           
      break;
  }
}
?>

Now when a comment is posted, my submit handler is called which notifies me of the new comment.

Eric.London's picture

Here's a code snippet that shows you how to use the drupal_mail function to send an email. First, define a callback function that will handle the creation of the message. NOTE: this function must end with "_mail"

<?php
function MYMODULE_mail($key, &$message, $params) {
  switch (
$key) {
    case
'invitation':
     
// note: data can be passed to this function in the $params array
     
$message['subject'] = t('EMAIL SUBJECT');
     
$message['body'] = t('MESSAGE BODY');
      break;   
  }
}
?>

Now, we can use this callback function in our code:

<?php
$params
= array(
 
'myVar' => 'data you would like in your message and/or subject',
);
drupal_mail('MYMODULE', 'invitation', $emailTo, language_default(), $params);
?>

More information about drupal_mail can be found here. NOTE: if you're going to send an email to a registered user, you should use the data found in $user for the language and email address.

Syndicate content