Wednesday, 25 October 2017

How to call the Subscribe Mail Chimp API from C#


I wanted to do MailChimp subscription. I wanted to do using C# so I did a quick google and get Reference of below Code.

Here are the Steps:

Create one Mail Chimp Account and get the API Key 





Get the list ID as shown below;



using System;
using System.IO;
using System.Net;
using Newtonsoft.Json;
using System.Diagnostics;

namespace MailChimpConfiguration
{
    class Program
    {
        static void Main(string[] args)
        {
            var apiKey = "-us17"; // your API key here
            var listId = ""; // your list ID here
            var subscribeRequest = new
            {
                apikey = apiKey,
                id = listId,
                email = new
                {
                    email = "pradsir@gmail.com"
                },
                double_optin = true,
            };
            var requestJson = JsonConvert.SerializeObject(subscribeRequest);



            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);
                }
            }

        }


        private static string CallMailChimpApi(string method, string requestJson)
        {
            var endpoint = String.Format("https://{0}.api.mailchimp.com/2.0/{1}", "us17", 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();
                }
            }
        }
    }
}

Credit :http://markheath.net/post/how-to-call-the-mailchimp-api-from-c 

No comments:

Post a Comment

Featured post

Getting Started With SOLR

Getting Started with Solr ·           Features o    Hit highlighting o    Auto correction o    Faceted Search o    Multi lan...