MailChimp and Java Integration – Part 2

In the previous article, we showed how to connection your Java application to MailChimp using the MailChimp api and the XML-RPC library provided by Zviki Cohen at nWire Software. The code in the article also provided a method to initialize the MailChimp mailing list by using the batch upload function in the api. This article will finish off the MailChimpHandler class by adding functionality to add, remove and update records to an existing list.

We are going to make use of two additional MailChimp api calls, listSubscribe and listUnsubscribe. Here is the completed MailChimpHandler class that adds the functionality of adding, removing and updating a record in the MailChimp list.

In a future, I'll post another article (or two) about how to get MailChimp to notify your Java application when changes are made to the mailing list (such as bounced emails, or a user unsubscribing from the list) so you can keep your contacts database in sync with changes made in the mailing list.

MailChimpHander Class (Version 2)
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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
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 connectedStatus;
    // 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() {
        // OMITTED FOR BREVITY. SEE ARTICLE 1
    }
 
    /**
    * test the connection to see if it is still good
    * @return result
    */
    private boolean testConnection(){
        // OMITTED FOR BREVITY. SEE ARTICLE 1
    }
 
     /**
     * 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){
        // OMITTED FOR BREVITY. SEE ARTICLE 1
     }
 
    /**
    * add a new contact to the MailChimp List
    * @param contactId - I need this to get the contact info in question. You will use something else.
    * @return result
    */
    public boolean addUser(int contactId){
	boolean listSubscribe = false;
        // This will hold the contact data we are going to add to the mailing list
	final Map<String, String> merges = new HashMap<String, String>();
        // Get the new contact from the database. You will use something else to get your contact
	CustomerContact contact = customerContactDao.getMailChimpCustomerContact(contactId);
        // make sure we got it, else return
	if(contact == null)
		return listSubscribe;
 
	// make sure we have had a good connection, otherwise try it again	
	if (testConnection() == false){
		log.info("Attempting to re-connect to MailChimp");
		initialize();         // reinstantiate the MailChimpServices and test connection
	}
 
        // assuming we could connect, proceed
	if (connectedStatus) {
                // Add the new contact information into the Map
		merges.put("FNAME", contact.getFirstName());
		merges.put("LNAME", contact.getLastName());
		merges.put("EMAIL", contact.getEmail());
		merges.put("EMAIL_TYPE", "html");
                // Attempt to add the new contact using the listSubscribe api
                // 5th parameter is normally HTML. We set it here so we can specify 6th parameter
                // 6th parameter is whether double opt-in message is sent (defaults to true)
		try {
		        listSubscribe = mcServices.listSubscribe(apiKey, listId, contact.getEmail(), merges,
					IMailChimpServices.EMAIL_TYPE_HTML, false);
		} catch (MailChimpServiceException mcse) {
			log.error("Error in adding user to list. " + mcse.getMessage());
			mcse.printStackTrace();
		}
		log.info("listSubscribe: " + listSubscribe);
	}else
		log.info("Could not add user because could not connect to MailChimp");
 
        // return the result of our attempt to the caller 	
	return listSubscribe;
    }
 
    /**
    * update an existing contact to MailChimp. This is essentially like the addUser method
    * except we are unsubscribing the original email from the list before adding the new one.
    * In my circumstances, it is not really know what has changed on the contact&#39;s information.
    * It could be the email address. So this is why we unsubscribe the user from the list first
    * using their old email address (which could be the same as the new email address), then we
    * add the user back in. Regardless of what data had changed in the contact, the result is it
    * gets updated in the MailChimp list without creating a duplicate.
    * @param contactId - I need this to get the contact in question
    * @param oldEmail - this tells what the previous email was before the change
    * @return result
    */
    public boolean updateUser(int contactId, String oldEmail){
	boolean listSubscribe = false;
	final Map<String, String> merges = new HashMap<String, String>();
	CustomerContact contact = customerContactDao.getMailChimpCustomerContact(contactId);
	if(contact == null)
		return listSubscribe;
 
	// make sure we have had a good connection, otherwise try it again			
	if (testConnection() == false){
		log.info("Attempting to re-connect to MailChimp");
		initialize();
	}
 
        // make sure we have a connection
	if (connectedStatus) {
		// first UNSUBSCRIBE the original email address
                // the 4th parameter is to delete the existing MailChimp record (defaults false)
                // the 5th parameter is whether to send a goodbye message or not (defaults true)
                // the 6th parameter is whether to send a notification message or not (defaults true)
		try {
			listSubscribe = mcServices.listUnsubscribe(apiKey, listId, oldEmail, true, false, false);
		} catch (MailChimpServiceException mcse) {
			log.error("Error in unsubscribing user from list. " + mcse.getMessage());
			mcse.printStackTrace();
		}
		// then SUBSCRIBE the new email address
		merges.put("FNAME", contact.getFirstName());
		merges.put("LNAME", contact.getLastName());
		merges.put("EMAIL", contact.getEmail());
		merges.put("EMAIL_TYPE", "html");
		try {
			listSubscribe = mcServices.listSubscribe(apiKey, listId, contact.getEmail(), merges,
					IMailChimpServices.EMAIL_TYPE_HTML, false);
		} catch (MailChimpServiceException mcse) {
			log.error("Error in adding user to list. " + mcse.getMessage());
			mcse.printStackTrace();
		}
		log.info("listSubscribe: " + listSubscribe);
	}else
		log.info("Could not add user because could not connect to MailChimp");
	return listSubscribe;
    }
 
    /**
    * delete a contact from MailChimp. 
    * @param oldEmail - previous email address
    * @return result
    */
    public boolean deleteUser(String oldEmail){
	boolean listSubscribe = false;
 
	if (testConnection() == false){
		log.info("Attempting to re-connect to MailChimp");
		initialize();
	}
	// make sure we have a connection
	if (connectedStatus) {
		// UNSUBSCRIBE the original email address
                // the 4th parameter is to delete the existing MailChimp record (defaults false)
                // the 5th parameter is whether to send a goodbye message or not (defaults true)
                // the 6th parameter is whether to send a notification message or not (defaults true)
		try {
			listSubscribe = mcServices.listUnsubscribe(apiKey, listId, oldEmail, true, false, false);
		} catch (MailChimpServiceException mcse) {
			log.error("Error in unsubscribing user from list. " + mcse.getMessage());
			mcse.printStackTrace();
		}
		log.info("listSubscribe: " + listSubscribe);
	}else
		log.info("Could not remove user because could not connect to MailChimp");
	return listSubscribe;
    }
 
}
This entry was posted in Java and tagged , , . Bookmark the permalink.

5 Responses to MailChimp and Java Integration – Part 2

  1. Pingback: MailChimp and Java Integration – Part 1 | Othenos, Inc.

  2. Nagesh says:

    Hi,
     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.

  3. Nagesh says:

     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.

  4. mkchronos says:

    Excellent article on how to implement MailChimp using Java.  Thanks for taking the time to help others that were looking for an overview on how to make it happen using the tools nwire put out there (and fast-tracking a working solution).

    One correction for your code I think.  I believe for the areas you put:
    if (connectedStatus)

    I believe you meant to put:

    if (connectionStatus)

    Since it's checking the boolean status for the variable connectionStatus.

    Thanks again for posting this, I'll be interested in seeing your approach on implementing the check for unsubscriptions and keeping the list in sync (you mentioned a future post).  Always nice to have a comparison.
    - Alex

  5. admin says:

    Thanks for the comment Alex. Yes, you are right about a mistake in the code. What I meant was the class variable 'connectionStatus' should have been 'connectedStatus'. I have made the correction.

    I am working on the article about how to detect changes in the MailChimp list and sync your database with those changes.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <font color="" face="" size=""> <span style="">