Upgrade Your Drupal Skills

We trained 1,000+ Drupal Developers over the last decade.

See Advanced Courses NAH, I know Enough

Queue email

Parent Feed: 

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.

Author: 
Original Post: 

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web