Drupal 8 : Programmatically sent Mail from system - Example

In Drupal 8 there is function service() from core is used to send Emails. This function returns a object that help to trigger mail from system by passing argument as “plugin.manager.mail”. Using this Object call mail() function.

After initiate mail need to call hook_mail() for define the Mail subject, Body and From address.


// Call below code in your function.
$sentMail = \Drupal::service('plugin.manager.mail')->mail(MODULE_NAME, UNIQUE_KEY, TO_MAIL, LANGUAGE, PARAMETERS, REPLY, SEND);
// Parameters
MODULE_NAME - Module that send mail.
UNIQUE_KEY - Unique Key identifying mail.
TO_MAIL - Receiver mail ID.
LANGUAGE - Message language.
PARAMETERS - Contains mail subject and body.
REPLY - Boolean value TRUE or FALSE for Reply or Not Reply.
REPLY - Boolean value TRUE or FALSE for Send Mails.
function MODULE_NAME_mail($key, &$message, $params) {
  if ($key == UNIQUE_KEY) {
    $message['from'] = FROM;
    $message['subject'] = PARAMETER_SUBJECT;
    $message['body'][] = PARAMETER_BODY;
FROM - From Mail Id for the mail. 


function faq_ask_node_update($node) {
  // Get the asker account.
  $email = 'test@example.com';
  $account = user_load_by_mail($email);
  $param = array();
  // Send the e-mail to the asker. Drupal calls hook_mail() via this.
  $mail_sent = \Drupal::service('plugin.manager.mail')->mail('faq_ask', 'notify_asker', $email, $account->getPreferredLangcode(), $params, NULL, TRUE);
  // Handle sending result.
  if ($mail_sent) {
    print "Mail Sent successfully.";
  else {
   print "There is error in sending mail.";
 * Implements hook_mail().
 * This function completes the email, allowing for placeholder substitution.
function faq_ask_mail($key, &$message, $params) {
  if (($key == 'notify_asker') || ($key == 'notify_expert')) {
    $message['from'] = 'info.codeexpertz@gmail.com';
    $message['body'] = "This is Sample mail content for testing purpose from CodeExpertz";
    $message['subject'] = "Test Mail from CodeExpertz";