Drupal: Send email

This is a quick and easy solution to send an email from Drupal using PHP, i.e a custom module. you will do it in 2 steps (I assume your module is called “mod”):

  • Define mod_mail() (implementing hook_mail() ), this function will prepare the email
  • Send the email using drupal_mail()

Define mod_mail()

/**
 * Implementation of hook_mail.
 */
function mod_mail($key, &$message, $params) {
  switch ($key) {
    case 'basic':
      $message['subject'] = t('Greetings');
      $message['body'] = array(t('I just wanted to say hello!'));
      break;
    case 'advanced':
      $message['subject'] = t('Hello @username', array('@username' => $params['username']));
      $message['body'] = array(t('Thank you for joining @site_name!', array('@site_name' => $params['site_name'])));
      break;
    default:
      ; /* Do nothing */
  }
}

Sending the email

In order to send the email you need to decide on 2 parameters (optionally, a 3rd):

  1. The recipent (email address)
  2. The key, in this example this would be ‘basic’ or ‘advanced’
  3. The $params to pass to mod_mail(), in our example it’s only needed if we are using the key ‘advanced’
// Basic example ($key = 'basic')
$email = "someone@example.com";
drupal_mail('mod', 'basic', $email, language_default());


// Advanced example ($key = 'advanced')
$email = "someone@example.com";
$params = array(
  'username' = 'Someone',
  'site_name' = variable_get('site_name'),
);
drupal_mail('mod', 'advanced', $email, language_default(), $params);

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top