Andrew Timberlake Andrew Timberlake

Hi, I’m Andrew, a programmer and entrepreneur from South Africa,
building Mailcast for taking control of your email.
Thanks for visiting and reading.


How to Add Subscribers to a MailChimp List With Ruby

I’m working on an app that creates user accounts and (optionally) subscribes users to our mailing list. Because I’m handling user creation in my app, I need some way to add them to the mailing list which is hosted on MailChimp. To do this, I am using their API to send through subscriber information.

The documentation for the ruby gem is not great. You have a few choices:

Below is some sample code that will get you started.

Install the mailchimp-api gem

> gem install mailchimp-api
# or
> echo 'gem "mailchimp-api", require: false' >> Gemfile
> bundle install

Get your MailChimp API Key

In MailChimp, go to your account settings page, click Extras and API Keys. If you don’t have an API key yet, click Create A Key.

Get your MailChimp list ID

Every list has a unique ID which is needed to add subscribers to the correct list. Got to Lists, Click on your list name, Click Settings and List name & defaults. On the right you’ll see your List ID (a 10 character hex code).

The code

require 'mailchimp' # The gem name is mailchimp-api but you require mailchimp

module MailChimpSubscription
  # These should prabably be environment variables or configuration variables
  MAIL_CHIMP_API_KEY = "0000000001234567890_us1"
  MAIL_CHIMP_LIST_ID = "abcdef1234"
  extend self

  def subscribe(user)
    mail_chimp.lists.subscribe(MAIL_CHIMP_LIST_ID,
                               # The email field is a struct that can use an
                               #    email address or two MailChimp specific list ids (see API docs)
                               {email: user.email},
                               # Set your merge vars here
                               {'FNAME' => user.first_name, 'LNAME' => user.last_name})
    rescue Mailchimp::ListAlreadySubscribedError
      # Decide what to do if the user is already subscribed
    rescue Mailchimp::ListDoesNotExistError => e
      # This is definitely a problem I want to know about
      raise e
    rescue Mailchimp::Error => e
      # Unforeseen errors that need to be dealt with
  end

  private
  def mail_chimp
    @mail_chimp ||= Mailchimp::API.new(MAIL_CHIMP_API_KEY)
  end
end

To use this module, you pass in a user object that responds to #email, #first_name and #last_name

user = OpenStruct.new(email: 'test@example.com', first_name: 'John', last_name: 'Doe')
MailChimpSubscription.subscribe(user)

Final thoughts

It’s probably a good idea to put mailing list subscription into a background job so that you don’t slow down your user creation response time. You can also handle transient errors, retry failed attempts etc.

11 Feb 2014
comments powered by Disqus