[Drupal-8] How to Send a Mail Programmatically in Drupal 8

| | 2 min read

This article covers, how to send email programmatically in your Drupal 8 site. There are two main steps to send an email using Drupal 8. First we need to implement hook_mail() to define email templates and the second step is to use the mail manager to send emails using these templates. Let's see an example for sending an email from the custom module, also the following name spaces.

use Drupal\Core\Mail\MailManagerInterface;
use Drupal\Component\Utility\SafeMarkup;
use Drupal\Component\Utility\Html;
 * Implements hook_mail().
function module-name_mail($key, &$message, $params) {
  $options = array(
    'langcode' => $message['langcode'],
  switch ($key) {
    case 'node_insert':
      $message['from'] = \Drupal::config('system.site')->get('mail');
      $message['subject'] = t('Your mail subject Here: @title', array('@title' => $params['title']), $options);
      $message['body'][] = Html::escape($params['message']);

Here, the variables $key, $message and params can be described as :

  • $key: An identifier of the mail template.
  • $message: An array to be filled in. Elements in this array include: id, to, subject, body, from, headers
  • $params: An array of parameters supplied by the caller of drupal_mail().

Now lets create a custom function to send the mail using mail manager.

function custom_function_name() {
  $mailManager = \Drupal::service('plugin.manager.mail');
  $module = 'module-name';
  $key = 'node_insert'; // Replace with Your key
  $to = \Drupal::currentUser()->getEmail();
  $params['message'] = $message;
  $params['title'] = $label;
  $langcode = \Drupal::currentUser()->getPreferredLangcode();
  $send = true;

  $result = $mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send);
  if ($result['result'] !== true) {
    $message = t('There was a problem sending your email notification to @email.', array('@email' => $to));
    drupal_set_message($message, 'error');

  $message = t('An email notification has been sent to @email ', array('@email' => $to));

Hope this helps, now checkout how to configure SMTP in Drupal 8 using swiftmailer Module

If you have any queries, please feel free to get in touch with us.