Hank Stoever
part time nerd, part time gnar.

Integrating mailchimp with your Rails application

posted over 3 years ago - 1 min read

Recently I added mailchimp integration to uludum. Mailchimp is a fantastic platform for email, especially for non-transactional emails. I'm using it to send occasional emails to our users. With mailchimp, designing and sending the email is extremely easy.

First things first, add gibbon to your Gemfile.

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

I had to use the gem from github, because the official gem was giving me trouble.

Then create a new initializer called config/initializers/mailchimp.rb:

if Rails.env.test?
  Gibbon::Export.api_key = "fake"
  Gibbon::Export.throws_exceptions = false
end

Rails.configuration.mailchimp = Gibbon::API.new(ENV['MAILCHIMP_KEY'])

This creates a helper client at Rails.configuration.mailchimp and sets some decent test mode settings.

We'll then create a new method in our user model called subscribe_to_mailchimp:

def subscribe_to_mailchimp testing=false
  return true if (Rails.env.test? && !testing)
  list_id = ENV['MAILCHIMP_ULUDUM_LIST_ID']

  response = Rails.configuration.mailchimp.lists.subscribe({
    id: list_id,
    email: {email: email},
    double_optin: false,
  })
  response
end

Here's whats happening here:

The method will return true immediately in test mode. This will prevent mailchimp's live API from being called.

Then we get our list ID from an environment variable. We call lists/subscribe at mailchimp. We also set double_optin to false. This will prevent mailchimp from sending an email to our user with confirmation that they'd like to be added to the mailing leist. Because we'll be subscribing the user when they sign up for our site, we don't need to them to double opt-in. Checkout the mailchimp docs for all available options.

Finally, add an after_create block to your user:

after_create do
    subscribe_to_mailchimp
end

That's it! All new users will get added to your mailchimp lists when new records are created.

Here's a test for that new method:

 describe "#subscribe_to_mailchimp" do
   let(:user) { create(:user) }
   it "calls mailchimp correctly" do
     opts = {
       email: {email: user.email},
       id: ENV['MAILCHIMP_LIST_ID'],
       double_optin: false,
     }
     clazz = Rails.configuration.mailchimp.lists.class
     clazz.any_instance.should_receive(:subscribe).with(opts).once
     user.send(:subscribe_to_mailchimp, true)
   end
 end
comments powered by Disqus