4

I want to use a template file for preparing the email message body using the table tag, and putting the submitted form data by user in table rows. I have implemented hook_mail() with the following code.

function get_price_mail($key, &$message, $params) {
  switch ($key) {
    case 'mail_to_eberhard':
      $message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed; delsp=yes';
      $message['subject'] = t('Factory Purchase - ').\Drupal::config('system.site')->get('name');;
      $message['body'][] = $params['message'];
      break;
   }
}

I created a template file (get_price/templates/mail-to-eberhard.html.twig), but the message body is not using my template file.

How do I make Drupal 8 use my template file?

1 Answer 1

7

So here is the answer: Inside the hook theme function of your module use this code

function get_price_theme() {
  return [
    'mail_to_eberhard' => array (
        'template' => 'mail-to-eberhard',  // TWIG File
        'variables' => array('submitted_data'=>[]),
    ),
  ];
} 

where variables is the array of parameter you want to send to the template file. Now create a template file named as mail-to-eberhard.html.twig inside your modules template folder. Then inside the hook_mail() alter function use this code.

function get_price_mail($key, &$message, $params) {
  switch ($key) {
    case 'mail_to_eberhard':
      $message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed; delsp=yes';
      //$message['from'] = \Drupal::config('system.site')->get('mail');
      $message['subject'] = t('Factory Purchase - ').\Drupal::config('system.site')->get('name');;
      //$message['subject'] = t('Article created: @title', array('@title' => $params['node_title']), $options);
      // Render the template to HTML
      // Set up email template
      $body_data = array (
         '#theme' => 'mail_to_eberhard',
         '#submitted_data' => $params['message']
      );
      //$message['body']['#theme'] = 'mail_to_eberhard';
      $message['body'][] = \Drupal::service('renderer')->render($body_data);
      break;
  }
} 

now inside you template file you can use the array variables like this

You have received one new message from the Get Price Tab.<br/><br/>
<b>Full Name</b> : {{ submitted_data['user_full_name'] }}<br/>
<b>Email</b> : {{ submitted_data['user_email'] }}<br/>
<b>Phone</b> : {{ submitted_data['user_number'] }}<br/>
<b>State</b> : {{ submitted_data['user_state'] }}<br/>
<b>Product SKU</b> : {{ submitted_data['product_sku'] }}<br/>
<b>Product URL</b> : <a href='{{ submitted_data['product_url'] }}'>{{ submitted_data['product_url'] }}</a>
<br/><b>Message</b> : {{ submitted_data['user_message'] }`

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.