Today I have a small helper module to share with you. A small pain in the ass is that sending of e-mails requires a bit too much code. More specifically sometimes you would like to send simple alerts to webmasters. This helper module helps you with it.

Use case

I have some external databases attached to my website and I want to get notified when a database is unreachable. Moreover I would like to be able to edit the email address over time.

The module

Download and install the webmaster_alert module from my GitHub page

Specify an e-mail address at /admin/config/webmaster/alert. This setting is configuration, so it will export into your existing configuration after running

drush cex

From now on, in your custom modules you can use

webmaster_alert_send_alert($title, $message)

This will send an e-mail to the configured email address with the specified message.

How to use in my use case

So, I've set up a cron job that regularly checks if the database is still available. Then, if not, it sends out the alert.

 * uses hook_cron()
 * We check every hour if external database is still available. 
function MYMODULE_cron() {

  $databases = [

  foreach($databases as $key) {
    $dbInfo = Database::getConnectionInfo($key);
    $host = $dbInfo['default']['host'];
    $username = $dbInfo['default']['username'];
    $password = $dbInfo['default']['password'];
    $databasename = $dbInfo['default']['database'];
    $connection = mysqli_connect($host, $username, $password, $databasename);
    if (!$connection) {
      \Drupal::logger('MYMODULE')->error('The '.$key.' database is not reachable anymore.');
      webmaster_alert_send_alert('Database alert', 'The '.$key.' database is not reachable anymore.');


Want to send these in html? Check out this tutorial "How to send html emails with drupal 8". 

Saved you some valuable time?

Donate and get more free time-saving code on this website in the future.