Send Emails in Bulk with deliver_all_later

This year, Rails introduced a new method for ActionMailer called deliver_all_later. This feature simplifies enqueuing multiple emails for delivery through Active Job. Instead of sending each email individually, you can now enqueue a batch of emails, allowing them to be sent asynchronously when their respective jobs run.

What is deliver_all_later?

deliver_all_later enqueues many emails at once. When each job is executed, it sends the email using deliver_now. This improves performance by reducing the number of round-trips to the queue datastore, especially when dealing with a large number of emails.

How Does It Work?

To use deliver_all_later, you can pass an array of email deliveries:

1
2
user_emails = User.all.map { |user| Notifier.welcome(user) }
ActionMailer.deliver_all_later(user_emails)

You can even specify a custom queue if needed:

1
ActionMailer.deliver_all_later(user_emails, queue: :my_queue)

This new feature is particularly useful for large-scale email delivery, such as when you’re sending out notifications to thousands of users. By batching email deliveries, you reduce the load on your application and improve overall efficiency.