How to use create custom tokens in sending mails Programmatically in drupal 8

Here we are going to see how can we send emails with token replaced dynamic values in email in drupal 8.

EVERYTHING CAN BE IN MODULENAME.MODULE FILE

1. We need to include the needed  class for tokens

use Drupal\Core\Render\BubbleableMetadata; 

 

2. Implement Hook_tokens_info

/**
 * Implements hook_token_info().
 */
function modulename_token_info() {
  $info = array();

  // Add any new tokens.
  $info['tokens']['customtokentype']['customtoken'] = t('Telling drupal that you define custom token');
  // Return them.
  return $info;
}

 

3. Implement Hook_tokens to create tokens for you when drupal access or calls your token

/**
 * Implements hook_tokens().
 */
function modulename_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
  $replacements = array();
  $simple = $data["customanything"];
  if ($type == 'customtokentype') {
    // Loop through each of the available tokens.
    foreach ($tokens as $name => $original) {
      // Find the desired token by name
      switch ($name) {
        case 'customtoken':
          $new = $simple;

          // Add the new value into the replacements array.
          $replacements[$original] = $new;
          break;
     }

}

}

 
  // Return the replacements.
  return $replacements;
}

 

4. Tokens defined now Implementation of email


/**
* Implements hook_mail().
*/

function modulename_mail($key, &$message, $params) {
 
   $options = array(
     'langcode' => $message['langcode'],
   );
  $message['from'] = \Drupal::config('system.site')->get('mail');
 switch ($key) {
    case 'custom_mail':
      $message['subject'] = \Drupal\Component\Utility\SafeMarkup::checkPlain($params['subject']);
      $message['body'][] = \Drupal\Component\Utility\Xss::filter($params['body']);
      break;
 }

}

 

5. Send Emails by calling this function anywhere


 

/**
 * Sending emails.
 */
function anyname_userdefined_to_send_notifications($tosendtotokens) {

  $mailManager = \Drupal::service('plugin.manager.mail');
  $token = \Drupal::token();

  $message_html = "hello my custom token is replaced  in email see it here [customtokentype:customtoken]";

  // Token data.
  $data = array('customanything' => $tosendtotokens);
  $message_html = $token->replace($message_html, $data, array('callback' => 'if_u_want_to_format_tokens'));

  // Admin mail.
  $params['body'] = $message_html;

  $params['subject'] = $message_html;
  $_mail = 'karthikeyanm.inbox@gmail.com';
  $send = true;
  $langcode = \Drupal::currentUser()->getPreferredLangcode();
  if (empty ($_mail)) {
    // Sending mail .
  $mails_sent = $mailManager->mail('modulename','custom_mail', $_mail, $langcode, $params, NULL, $send);

   }
  
  return $mails_sent;
}

 

6. Define your format function say if you want anything to alter in tokens before its been sending or replacing in mail.

 

function if_u_want_to_format_tokens(&$tokens) {

if (is_array($tokens) && count($tokens) > 0) {
    foreach ($tokens as $token => $value) {
      switch ($token) {
        case '[customtokentype:customtoken]':
          $tokens[$token] = "I just want to say its altered before replacement by tokens callback";
          break;  
      }
    }
  }
  return $tokens;

}

Done !

7. Now Im going to send email When new entity is inserted to my site.

/**
* Implements hook_entity_insert().
*/

use Drupal\Core\Entity\EntityInterface;

function module_entity_insert(EntityInterface $entity) {

$tosendtotokens = "I can even send entity related thing here as I have $entity object ";
anyname_userdefined_to_send_notifications($tosendtotokens);
}

 

 See You Soon with new article

 

You are Done !