Queue email

Schedule

 

When sending email from your application, using queuing process can reduce the application response time and increase speed.

By sending the message to queue instead of sending directly at the end of server response, you may achieve better user experience. Once messages are in queue, you just need a scheduled cron task to initiate scheduled email sending.

How ?

Queuing is simple in Drupal 8

Let's imagine you have a module that currently send an email using mail plugin to multiple users:


foreach (User::loadMultiple($users) as $account) {
    \Drupal::service('plugin.manager.mail')->mail(
            'my_module,
            'my_key',
            $account->getEmail(),
            $account->getPreferredLangcode(),
            $params,
            $from->mail,
            TRUE
         );
}

 

To direct message to queue instead, you can replace with queue service:


//Create queue
    $queue = \Drupal::queue('ek_email_queue');
    $queue->createQueue();
//add data to message
    $data['module'] = 'my_module';
    $data['key'] = 'my_key';
    $data['params'] = $params;
//send to queue
    foreach (User::loadMultiple($users) as $account) {
                $data['email'] = $account->getEmail();
                $data['lang'] = $account->getPreferredLangcode();
                $queue->createItem($data);
    }

Finally, you just need to add a cron task schedule to send emails that are in queue.

Comments

Steven Jones

4 years 9 months ago

There's a module for that!

https://www.drupal.org/project/queue_mail

Will help you queue email sending on your Drupal site.

Add new comment

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.