<?php
/**
* Implements hook_mail().
*/
function learndrupalway_mail($key, &$message, $params) {
$options = [
'langcode' => $message['langcode'],
];
switch ($key) {
case 'user_login':
$message['from'] = Drupal::config('system.site')->get('mail');
$message['subject'] = t('Login Notification');
$message['body'][] = t('A new user has been logged in');
break;
}
}
function send_notification() {
$mailManager = Drupal::service('plugin.manager.mail');
$module = 'mfa';
$key = 'user_login';
$to = Drupal::currentUser()->getEmail();
$params['message'] = $message;
$params['title'] = 'Your Notification';
$langcode = Drupal::currentUser()->getPreferredLangcode();
$send = true;
$result = $mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send);
if ($result['result'] != true) {
Drupal::messenger()->addError(t('There was a problem sending your email notification to @email.', ['@email' => $to]));
return;
}
$message = t('An email notification has been sent to @email ', ['@email' => $to]);
Drupal::messenger()->addError(t('An email notification has been sent to @email.', ['@email' => $to]));
}
Consider a use case, where you need to send an email based on certain conditions upon login. In such case, use the hook user login hook function and call the custom function send_notification we just built.
This code will trigger the email automatically on a prod server. However on local set up or a dev instance where there is no email sending capability, you would need a contrib module such as SMTP.
/**
* Implements hook_user_login().
*/
function learndrupalway_user_login(UserInterface $account) {
// your code logic here on when to send the email.
send_notification();
}
- Log in to post comments