Skip to content

Instantly share code, notes, and snippets.

@cesc1989
Forked from maxivak/00.md
Last active May 19, 2021 02:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cesc1989/cc6ab1150ba698019d0710e94ea0d851 to your computer and use it in GitHub Desktop.
Save cesc1989/cc6ab1150ba698019d0710e94ea0d851 to your computer and use it in GitHub Desktop.
How to send emails with ActionMailer and Sidekiq

Sending emails with ActionMailer and Sidekiq

Send email asynchroniously using Sidekiq.

ActionMailer

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    

SMTP Settings

# 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

Sidekiq

Gemfile:

gem 'sidekiq'

Install Redis

Redis provides data storage for Sidekiq. It holds all the job data along with runtime and historical data

Configure Sidekiq

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.

Configure Sidekiq

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

Run Sidekiq

bundle exec sidekiq
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment