WebTechKitchen; Your Web Technology Kitchen, contact us to create, or maintain your websites and other digital properties.

Sending an email from Drupal

Submitted by barnettech on Wed, 03/17/2021 - 14:10
/**
 * Implements hook_mail().
 */
function app_voucher_mail($key, &$message, $params) {
  $function = 'app_voucher_mail__' . $key;
  if (function_exists($function)) {
    return $function($key, $message, $params);
  }

  /*
   * @I Convert the enrollment email to use the new mail handler
   *    type     : improvement
   *    priority : normal
   *    labels   : refactoring
   */
  if (!empty($params['from'])) {
    $message['from'] = $params['from'];
  }
  $message['subject'] = $params['subject'];
  $message['body'][] = $params['body'];
}

/**
 * Indirect implementation of hook_mail() for `voucher expiration` emails.
 */
function app_voucher_mail__voucher_expiration_warning($key, &$message, $params) {
  $host = \Drupal::request()->getSchemeAndHttpHost();
  $message['from'] = \Drupal::config('system.site')->get('mail');
  $message['subject'] = t('Your voucher is about to expire');
  $link = Url::fromUri('internal:/dashboard/' . $params['uid'] . '/my-vouchers');
  $message['body'][] = t('Your voucher is about to expire.  Click here to view and manage your list of vouchers . ' . $host . '/dashboard/' . $params["uid"] . '/my-vouchers');
}

// Send email to use to remind them of voucher expiring.
    $mail = $account->getEmail();
    $mailManager = \Drupal::service('plugin.manager.mail');
    $from = 'jamesbarnett@ipc.org';
    $host = \Drupal::request()->getSchemeAndHttpHost();
    $params['subject'] = "Your voucher is about to expire";
    $params['host'] = $host;
    $params['uid'] = $account->id();

    // Gets the sites default langauge.
    $language = $account->getPreferredLangcode();

    if ($mailManager->mail('app_voucher', 'voucher_expiration_warning', $mail, $language, $params,
      NULL, TRUE)) {
      \Drupal::service('messenger')
        ->addMessage("Reminder email about expired Voucher sent to user: " . $account->getUsername());
    }
    else {
      \Drupal::service('messenger')->addMesage("Failed to send email.");
    }

https://www.zyxware.com/articles/5504/drupal-8-how-to-send-a-mail-progr…
shows with just 2 functions