Sending an email when a form is submitted using form_alter and drupal_mail

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);

}
?>

Last 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.

Updated: