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!

Comments

StevVise (not verified)

Buy Cheap Online Uk Viagra http://apcialisle.com/#927 - Cialis Where To Buy Metronidazole buy generic cialis Isotretinoin tab internet pharmacy with free shipping

LesBiopay (not verified)

Levitra Schmelztabletten Preise http://buycialisuss.com - tadalafil cialis from india Viagra Super Aktiv Cialis Viagra Welche Dosierung

Stephex (not verified)

Comprar Cialis En Gijon generic cialis online canada Safe Way To Byi Viagra Online buy cialis uk Online Generic Cialis Review

Stephex (not verified)

Comprar Cialis En Gijon generic cialis online canada Safe Way To Byi Viagra Online buy cialis uk Online Generic Cialis Review

Stephex (not verified)

Comprar Cialis En Gijon generic cialis online canada Safe Way To Byi Viagra Online buy cialis uk Online Generic Cialis Review

Stephex (not verified)

Lioresal France acquistare cialis online Amoxicillin 500 Tv buy cialis uk Propranolol Sale

Add new comment