Send Mail with Custom Email Template & with Dynamic values via Drupal Mail Service

Send Mail with Custom Email Template & with Dynamic values via Drupal Mail Service

On20th Jan 2021, 2024-11-21T08:30:46+05:30 ByKarthik Kumar D K | read
Listen Pause Resume Stop

Sending an email works with defining an email template (subject, text and possibly email headers) and the replacement values to use in the appropriate places in the template. Processed email templates are requested from hook_mail() from the module sending the email. Any module can modify the composed email message array using hook_mail_alter(). Finally \Drupal::service('plugin.manager.mail')->mail() sends the email, which can be reused if the exact same composed email is to be sent to multiple recipients.

Below function's triggerMail code, can be written in any submit handlers or post actions in Drupal.

function triggerMail() {
  $module = "x_module";
  $key = "x_mail";
  $to = "example@gmail.com";
  $langcode = 'en';
  \Drupal::service('plugin.manager.mail')->mail($module, $key, $to, $langcode);
}

Below is the hook_mail() usage, written in x_module.module file.

function x_module_mail($key, &$message, $params) {
  switch($key) {
    // To Trigger email on x_mail key.
    case 'x_mail':
      $message['headers'] = [
        'content-type' => 'text/html'
      ];
      $message['subject'] = t('X Mail subject');
      $message['body'][] = (string) getXMailMessageBody();
  }
}

Below is the helper function getXMailMessageBody() which can pull the dynamic data from the system and pass it through.

function getXMailMessageBody() {
  // Get Dynamic values.. then pass to twig file..
  return twig_render_template(
    drupal_get_path('module', 'x_module') . '/templates/x-mail.html.twig',
    [
      'theme_hook_original' => 'not-applicable',
      'dynamic_key1' => "{value1}",
      'dynamic_key2' => "{value2}
    ]
  );
}

Create a twig template file x-mail.html.twig in the module folder within templates folder.

Email Body and with dynamic values here {{ dynamic_key1 }} & {{ dynamic_key2 }}.

So, with these Drupal Mail service & custom template, you can send emails with customized message mails from your Drupal application.

Thank you :)

Related Articles

Recent Articles

Recent Quick Read

Recent Great People

We Need Your Consent
By clicking “Accept Cookies”, you agree to the storing of cookies on your device to enhance your site navigation experience.
I Accept Cookies