How to use Mailchimp API to subscribe users in Rails 4.1

Let's use the simple solution that is easy to setup and get it up and running quickly. The solution uses sucker_punch gem to subscribe user to mailing list in a background job. Read the article on Sucker Punch to learn how to set it up.


Step 1

Signup for API key here :

Step 2

Add gibbon gem to Gemfile.

gem 'gibbon', github: "amro/gibbon"

Step 3

Install the gem.

bundle install

Step 4

In secrets.yml, set the Mailchimp API key. Here is a sample config file:

  mailchimp_api_key: your-secret-api-key-goes-here 

  mailchimp_api_key: your-secret-api-key-goes-here 

  mailchimp_api_key: your-secret-api-key-goes-here 

Step 5

Create gibbon.rb in config/initializers/ directory with the following contents:

Gibbon::API.api_key = Rails.application.secrets.mailchimp_api_key
Gibbon::API.timeout = 15

Rails.application.secrets.mailchimp_api_key reads the mailchimp API Key from secrets.yml file.

Step 6

Make sure secrets.yml is added to your .gitignore file. Here is a sample .gitignore file to use in the rails root directory:

# Ignore bundler config.

# Ignore the default SQLite database.

# Ignore all config files

# Ignore all logfiles and tempfiles.

Now the secrets.yml will not get checked in to your project's git repository. You must either use capistrano or manually scp the secrets.yml to your server to shared/config directory of your Rails application. Another alternative is to use the environment variables to set the values for api credentials.

Step 7

Create a background job in app/jobs folder called subscribe_job.rb:

class SubscribeJob
  include SuckerPunch::Job

  def perform(id)
    ActiveRecord::Base.connection_pool.with_connection do
      user = User.find(id)
      mailchimp_list_id = Rails.application.secrets.mailchimp_list_id
      email =

        g =
        g.lists.subscribe({ id: mailchimp_list_id, email:  {email: email}})

      rescue Gibbon::MailChimpError => mce
        SuckerPunch.logger.error("subscribe failed: due to #{mce.message}")
        raise mce
      rescue Exception => e
        SuckerPunch.logger.error("subscribe failed: due to #{e.message}")
        raise e


You can also define the mailchimplistid as a constant in your User model.

Step 8

In your controller, you can put the job in the background by:

Step 9

If you are using Resque, you can run the failed job again as follows:

Resque::Failure.count.times do |i|


Mailchimp API 2.0

Related Articles

Ace the Technical Interview

  • Easily find the gaps in your knowledge
  • Get customized lessons based on where you are
  • Take consistent action everyday
  • Builtin accountability to keep you on track
  • You will solve bigger problems over time
  • Get the job of your dreams

Take the 30 Day Coding Skills Challenge

Gain confidence to attend the interview

No spam ever. Unsubscribe anytime.