Background delivery of emails in Rails
On the Gemfile of your project just add:
and then execute
bundle install to install all gems needed for resque to work properly.
If you are using Mac just run the following commands:
$ brew install redis
$ brew services run redis // to start the redis service
If you are using GNU/Linux the recommended way is to compile from sources like this:
$ wget http://download.redis.io/redis-stable.tar.gz
$ tar xvzf redis-stable.tar.gz
$ cd redis-stable
and then start the server using:
You can find more information here.
Before sending emails you need a worker to execute the background tasks on your server so we need to create the file
/lib/tasks/resque.rake with the following content:
task "resque:setup" => :environment do
ENV['QUEUE'] = '*'
ENV['TERM_CHILD'] = '1'
ENV['RESQUE_TERM_TIMEOUT'] = '10'
desc "Alias for resque:work (To run workers on Heroku)"
task "jobs:work" => "resque:work"
and start your worker with the following command:
$ rake resque:setup
On Rails 5 you don’t need to setup anything else to start delivering emails. Just use the
deliver_later method on your Mailer. For example:
If you want to test that your emails are being delivered in background you could start the web client of redis, after starting the redis service, and check with the following command:
and you should get an interface like this one under the stats tab:
Then send and email and you should see somthing like this with the number of processed emails:
Sending background emails for Devise
To accomplish this you need to overwrite the
send_devise_notification method on your User model like this:
def send_devise_notification(notification, *args)
devise_mailer.send(notification, self, *args).deliver_later
EXTRA Heroku config
First let’s add the Redis addon to our Heroku app by going to this page:
Reliable and powerful Redis as a service.elements.heroku.com
There you should see something like this:
Click on Install Heroku Redis and on the next screen enter your app name to intall the addon:
After installing you should see a screen like this one:
where you can confirm that the addon has been installed.
Finally you need to create a new file on
config/initializers/redis.rb with the following content:
$redis = Resque.redis = Redis.new(url: ENV['REDIS_URL']) if ENV['REDIS_URL'].present?
This will initiliaze Redis if the environment variable variable is present.
And that’s it, you have configured background emails delivery with Resque and Redis in Rails. I hope this article has been useful to you.
If you have any question or suggestion let me know or leave a comment.
Author: Eng. Alberto Aragón Alvarez
If you like it, clap. For more histories like this one follow our publication on Medium.
If you want to collaborate with us please visit our web site: