Send email asynchroniously using Sidekiq.
Create your mailer us usual:
# app/mailers/users_mailer.rb
class UsersMailer < ActionMailer::Base
def welcome_email(user_id)
@user = User.find(user_id)
mail( :to => @user.email,
:subject => "Welcome"
) do |format|
format.text
format.html
end
end
end
Send email:
user = User.find(1)
mail = UsersMailer.welcome_email(user.id)
#mail.deliver_now
mail.deliver_later
Gemfile:
gem 'sidekiq'
Redis provides data storage for Sidekiq. It holds all the job data along with runtime and historical data
To make work mailer.deliver_later we need to tell ActiveJob to use Sidekiq:
# config/initializers/active_job.rb
ActiveJob::Base.queue_adapter = :sidekiq
Read more about ActionJob and Sidekiq: https://github.com/mperham/sidekiq/wiki/Active-Job
Specify queue name for different environments:
# config/initializers/sidekiq.rb
Sidekiq.configure_server do |config|
config.redis = { url: 'redis://localhost:6379/0', namespace: "mysite_sidekiq_#{Rails.env}" }
end
Sidekiq.configure_client do |config|
config.redis = { url: 'redis://localhost:6379/0', namespace: "mysite_sidekiq_#{Rails.env}" }
end
bundle exec sidekiq --environment development -C config/sidekiq.yml
Use god for monitoring and running sidekiq automatically: https://gist.github.com/maxivak/05847dc7f558d5ef282e
do u know how can i skip the async email send in some situations?, for example: im using cron for some rakes that send emails daily but there i dont need to use sidekiq for it but it does anyway because of the configuration that you and i use from this tutorial