Drupal - How to programmatically send an email?

Using hook_mail and drupal_mail you can create and send an e-mail.

Implement an e-mail use hook_mail:

function MODULENAME_mail ($key, &$message, $params) {
  switch ($key) {
    case 'mymail':
      // Set headers etc
      $message['to'] = '[email protected]';
      $message['subject'] = t('Hello');
      $message['body'][] = t('Hello @username,', array('@username' => $params['username']));
      $message['body'][] = t('The main part of the message.');

To send a mail use drupal_mail:

drupal_mail($module, $key, $to, $language, $params = array('username' => 'John Potato'), $from = NULL, $send = TRUE)

Obviously replace the parameters: $key should equal 'mymail'

An e-mail is sent in a few steps:

  1. drupal_mail is called
  2. Drupal builds the e-mail
  3. hook_mail is called for the specifics (implementation)
  4. hook_mail_alter is called so other modules can modify it
  5. drupal_send_mail is called

If you'd like a simpler way of sending emails, check out Simple Mail; it's a module I'm working on to make sending emails with Drupal 7+ much easier, and it doesn't require any extra hook implementations or MailSystem knowledge. Sending an email is as simple as:

simple_mail_send($from, $to, $subject, $message);

You can use a simpler way of sending emails, check out mailsystem ; it's a module.

$my_module = 'foo';
$from = variable_get('system_mail', '[email protected]');
$message = array(
  'id' => $my_module,
  'from' => $from,
  'to' => '[email protected]',
  'subject' => 'test',
  'body' => 'test',
  'headers' => array(
    'From' => $from, 
    'Sender' => $from, 
    'Return-Path' => $from,

$system = drupal_mail_system($my_module, $my_mail_token);
if ($system->mail($message)) {
  // Success.
else {
  // Failure.