How to send emails in Drupal programmatically

Posted by admin on Tue, 01/31/2017 - 17:53

The easiest way to simply send email in Drupal programmatically.

drupal_mail('system', 'mail', 'yourmail@gmail.com', language_default(), array(
  'context' => array(
    'subject' => 'Awesome subject',
    'message' => 'Email body message here',
  )
));

Just replace yourmail@gmail.com with email of recipient, put subject and message - and your email would be sent immediately.

Another way - more complicated, but more complex - is to use hook_mail.
First what you need - is to declare in your custom module hook_mail:

/**
 * Implements hook_mail().
 */
function yourmodule_mail($key, &$message, $params) {
  if ($key == 'my_example') {
    $message['subject'] = 'Email subject';
    $message['body'][] = "This is a email message \n Some variable = {$params['some_var']}";
  }
}

This looks a little bit crazy, but this is extendable by other module with hook_mail_alter.

Then to send email using this hook - you just need to call drupal_mail with next parameters:

drupal_mail('yourmodule', 'my_example', 'to-user@mail.com',
language_default(), array('some_var' => 'Some value'));

Using this will send a email to to-user@mail.com using your hook_mail and with parameter some_var set to 'Some value'.

Tags: 
×

Hey! Don't miss a new cool stuff!

Add new comment