Sunday, March 18, 2012

Some Tips on Integrating MailChimp with Rails 3

At one point we had rolled our own newsletter functionality but as our app continued to grow we found it easier to hand over the responsibility to a company that specialized in it. After looking around a bit, we settled on MailChimp.

The basic issue was how to coordinate adding and removing users with the separate mail list that they were managing for us. We took a look at a couple of gems before settling on Gibbon. Here are a few things to get you started.

First of all, we'll assume you're already registered over on Mailchimp and have an API key. Fire up your favorite text editor and create a file in your config/initializers called mailchimp.rb Inside, let's set your API key:
ENV['MC_API_KEY'] = 'your_api_key'

With that done, we can now fetch your lists and add a subscriber. We're using just a single list for the moment, so we'll fetch it like this:
gb = Gibbon.new
list_id = gb.lists({:list_name => "OurSubscribers"})["data"].first["id"]

In the above example the list name is "OurSubscribers". Best to replace that with the name of your actual list. That list_id is what you'll use to create a subscriber and add them to this list. We've got it setup to run as an after_create on our user model but your situation may call for a different implementation.
gb.list_subscribe(:id => list_id, :email_address => 'vince@public.com', :merge_vars => {'fname' => 'vince', 'lname' => 'public' }, :email_type => "html",  :double_optin => false, :send_welcome => false)

A couple of things to note:
  1. 1. The email address must be valid. Don't even use @example.com to test as they will reject it.
  2. 2. Setting double_optin to false will skip sending the person you added a confirmation email. Use carefully because if you abuse this, Mailchimp will suspend your account

A full list of the options can be found on their listSubscribe docs page.

Unsubscribing a user is just as simple.
gb.list_unsubscribe(:id => list_id, :email_address => 'vince@public.com', :delete_member => true, :send_goodbye => false, :send_notify => false)


Again for a list of what these options mean, check their API page on list_unsubscribe. Some of the options we've chosen may not be right for you.

Hopefully this is sufficient to give you a little head start. If you decide to use Hominid instead, be sure to check the state of this issue first.

No comments:

Post a Comment