Upgrade Your Drupal Skills

We trained 1,000+ Drupal Developers over the last decade.

See Advanced Courses NAH, I know Enough

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

Parent Feed: 

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 = "[email protected]";
  $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 :)

Original Article: https://peoplesblog.co.in/blogs/Sci-Tech/Drupal/2021-01-20-Send-Mail-with-Custom-Email-Template-and-with-Dynamic-values-via-Drupal-Mail-Service.html

Original Post: 

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web