For Drupal 8, see How to use create custom tokens in sending mails in drupal 8 Programmatically, and the code it shows.For Drupal 8
// We need to include the needed class for tokens.
use Drupal\Core\Render\BubbleableMetadata;
/**
* 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;
}
/**
* Implements hook_tokens().
*/
function modulename_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
$replacements = array();
$simple = $data["customanything"];
if ($type == 'customtokentype') {
foreach ($tokens as $name => $original) {
// Find the desired token by name
switch ($name) {
case 'customtoken':
$new = $simple;
$replacements[$original] = $new;
break;
}
}
}
// Return the replacements.
return $replacements;
}
Getting the value of tokens in your function requires code similar to the following one.
$token = \Drupal::token();
$message_html = "hello my custom token is replaced see it here [customtokentype:customtoken]";
// Token data.
$data = array('customanything' => $tosendtotokens);
$message_html = $token->replace($message_html, $data);