Send email asynchroniously using Sidekiq.
Create mailer class:
# app/mailers/user_mailer.rb
class UserMailer < ActionMailer::Base
def welcome_email(user_id)
@user = User.find(user_id)
mail(to: @user.email, subject: "Hola")
end
end
Views for email:
app/views/user_mailer/welcome_email.html.erb - HTML version
app/views/user_mailer/welcome_email.text.erb - TEXT version
Send email:
user = User.find(1)
UserMailer.welcome_email(user.id).deliver_later
# config/environments/development.rb
Rails.application.configure do
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address: 'localhost',
port: 1025
}
end
For production
# config/environments/production.rb
Rails.application.configure do
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
domain: ENV['MAILGUN_DOMAIN'],
address: ENV['MAILGUN_HOST'],
user_name: ENV['MAILGUN_USERNAME'],
password: ENV['MAILGUN_PASSWORD'],
port: ENV["MAILGUN_PORT"]
}
end
Gemfile:
gem 'sidekiq'
Redis provides data storage for Sidekiq. It holds all the job data along with runtime and historical data
To make #deliver_later
work we need to tell ActiveJob to use Sidekiq. As long as Active Job is setup to use Sidekiq we can use #deliver_later
.
# config/initializers/active_job.rb
config.active_job.queue_adapter = :sidekiq
Read more about ActionJob and Sidekiq in the docs.
By default, jobs to deliver emails will be placed in queue named :mailers
.
config/sidekiq.yml:
---
:concurrency: 1
:queues:
- default
- mailers
Specify Redis namespace for different environments:
# config/initializers/sidekiq.rb
Sidekiq.configure_server do |config|
config.redis = { url: ENV["REDIS_URL"] }
end
Sidekiq.configure_client do |config|
config.redis = { url: ENV["REDIS_URL"] }
end
bundle exec sidekiq