DEV Community

Rahul Khan
Rahul Khan

Posted on

Sending mails using Cron in Drupal 8

In this post, we will be sending a simple birthday greeting email to the users using cron.

First, we have to create a module file in our custom module folder. We will name it as 'MODULE_NAME.module'. Using the hook_cron(), we will call a function to send the emails to the users where the mail-body is defined.

function MODULE_NAME_cron() {
    user_birthday_mails();
}
Enter fullscreen mode Exit fullscreen mode

Now we will fetch the details of the users, namely User-Name, Email-ID & Date of Birth.

In this scenario, I'm fetching the user details from a custom table.

<?php
function user_birthday_mails() {
    // this is used to send HTML emails
    $send_mail = new \Drupal\Core\Mail\Plugin\Mail\PhpMail();

    $current_m_d = date('m-d', \Drupal::time()->getRequestTime());
    $fetch_query = \Drupal::database()->query("SELECT `firstname`, `email`, `dob` FROM `TABLE_NAME`");
    $query_result = $fetch_query->fetchAll();

    foreach($query_result as $result){
        $birthday = explode('-', $result->dob);
        $birth_m_d = $birthday[1].'-'.$birthday[2];

        $user_name = $result->firstname;
        $user_mail = $result->email;

        if($birth_m_d == $current_m_d){
            $from = 'sitename@example.com';
            $to = $user_mail;
            $message['headers'] = array(
                'content-type' => 'text/html',
                'MIME-Version' => '1.0',
                'reply-to' => $from,
                'from' => 'Site Admin <'.$from.'>'
            );
            $message['to'] = $to;
            $message['subject'] = "Happy Birthday ".$user_name."!!!";

            $message['body'] = 'Dear '.$user_name.',
            <br><br>
            We value your special day just as much as we value you. On your birthday, we send you our warmest and most heartfelt wishes..
            <br><br>
            Regards,<br>
            Site Admin';

            $send_mail->mail($message);
            \Drupal::logger('userinfo')->notice('Birthday mail sent to '.$user_name);
        };
    }
}
Enter fullscreen mode Exit fullscreen mode

I hope you find this simple use of cron helpful.

Top comments (0)