Pages

Tuesday, November 11, 2008

Email marketing with ConstantContact

I had come to know few days ago about email marketing. One of the client (say MyClient) had a requirement to send mail to it's customers once a day. So what's the simple option? The simple option is to send mail to customers a day from MyClient. But if the number of recipients are thousands then MyClient will have to take load of sending so much mail. But if it would be possible to have another provider to whome MyClient provide it's client's list and the mail and then the provider would send mail as scheduled by MyClient then it should be easier for MyClient to manage. Email marketing is one with this purpose. Companies like EmailLabs, ConstantContact provide emial marketing. I had got a chance to work with ConstantContact API few days ago. But ConstantContact has no rich documentation of how to use its API with .NET. As I had figured some way to work with, I thought I need to share it with others. I'm going to provide three functions to add contact, remove contact and get the url of a list. FYI, till the day I have published this blog, ConstantContact API yet has no support for adding and updating mails.

==========================================================================================================

        /// <summary>

        /// Identify the given list's url from the constantcontact site

        /// </summary>

        /// <param name="listName"></param>

        /// <returns></returns>

        private string GetListUrl(string listName)

        {

            string apiUrl = "http://api.constantcontact.com/ws/customers";

            string userName = "user name";

            string password = "password";

            //to access api we need an api key to generate from constant contact site

            string apiKey = "yourapikey";

            //this is the namespace of returned url from constantcontact.

            //This name space is required for parsing the xml

            string xmlNamespace = @"http://www.w3.org/2005/Atom";

            //this is teh complete url to connect to

            string completeurl = apiUrl + string.Format("/{0}/lists", userName);

            Uri address = new Uri(completeurl);

            HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;

            //here the network credential will be 'apikey%username'

            request.Credentials = new NetworkCredential(string.Format("{0}%{1}", apiKey, userName), password);

            request.Method = "get";

            //request.contenttype = "application/x-www-form-urlencoded";

            HttpWebResponse response = request.GetResponse() as HttpWebResponse;

            using (response)

            {

                //get the response in reader

                StreamReader reader = new StreamReader(response.GetResponseStream());

                XmlDocument doc = new XmlDocument();

                //load the reader content in xml document

                doc.Load(reader);

 

                //prepare namespace manager here

                XmlNamespaceManager nsm = new XmlNamespaceManager(doc.NameTable);

                nsm.AddNamespace("cc", xmlNamespace);

                XmlNodeList nodes = doc.SelectNodes("//cc:entry", nsm);

                XmlNode targatedNode = null;

                foreach (XmlNode singelNode in nodes)

                {

                    XmlNode titleNode = singelNode.SelectSingleNode("cc:title", nsm);

                    //loop here to find the list name

                    if (titleNode.InnerText.ToLower() == listName.ToLower())

                    {

                        targatedNode = singelNode;

                        break;

                    }

                }

                //list name found so return here

                if (targatedNode != null)

                {

                    XmlNode idNode = targatedNode.SelectSingleNode("cc:id", nsm);

                    return idNode.InnerText;

                }

            }

            return string.Empty;

        } ==========================================================================================================

        /// <summary>

        /// Add all contacts of the given emails

        /// </summary>

        /// <param name="optMails"></param>

        public void AddContact(IList<string> emails)

        {

            try

            {

                string apiUrl = "http://api.constantcontact.com/ws/customers";

                string userName = "username";

                string password = "password";

                //to access the api u need to have an api key which u can generate from constant contact site

                string apiKey = "api key";

                string listName = "list name to which you want to add contacts";

                //get the list url

                string listUrl = GetListUrl(listName);

                string completeurl = apiUrl + string.Format("/{0}/activities", userName);

                Uri address = new Uri(completeurl);

                //create a web requst to be sent

                HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;

                //set the credential for the request. Here user name will be 'apikey%username'

                request.Credentials = new NetworkCredential(string.Format("{0}%{1}", apiKey, userName), password);

                request.Method = "post";

                request.ContentType = "application/x-www-form-urlencoded";

 

                //build data here.

                //get help from here for data format:

                //      http://developer.constantcontact.com/node/35#comment-14

                //      http://developer.constantcontact.com/doc/activities#UrlEncodedParameters

 

 

                StringBuilder sb = new StringBuilder();

                sb.Append("activityType=" + HttpUtility.UrlEncode("ADD_CONTACTS", Encoding.UTF8));

                sb.Append("&data=" + HttpUtility.UrlEncode("Email Address\n", Encoding.UTF8));

                foreach (string mail in emails)

                {

                        sb.Append(HttpUtility.UrlEncode(string.Format("{0}", mail), Encoding.UTF8));

                }

                sb.Append("&lists=" + HttpUtility.UrlDecode(listUrl, Encoding.UTF8));

                byte[] byteData = UTF8Encoding.UTF8.GetBytes(sb.ToString());

                request.ContentLength = byteData.Length;

                //write data to http stream

                using (Stream postStream = request.GetRequestStream())

                {

                    postStream.Write(byteData, 0, byteData.Length);

                }

                //read data here to ensure that the write was done successfully. If write is failed

                //then u'll get exception when u'll try to read it

                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)

                {

                    // Get the response stream 

                    StreamReader reader = new StreamReader(response.GetResponseStream());

                    //this string can be used to know the status of the write operation

                    string st = reader.ReadToEnd();

                }

            }

            catch (Exception exp)

            {

                throw;

            }

        }

  ==========================================================================================================

        /// <summary>

        /// Remove a contact from constantcontact

        /// </summary>

        /// <param name="email"></param>

        public void RemoveContact(string email)

        {

            try

            {

                string apiUrl = "http://api.constantcontact.com/ws/customers";

                string userName = "username";

                string password = "password";

                //to access the api u need to have an api key which u can generate from constant contact site

                string apiKey = "api key";

                string listName = "list name to which you want to add contacts";

                //get the list url

                string listUrl = GetListUrl(listName);

                string completeurl = apiUrl + string.Format("/{0}/activities", userName);

                Uri address = new Uri(completeurl);

                //create a web requst to be sent

                HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;

                //set the credential for the request. Here user name will be 'apikey%username'

                request.Credentials = new NetworkCredential(string.Format("{0}%{1}", apiKey, userName), password);

                request.Method = "post";

                request.ContentType = "application/x-www-form-urlencoded";

 

                //build data here.

                //get help from here for data format:

                //      http://developer.constantcontact.com/node/35#comment-14

                //      http://developer.constantcontact.com/doc/activities#UrlEncodedParameters

 

                StringBuilder sb = new StringBuilder();

                sb.Append("activityType=" + HttpUtility.UrlEncode("REMOVE_CONTACTS_FROM_LISTS", Encoding.UTF8));

                sb.Append("&data=" + HttpUtility.UrlEncode("Email Address\n", Encoding.UTF8));

                sb.Append(HttpUtility.UrlEncode(string.Format("{0}", email), Encoding.UTF8));

                sb.Append("&lists=" + HttpUtility.UrlDecode(listUrl, Encoding.UTF8));

                byte[] byteData = UTF8Encoding.UTF8.GetBytes(sb.ToString());

                request.ContentLength = byteData.Length;

 

                //write data to stream

                using (Stream postStream = request.GetRequestStream())

                {

                    postStream.Write(byteData, 0, byteData.Length);

                }

                //read data here to ensure that the write was done successfully. If write is failed

                //then u'll get exception when u'll try to read it

                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)

                {

                    // Get the response stream 

                    StreamReader reader = new StreamReader(response.GetResponseStream());

                    string st = reader.ReadToEnd();

                }

            }

            catch (Exception exp)

            {

                throw;

            }

        }