You are here

function development_environment_mail_alter in Development Environment 8

Same name and namespace in other branches
  1. 7 development_environment.module \development_environment_mail_alter()

Implements hook_mail_alter().

Prevents the sending of emails, and instead logs them to the Drupal log.

File

./development_environment.module, line 18
Holds hooks for the Development Environment module.

Code

function development_environment_mail_alter(&$message) {
  $settings_value = \Drupal::service('settings')
    ->get('development_environment.log_emails');
  $log_emails = is_null($settings_value) ? \Drupal::state()
    ->get('development_environment.log_emails') : $settings_value;
  if ($log_emails) {
    try {

      // Stop emails from being sent.
      $message['send'] = FALSE;
      $lid = \Drupal::database()
        ->insert('development_environment_log')
        ->fields([
        'email_data' => serialize($message),
        'timestamp' => \Drupal::time()
          ->getRequestTime(),
        'recipient_email' => $message['to'],
        'subject' => $message['subject'],
      ])
        ->execute();
      if (\Drupal::currentUser()
        ->hasPermission('access development environment email logs')) {
        $url = Url::fromRoute('development_environment.suppressed_email_log', [
          'lid' => $lid,
        ]);
        $link = Link::fromTextAndUrl(t('log'), $url);
        $formatted_link = new FormattableMarkup('@link', [
          '@link' => $link
            ->toString(),
        ]);
        \Drupal::messenger()
          ->addStatus(t('The email to @email was not sent, as this is a development environment. The mail details can be viewed in the @log.', [
          '@email' => $message['to'],
          '@log' => $formatted_link,
        ]));
      }
      else {
        \Drupal::messenger()
          ->addStatus(t('The email to @email was not sent, as this is a development environment', [
          '@email' => $message['to'],
        ]));
      }
    } catch (\Exception $e) {
      watchdog_exception('development_environment', $e);
      \Drupal::messenger()
        ->addStatus(t('The email to @email was not sent, and an error occurred while trying to log it. Please see error logs for further details', [
        '@email' => $message['to'],
      ]));
    }
  }
}