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', '', language_default(), array(
  'context' => array(
    'subject' => 'Awesome subject',
    'message' => 'Email body message here',

Just replace 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', '',
language_default(), array('some_var' => 'Some value'));

Using this will send a email to using your hook_mail and with parameter some_var set to 'Some value'.


Hey! Don't miss a new cool stuff!


jessicalaex (not verified)

Thank you for the post. I really loved the way you written this post. It has some good information which is written in a easy to understand manner. This is very interesting and attractive. Keep sharing such wonderful and useful post.

hillarydavidson (not verified)

After looking at the couple of the blog articles on your online journal, I genuinely welcome your method for writing an article. I spared as a most loved it to my bookmark website page list and will checking back rather than later. Share your thoughts.

Jade Hayward (not verified)

To sending the mails in just one click is simple to do that add email addresses to those you want to send email and then send it programmatically. As usual I use this method to send emails in schools email address for new is legit books to tell them that now they can use it.

marvel-Anna (not verified)

Thanks, I followed your suggestion and indeed the mail send,help with assignment writing but instead of the form values, it sends me the subject and body from the hook mail.

Add new comment