How to programmatically send email in html format in Drupal 8 (2)

  1. For implement the mail_hook() function, insert the following function into the *.module file inside the module folder. Assume the module name is 'your_module_name', the file path should be "/modules/your_module_name/your_module_name.module"
    /** * Implements hook_mail(). */
    function your_module_name_mail($key, &$message, $params) {
         switch ($key) {
             case 'normal':
                $message['subject'] = $params['title'];
                $message['body'][] = $params['body'];
                break;
        }
    }
    
  2. Also insert the following function into the *.module file inside the module folder for implement the mail_hook_alter() function. 
    /** * Implements your_module_name_mail_alter(). */
    function your_module_name_mail_alter(&$message){
          if ($message['module'] == 'your_module_name') {
                /*sending html formatted email*/
                $message['headers']['Content-Type'] = 'text/html; charset=UTF-8;'
          }
    }
  3. Now, you can send email in html format programatically by the following codes.
    $mailManager = \Drupal::service('plugin.manager.mail');
    $key = 'normal';//The value is the variable $key on step 1
    $module= 'your_module_name';
    $langcode = \Drupal::currentUser()->getPreferredLangcode();
    $send = true;
    $to= 'to@email.com';//Recevicer
    $from= 'from@email.com';//Sender
    $params['title'] = 'Mail Title';//Title
    $params['body'] = 'Mail Body';//Context
    $mailManager->mail($module, $key, $to , $langcode, $params, $from, $send);