0 Comments

I’ve been trialling the free tier of MailChimp for building the mailing list for my Skype Voice Changer application, and although you can use their pre-built forms to get people to sign up, there may be occasions that you wish to do your own server side handling of new subscriber requests, and pass the message on to MailChimp via their API.

It turns out that it is quite easy to do from C#. First of all you will need to find out your API key and list Id. To find out your API key, go to your Account settings, and then under the Extras menu there is an API keys section. You can create a key here, and disable it if necessary. Obviously you need to keep this secret.

The next step is to find out your list ID. This can be discovered with a call to the lists/list API, but can also be found if you go to the list name and defaultspage under Settingsfor that list.

For this example, we’ll be calling the lists/subscribe API, allowing us to programmatically add a new subscriber to our mailing list. You also need to know your data-center. This is found at the very end of your API key, and you’ll also see it at the start of the URLs in your MailChimp administration portal. It will be something like “us3”.

Once you know this you can construct the URL you need to call. We’re calling the 2.0 version of the MailChimp API, and the lists/subscribe method, so the URL would be as follows for the “us3” data center:

https://us3.api.mailchimp.com/2.0/lists/subscribe

With that, we can use a WebClient and call UploadString to post some JSON data to that API. Note that the MailChimp API allows the use of XML too, but JSON is the default. Here’s a method to call an API, passing in a method name (e.g. “lists/subscribe”, and a request formatted as JSON. The data center is hardcoded to “us3” in this example.

private static string CallMailChimpApi(string method, string requestJson)
{
    var endpoint = String.Format("https://{0}.api.mailchimp.com/2.0/{1}", "us3", method);
    var wc = new WebClient();
    try
    {
        return wc.UploadString(endpoint, requestJson);
    }
    catch (WebException we)
    {
        using (var sr = new StreamReader(we.Response.GetResponseStream()))
        {
            return sr.ReadToEnd();
        }
    }
}

Notice that I’m also catching WebExceptions, which we may get if the MailChimp API rejects our call.

Now we need correctly format the JSON request. I’m just constructing an anonymous object, and passing in my API key, List ID and the email I want to be subscribed. I’m also setting double_optin to true, which means this user will get emailed by MailChimp for them to confirm their address before they are added to the list. You can set it to false, but remember MailChimp are not likely to be pleased if you use this capability to add people who haven’t yet confirmed their email addresses via double opt-in.

Here’s the code that constructs the JSON request using Newtonsoft’s JSON.NET library:

var apiKey = "439583490834t34q334-us3"; // your API key here (no, this is not a real one!)
var listId = "6b414de31f"; // your list ID here
var subscribeRequest = new
{
    apikey = apiKey,
    id = listId,
    email = new
    {
        email = email
    },
    double_optin = true,
};
var requestJson = JsonConvert.SerializeObject(subscribeRequest);

Now all we need to do is process the responses. If it succeeds the response JSON will include the email and an “euid” field. If we send this message for someone already subscribed, we’ll get a status of “error” and a “name” of “List_AlreadySubscribed”. Other errors such as an invalid email address will have different names such as “ValidationError”. There is also an “error” field containing a helpful message.

To examine the response, I simply used JSON.NET to deserialize to a dynamic object and check the properties:

var responseString = CallMailChimpApi("lists/subscribe.json", requestJson);
dynamic responseObject = JsonConvert.DeserializeObject(responseString);
if ((responseObject.email != null) && (responseObject.euid != null))
{
    // successful!
}
else
{
    string name = responseObject.name;
    if (name == "List_AlreadySubscribed") 
    {
        Trace.TraceInformation("Mailchimp already subscribed");
    }
    else
    {
        Trace.TraceError("Mailchimp subscribe error {0}", responseObject.error);
    }
}

Hope someone finds that useful. The MailChimp API actually is very comprehensive, and it looks like you can do pretty much everything they offer using it.

Vote on HN
comments powered by Disqus