Posted in:

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 defaults page under Settings for 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.

Comments

Comment by John Bernhardsson

Hi Mark,
I am about to use MailChimp to store mailing lists for a customer and they are going outside the custom functionalities of MailChimp so I will have to use the API.
I am new to MailChimp so this post was very usefull and saved me a lot of time.
Thanx!

John Bernhardsson
Comment by Mark Heath

great, glad to hear you found it helpful

Mark Heath
Comment by Shweta

Hello Mark. I am new to the Mail Chimp so I found the article very useful for me. Can you please also guide, how to populate and sync the email and other details from C# to Mail Chimp list without the step of subscribe from email.
Highly Appreciated.
Thanks!

Shweta
Comment by Mark Heath

hi there, that's not something I've tried myself, but if I do, I'll blog about it

Mark Heath
Comment by Apeksha Thakkar Jain

hi I am getting such error {"Index (zero based) must be greater than or equal to zero and less than the size of the argument list."} on endpoint.please help me.

Apeksha Thakkar Jain
Comment by Borjan Vasovski

Great article. Thank you

Borjan Vasovski
Comment by James

It looks like you are using an example for the old 2.0 API. How is this different from the 3.0 API? Can you provide examples of same task using the 3.0 API?

James
Comment by James

How do you know which method?? I have seen examples using "us1" and "us10" but neither of those work - I get 401 unauthorized.

James
Comment by Mark Heath

look at the end of your API key

Mark Heath
Comment by Mark Heath

sorry haven't used the 3.0 API yet

Mark Heath
Comment by Mark Heath

no, but looks a useful library - wasn't around when I wrote this post!

Mark Heath
Comment by kumar

How to create list and members and subscribe how will do this mailchimp api C# Code
can you share with me

kumar
Comment by kumar

How to call created Template in mailchimp using api C# Code
can you share with me

kumar
Comment by kumar

can you have send email in mailchimp C# APi Code ?

kumar