Design by Pelling

Archived Blog

Using the MailChimp API

Using the MailChimp API

When it comes to marketing, there are many ways of gaining new business; Whether it’s via PPC campaigns, direct mail, social media etc…  One avenue that I feel is somewhat neglected is email marketing.

Email marketing provides a great way of keeping your existing customers engaged with useful content so that you can build a long-term relationship with them. These people are proven buyers of your product or service, and therefore certainly should not be ignored. If you do, you may be losing out on a lot of potential revenue.

The whole idea of email marketing may sound a little daunting at first as there’s a lot to consider. Some questions may be:

  • How do you create and send out an email?
  • Does your hosting company have hourly limits on outgoing email?
  • How do you let people subscribe, but more importantly, unsubscribe?
  • How do you measure the successfulness of your email campaigns?
  • How do you check if your email appears correctly in different email clients?

MailChimp to the rescue!

Designing an email with MailChimp

MailChimp is an awesome tool for designing and sending email marketing campaigns, as well as building and managing your email list. Best of all it’s free if you have less than 2,000 subscribers and send less than 12,000 emails per month!

It has a whole range of functionality including but not limited to:

  • A WYSIWYG editor with drag & drop functionality, which makes creating emails very easy even for users with no coding experience. They also have a wide range of premade templates you can use, or for the more advanced users, the ability to upload your own HTML and image assets.
  • An easy way to integrate a sign up form to your website or your Facebook page.
  • The ability to easily import from 3rd party websites such as Salesforce, Highrise, Eventbrite, Zoho, Zendesk, FreshBooks, Google Drive, Google Contacts etc…
  • The ability to create list segments, which offer a way to split your list into smaller segments based on their previous purchase history, interests etc…
  • The ability to A/B test your email campaigns.
  • The ability to send the email campaign:
    • Immediately.
    • At a specific time.
    • At a optimal time determined by MailChimp.
    • Via Time Warp, which allows you to send out the email at a given time in each recipient’s timezone.
  • Extensive analytics on both campaigns and lists.
  • Functionality to allow subscribers to update their details at any time, or unsubscribe should they wish to do so.
  • Etc…

As you can see, I’m a pretty big fan of MailChimp. How could you not be with such an awesome mascot, Freddie?

Freddie

The API

Today we’ll be looking at how to use the MailChimp API to subscribe users to your MailChimp lists automatically using PHP. For example, you could use it to allow users to subscribe to your newsletter when registering to your website.

The first thing you’ll need to do is get an API key from MailChimp. You can do this by logging into MailChimp then clicking on Your username » Account Settings » Extras » API Keys. You then just have to click on Create A Key, and you will be provided with a API key.

Getting an API Key

Note – You should specify a label for your own reference, so you know which site each API key is for.

Next you’ll need to find out the list ID for the list you’re subscribing users to. In case you haven’t created a list yet, you can visit this page read the official support article by MailChimp.

Once you have a list set up, you can find the list ID by selecting Lists (in the sidebar) » The caret next to Stats » Settings. At the bottom of this page you’ll see the list ID, which is an alphanumeric value that’s 10 characters long.

Now that you’ve generated an API key and know what the list ID is, let’s go and download an API wrapper. An API wrapper is a collection of code that’s designed to simplify the whole process of interacting with an API.

If you go to the MailChimp API download page, you’ll see an extensive list of API wrappers for various languages/platforms; We’ll be using PHP and version v2.x of the MailChimp API. There’s quite a few wrappers to choose from, but as we’re literally just subscribing users to our list, we’ll be using mailchimp-api by Drew McLellan (requires PHP 5.3 or above). You can click here for the direct link to the download page.

To use the wrapper, we need to create the object:

include('MailChimp.php');
$mc = new MailChimp('your-api-key-goes-here');

You’ll need to specify the API key you generated earlier when creating the object, i.e. replace the your-api-key-goes-here with your API key.

Now that we’ve created the object, we can go about subscribing a user to our list. You can do this using the call and lists/subscribe methods as shown below:

$result = $mc->call('lists/subscribe', array(
'id'                => 'your-list-id-goes-here',
'email'             => array('email'=>'freddie@tastybananas.com'),
'merge_vars'        => array('FNAME'=>'Freddie', 'LNAME'=>'Smith'),
'double_optin'      => false,
'update_existing'   => true,
'send_welcome'      => false,
));

Here’s a list of what each field above does:

  • id (required) – This is the list ID of the list the user should be subscribed to.
  • email (required) – This is the email address of the user you’re subscribing.
  • merge_vars (optional) – You can use this to save additional information about the user, such as the first name and last name as shown above.
  • double_optin (optional) – This defaults to true and dictates whether or not you want to use the double opt-in system. This means that they will receive an additional email asking them to confirm the subscription.
  • update_existing (optional) – This defaults to false and specifies what happens when an existing email is being used to subscribe. If it’s false it will return an error message, whereas if it’s true it will update the information instead.
  • send_welcome (optional) – If double_optin is set to false and this is set to true, it will send new subscribers a welcome email.

You can download a working version of the above code by clicking on the link below. Don’t forget to fill in your API key and list ID.

The object will return true along with MailChimp’s response JSON if the request was successful, or false if there was an error sending the request. You can use this to output an appropriate message to the user. Again, you can view the list/subscribe documentation to find out more.

Keeping an eye on your API

MailChimp API reports

As with most things, it’s worth keeping an eye on your API calls just in case an issue arises. Luckily, MailChimp has a section on the API page that shows you details of the API calls made in the last 24 hours. Again, you can access the page by clicking Your username » Account Settings » Extras » API Keys.

And that’s about it! I hope you found this tutorial useful, and as always please don’t hesitate to leave a comment if you have any suggestions, questions or constructive criticisms!

  • Pingback: Using the MailChimp API | Make a smarter web us...()

  • Keith

    Hi. Thanks for this article – I’m a new developer who is trying to find a solution to an issue that this might work with but I’m new to APIs.

    I’ve recently migrated a large list of subscribers from a different system to MailChimp and I have the subscriber forms set up etc.

    The challenge is that I need a way for people to check if their email is already subscribed with us, but using MailChimp’s generic forms – they are forced to complete the entire subscriber form (address, preferences etc.) before they are given the message that their email address already exists, and then given the option to have a personalized link emailed to them.

    Do you think that the solution you post above would work where I could use the API to confirm simply that their email address already exists and send them an email with a personalized URL to update?

    • hodaka

      Hi Keith,

      Thanks for your comment!

      I personally haven’t had to handle a case like the one you described. However the first question that comes to mind is where the form is going to be placed, i.e. whether or not it will require login to access.

      Before proceeding, please note that the documentation for any method I mention below can be viewed on http://apidocs.mailchimp.com/api/2.0/

      If it’s behind a login
      ===============

      Let’s say a user subscribed to the list when they registered to your eCommerce website. In this case, you would have most likely validated their email address during the registration process, so it’s quite easy to use the API to allow a new user to subscribe or an existing user to update their information.

      So on a “Edit Details” page or similar, you could:

      – Use the “lists/member-info” method to check if the user is already subscribed to your list

      – If they are already subscribed, the above method can be used to prefill the form fields with existing information

      – Upon submission of the form, you can use the “lists/subscribe” method to add/update the user as necessary. Note – you will need to have the “update_existing” parameter set to “true” to ensure existing users are updated, rather than throwing an error

      – In both cases, I strongly recommend you pull the validated email address from the user table in your database, instead of allowing them to enter it manually via the form. This is because you’re using the API – if the user’s allowed to specify the email address via the form, they’d be free to update other people’s information as long as they know the email address

      If the form isn’t behind a login
      ======================

      An example of this would be if the sign up form is on the sidebar of your website, i.e. anyone can sign up.

      This is a little more problematic.

      The ideal functionality would probably be:

      1. They fill in their email address, which would be the first field on the sign up form

      2. You use AJAX and the API in the backend to check if they’re already subscribed

      3. If they are, you use the API to trigger the personalised update URL to be sent out

      4. If they’re not, they’re shown the rest of the form, which they can use to subscribe

      Again, checking whether or not they’re subscribed to your list should be very simple, as you can use “lists/member-info” or “helper/search-members” methods to do so. The problem is that I can’t see a method that allows you to trigger a personalised update URL to be sent out if it turns out they are already subscribed.

      Therefore I believe you have 2 options here:

      1. Use the MailChimp form that you are already using

      2. Use “lists/subscribe” with the “update_existing” parameter set to “true”. I strongly advise against this however as it means anyone can update subscriber information as long as they know the email address.

      Hopefully that all makes sense! If not, please don’t hesitate to ask.

      As I say, I haven’t actually had to handle that kind of scenario so I would be interested to hear if anyone else has a better approach.

      Kind regards,

      Hodaka

      • Higinio Fuentes

        Hello and thank you very much for your clear explanations. The code goes perfectly!
        Now I’m trying the next step: unsubscribe or delete the susbcribers created before.
        I don’t understand clearly where to find the euid! because I tried the $url = ‘http://us10.api.mailchimp.com/export/1.0/list?apikey=’.$apikey.’&id=’.$list_id; but nothing appears related to the euid! Any help on this? Thank you!

        • hodaka

          Hi Higinio,

          Glad to hear you found the article useful!

          Concerning unsubcribing a user, as you probably already know you’d need to use the “lists/unsubscribe” method (https://apidocs.mailchimp.com/api/2.0/lists/unsubscribe.php).

          A simpler way would probably be to just use the email address, so something like:

          $result = $mc->call(‘lists/unsubscribe’, array(
          ‘id’ => ‘your-list-id-goes-here’,
          ’email’ => array(’email’=>’freddie@tastybananas.com’),
          ‘delete_member’ => false,
          ‘send_goodbye’ => true,
          ‘send_notify’ => true,
          ));

          I haven’t tested the code above, but it should work. I’ve also left in all the parameters just for reference.

          Let me know if it works. If it doesn’t, I’ll try and test it at my end when I have a spare moment!

          Hodaka

          • Higinio Fuentes

            Hi Hodaka,
            Brilliant again!
            Goes perfectly, and I tried with ‘delete_member’ => true and goes fine as well.
            I let you this code, I found thanks to your explanations: is the list of all members of one list with:
            $result = $mc->call(‘lists/members’, array( ‘id’ => $mcListId ));
            Thank you again 🙂

          • hodaka

            Hi Higinio,

            No problem at all, happy to help! 🙂

            Hodaka

  • TweetsOfSumit

    Thank you for this. The Mailchimp docs suck ass. This is the simple tutorial I’ve been searching for! Great for PHP beginners.

    • hodaka

      Thanks for your comment and I’m very glad you found the tutorial useful!

  • Pages24

    How can I check if the user is subscribed?

    • hodaka

      Hi there,

      As long as you know their email address, you should be able to use the “lists/member-info” method to check if the user is already subscribed to your list. You can find more information on that method here – https://apidocs.mailchimp.com/api/2.0/lists/member-info.php

      It seems that API v3.0 is available, so you should try to use that instead of v2.0 though. I will look into updating this article in the near future.

      Kind regards,

      Hodaka

Want to hire us? We'd love to hear from you

Pelling have over 50 years combined experience designing and coding websites. We work with companies of all sizes, from one-man bands to multinational blue chip companies. We endeavour to provide high quality service, while maintaining a competitive price.

We pride ourselves in our level of customer service, which we believe is the main reason behind our high customer retention rates.

Contact us