MailChimp™ is a great online email marketing site. It is extremely easy to use and provides tools to manage your email lists, build attractive HTML email campaigns, and track how those campaigns performed. On top of that, it offers a free account for smaller companies. How can you beat that? Those of you who are Java programmers might want to integrate your application with MailChimp. If so, then this is for you. These two articles are going to show you how to automatically create and update your MailChimp list using Java.
Assumptions
It is assumed that you have some kind of an existing list of customers, contacts or other names with email addresses that you have in a database and manage with a Java application. And, of course, you want to be able to populate a MailChimp list with these contact email addresses, as well as keep the list updated when contacts are added, modified or deleted. If either assumption is wrong, then probably these articles are not what you're looking for! But if their right, then read on. Article 1, will focus on getting everything setup and perform the initial upload of your existing contact information. Article 2, will finish up by creating the methods that will perform the continual additions, modifications and deletions to the list as your contacts change. So let's get started.
MailChimp Basics
OK. MailChimp is pretty straightforward. I am going to let you get familiar with setting up an account and creating a list. They have plenty of help to get you started. So, if you do not already have a MailChimp account, go and create one now, I'll wait. (Note that this article does not include any details on setting up the MailChimp account or creating your mailing lists, as there are sufficient resources at MailChimp to help with that.) If you have not already done so, review the MailChimp tutorials on setting up an account and creating your first mailing list. Then do both.
API Key
Once you have your account, go to the account page (button on upper left of page after sign-in). Click the API Keys and Info button. You are going to want to create an API Key for use by your Java application. This key essentially identifies your account and provides access to it. Add a key and then make a mental note of where this information is located, as we will be coming back here later to retrieve it.
List ID
You need to create a mailing list to hold the email information you are going to upload. Go ahead and create one using the default values. A mailing list that you create in MailChimp will have a unique alphanumeric identifier. This can be found by selecting a list, then clicking the list settings link. Towards the bottom of that page you will find the ID that has been assigned to the list in question. Again, we don't need it now but will later so make a note of where to find it.
Java Connections
The MailChimp api (1.2) provides several protocols for connecting to the MailChimp servers – XML-RPC, JSON, PHP. We are going to use XML-RPC. Zviki Cohen at nWire Software has provided a nice Java xml-rpc library as a starting point in our integration attempt with MailChimp. Download it from here. Read over the MailChimp api to become familiar with the operations that are possible. There are three basic groups of functions – list management, campaign creation and sending, and campaign statistics. We are only going to be using the list management portion of the api. In this article, we are only interested in testing the connection and doing a batch upload of our data into the MailChimp list. Zviki does not define all the list management functions in the IMailChimpServices interface but he defines enough for our purposes. You can easily add additional functions to the interface as needed.
Connecting to MailChimp
The first step in our integration process will be connecting to our account on the MailChimp server. To do so, we need to have our API Key handy.Using the XML-RPC library you just downloaded, we are going to create a class called MailChimpHandler which will be our entry point for all interactions between our Java application and the MailChimp server. This class will implement the methods we have defined in the IMailChimpHandler interface. Eventually, we are going to be able to initialize the mailing list with our current set of contacts, add records to the mailing list as we add more contacts to our database, update a record in MailChimp when a contact changes in our database, and delete a record from MailChimp when deleting a contact from the database. But for right now, we just want to insure we can create the MailChimpServices and connect to MailChimp.
MailChimpHandler interface
1 2 3 4 5 6 7 8 | package com.othenos.mailchimp; public interface IMailChimpHandler { public int initializeMailChimpList(int companyId); public boolean addUser(int contactId); public boolean updateUser(int contactId, String oldEmail); public boolean deleteUser(String oldEmail); } |
MailChimpHandler class (version 1).
This version simply tests to insure that we can make a connection to MailChimp using the provided API key and List ID. After instantiating an instance of MailChimpHandler, we can call the initializeMailChimpList method to upload our list of contacts. The method will insure that the mcServices is created and will test our connection before uploading. The code is well commented, so please read though it carefully, as this is all the explanation that is provided. I hope it is enough. Once you get this working OK, then you can move on to the next article to see how to add to, delete from and modify the list.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 | public class MailChimpHandler implements IMailChimpHandler { private final Log log = LogFactory.getLog(getClass()); // API Key - see http://admin.mailchimp.com/account/api or run login() once private String apiKey = "put your api key info here"; // A List Id to run examples against. use lists() to view all // Also, login to MC account, go to List, then List Tools, and look for the // List ID entry private String listId = "put your list ID here"; // Instance of the MailChimpServices private IMailChimpServices mcServices = null; // Flag indicating status of our connection to MailChimp private boolean connectionStatus; // Class to get the attributes associated with a company from database private ICompanyAttributesDao companyAttributesDao; public MailChimpHandler() { connectionStatus = false; } /** * prepare an instance of the MailChimpServices and determine * if we can connect using our apiKey. */ private void initialize() { mcServices = MailChimpServiceFactory.getMailChimpServices(); final String ping = mcServices.ping(apiKey); if (IMailChimpServices.PING_SUCCESS.equals(ping)) { log.info("MailChimp connection pinged successfully"); connectionStatus = true; } else { log.error("Failed to ping MailChimp, response: " + ping); } } /** * test the connection to see if it is still good * @return result */ private boolean testConnection(){ if(mcServices != null) return IMailChimpServices.PING_SUCCESS.equals(mcServices.ping(apiKey)); else return false; } /** * Performs the initialization of the mail chimp list by adding * all the appropriate customer contacts to the list * @param companyId (this is optional and only here because my application needs it. Yours almost certainly won't need it) * @return number of successful insertions */ public int initializeMailChimpList(int companyId){ int listSubscribe = 0; int listFailure = 0; // insure we can connect to the server, if not then re-initialize if (testConnection() == false){ log.info("Attempting to re-connect to MailChimp"); initialize(); } // if we have confirmed we can connect OK, proceed if (connectedStatus) { // This is my way of getting all the contacts I want to add to the list // You will come up with your own way of getting your contacts List<CustomerContact> contacts = customerContactDao.getMailChimpCustomerContacts(companyId); // Instantiate an ArrayList to hold all the contact info to send // ArrayList seems to be the preferred data structure for sending and receiving array information List<Map<String, String>> chimps = new ArrayList<Map<String,String>>(); // For each of our contacts, build a HashMap of MailChimp tags and add it to the list for(CustomerContact contact : contacts){ Map<String, String> chimp = new HashMap<String, String>(); chimp.put("FNAME", contact.getFirstName()); chimp.put("LNAME", contact.getLastName()); chimp.put("EMAIL", contact.getEmail()); chimp.put("EMAIL_TYPE", "html"); // define the mail type to be HTML chimps.add(chimp); } // Now that we have the ArrayList populated, attempt to send it to MailChimp try { // attempt a batch update of the list using mcServices listBatchSubscribe method // the last 3 arguments have to do with double-optin, updating existing and replacing interests. All false for us. HashMap<String, Object> results = mcServices.listBatchSubscribe(apiKey, listId, chimps, false, false, false); // the results come back as a HashMap with three entries, success_count, error_count and errors listSubscribe = (Integer)results.get("success_count"); listFailure = (Integer)results.get("error_count"); log.info("Mail Chimp results : " + listSubscribe + " inserted and " + listFailure + " errors."); // interpret the results to see what went good and bad // The errors comes back as an array of Objects Object[] errors = (Object[])results.get("errors"); createLogFile(errors, companyId); // and update the good contacts to indicate they have been subscribed // We have opted to update our contact list to indicate that the contacts got subscribe OK // This is certainly optional customerContactDao.markContactsSubscribed(companyId); // be sure and mark contacts that have errors as not subscribed // Again, we have opted to mark our contacts that failed to get subscribed // This is optional as well for(Object item : errors){ HashMap<String,Object> result = (HashMap<String,Object>)item; HashMap<String,Object> row = (HashMap<String,Object>)result.get("row"); String fName = (String)row.get("FNAME"); String lName = (String)row.get("LNAME"); String email = (String)row.get("EMAIL"); customerContactDao.markContactsNotSubscribed(fName, lName, email); } } catch (MailChimpServiceException mcse) { log.error("Error in adding user to list. " + mcse.getMessage()); mcse.printStackTrace(); } catch(Exception e){ log.error("Error in adding user to list. " + e.getMessage()); e.printStackTrace(); } }else log.info("Could not add user because could not connect to MailChimp"); return listSubscribe; } /** * add a new contact to MailChimp * @param contactId * return result */ public boolean addUser(int contactId){ // TODO Complete return false; } /** * update an existing contact to MailChimp * @param contactId * @param oldEmail * return result */ public boolean updateUser(int contactId, String oldEmail){ // TODO Complete return false; } /** * delete a contact from MailChimp * @param oldEmail * return result */ public boolean deleteUser(String oldEmail){ // TODO Complete return false; } } |
Pingback: MailChimp and Java Integration – Part 2 | Othenos, Inc.
Hi,
I tried with the code given by you to execute the Mailchimp services.
i am not able to connet to Mailchimp services. I am getting the exception while executing the ping() method.
Exception in thread "main" com.nwire.mailchimp.MailChimpServiceException: Failed to read servers response: api.mailchimp.com
at com.nwire.mailchimp.MailChimpServiceFactory$ClientFactory$1.invoke(MailChimpServiceFactory.java:190
)
at $Proxy0.ping(Unknown Source)
Did you download the xml-rpc library from nWire software? If so, try running the test script that they have included with their package. Read their README file to setup your api key and list id for testing. Once you get that to work properly, then insure that you have all their libraries included in the project you are working on and try it again.
Hi,
Thanks for your reply. i downloaded the mcapi_java_1.2.zip file provided by Zviki.
created a project in eclipse and try to connect to mail chimp services.
i am not getting any compilation errors. while executing the ping() method from java program i am getting the exception.
i just want to use only inlineCss() service of Mail chimp.
please provide me the updated code for connecting to Mail chimp services including the xml-rpc library.
looking forward for your reply.
Thank you.
Howdy there,just found your Blog when i google something and wonder what web hosting do you use for your wordpress,the speed is more faster than my blog, i really need to know it.will back to check it out,thank you!
Janelle,
I have my own server which is hosted on the Amazon cloud service.