Add a MailChimp subscribe feature to your contact form

MailChimp is a great email marketing service provider with an easy to use control panel and features like: campaign management (RSS-driven, A/B Split, Plain-text and regular), statistics, auto-responder and a complete set of list management tools. They offer different ways to place a subscriber form on your website or blog. If you to like add the MailChimp subscribe feature to your existing contact form you need to add some custom code. 

A subscribe box on your contact form, is a huge opportunity to get more subscribers for your newsletter. Most people will use this tiny subscribe box much faster than using a standard MailChimp subscribe form!

This tutorial is about how to use the MailChimp subscribe feature on your existing contact form. The tutorials steps should be easy enough to add the code to your own contact form, even if you’re not a PHP developer. This tutorial is a complete rewrite from an older version, because the old tutorial code didn’t worked with the current MailChimp API system (version 2). So if you already use the old code, you need to update!

MailChimp subscribe feature

Preparations

  • If you don’t have a MailChimp account, register one at MailChimp. They offer a free account for the first 2.000 mailing list members and for 12.000 messages a month. Sign-up now for free and get a $30 bonus if you upgrade your account later.
  • Setup a mailing list via the MailChimp control panel and obtain the Unique ID (via Lists -> Your List -> Settings, bottom page).
  • Next you need an MailChimp API Key, create one from the control panel (Account -> Extras -> API Keys)
  • As an option create a custom field (Lists -> Your List -> Settings -> List Fields and *|MERGE|* Tags) and name it subscription_via. Don’t change the other variables. We use this additional merge field to store the information where a subscription happens with the contact form we build in this tutorial.

HTML  for the contact form 

First you need is contact form with form fields for name, e-mail address, a check-box for the subscription and of course a text-area for the sender’s message. I use a basic HTML example for better understanding. In the example below the form is processed by a script names “process.php”.

<form action="process.php" method="post">
	<div>
		<label for="name">Name</label>
		<input type="text" value="" name="name" />
	</div>
	<div>
		<label for="email">E-mail</label>
		<input type="text" value="" name="email" />
	</div>
	<div>
		<label for="message">Message</label>
		<textarea name="message" cols="30" rows="4"></textarea>
	</div>
	<div>
		<input type="checkbox" value="yes" name="newsletter" />
		<label for="newsletter">Subscribe to newsletter</label>
	</div>
	<div>
		<input type="submit" value="Register" name="subscribe" />
	</div>
</form>

MailChimp API wrapper

The MailChimp API offers several ways to communicate with the MailChimp system. If you work mostly with PHP you can use the official API wrapper. I use for this tutorial the simplified MailChimp API Wrapper by Drew McLellan because this PHP class is much easier to use. Add the following code to your PHP mail script which is used to process your contact form, in our case it would be the file “process.php”. Choose a location in your code right after the mail is send, that could be after the use of the mail() function or the code your use from PHPMailer

include_once 'MailChimp.php';

$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);

$mc = new \Drewm\MailChimp('YOUR_MC_API_KEY');
$mvars = array('optin_ip'=> $_SERVER['REMOTE_ADDR'], 'FNAME' => $name, 'MMERGE3' => 'VALUE_FOR_OPT_MERGEFIELD');
$result = $mc->call('lists/subscribe', array(
		'id'                => 'UNIQUE_LIST_ID',
		'email'             => array('email'=>$email),
		'merge_vars'        => $mvars,
		'double_optin'      => true,
		'update_existing'   => false,
		'replace_interests' => false,
		'send_welcome'      => false
	)
);

The code from top to bottom:

  1. Include the MailChimp wrapper class (use the right path to prevent a PHP error)
  2. filter the form input using the filter_var() function
  3. Create a new object with your MailChimp API key as argument
  4. Define the merge vars: IP address, first name and the optional merge var we defined before in MailChimp
  5. Make an API call to the “lists/subscribe” end point using the merge vars and some other array values. Don’t forget to enter here the unique mailing list ID. The other values are some kind of default change them if necessary.

After API call is done, your script will receive a response from the MailChimp API system. This response is stored as an array inside the variable $response.

With the code below were are able to check/validate the response. Add the code below the previous part.

if (!empty($result['euid'])) {
	echo 'Thanks, please check your mailbox and confirm the subscription.';
} else {
	if (isset($result['status'])) {
		switch ($result['code']) {
			case 214:
			echo 'You\'re already a member of this list.';
			break;
			// check the MailChimp API if you like to add more options
			default:
			echo 'An unknown error occurred.';
			break;
		}
	}
}

If the response contains an array element with the key “euid”, the subscription was successful. The subscriber will receive an email message with the conformation link (double-optin). Otherwise we use the error code from other array elements to decide which (error) message the script needs to show. My example is using only code “214”, which means that a subscriber is already a member. Check the MailChimp API documentation (link below) for additional code values.

MailChimp subscribe tutorial code

As mentioned before this tutorial is about how to add the MailChimp subscribe feature to your existing contact form. The code below is just a concept how the HTML form could be processed. Your PHP mail script will look different and my advice is to test this modification on your test location first. 

<?php
include_once 'MailChimp.php';

if (isset($_POST['Submit'])) {
	if (empty($_POST['name']) || empty($_POST['email'])) {
		echo 'Please enter a name and email address.';
	} else {
		$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
		$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
		/*
		 * Place here your validation and other code you're using to process your contact form.
		 * For example: mail('your@mail.com', 'Subject: contact form', $_POST['message']);
		 * Don't forget to validate all your form input fields!
		 */
		if (!empty($_POST['newsletter'])) {
			$mc = new \Drewm\MailChimp('YOUR_MC_API_KEY');
			$mvars = array('optin_ip'=> $_SERVER['REMOTE_ADDR'], 'FNAME' => $name, 'MMERGE3' => 'VALUE_FOR_OPT_MERGEFIELD');
			$result = $mc->call('lists/subscribe', array(
					'id'                => 'UNIQUE_LIST_ID',
					'email'             => array('email'=>$email),
					'merge_vars'        => $mvars,
					'double_optin'      => true,
					'update_existing'   => false,
					'replace_interests' => false,
					'send_welcome'      => false
				)
			);
			if (!empty($result['euid'])) {
				echo 'Thanks, please check your mailbox and confirm the subscription.';
			} else {
				if (isset($result['status'])) {
					switch ($result['code']) {
						case 214:
						echo 'You\'re already a member of this list.';
						break;
						// check the MailChimp API docs for more codes
						default:
						echo 'An unknown error occurred.';
						break;
					}
				}
			}
		}
	}
}

I assembled a working example which is available as download here. If you’re interested to try the example first check the MailChimp demo here.

MailChimp resource links

MailChimp subscribe/list API – If you need further information about the API endpoint I’ve used for this tutorial.

Official PHP wrapper – The API wrapper for PHP5 maintained by MailChimp.

MailChimp error codes – The list of error codes MailChimp might return as a response for your subscription request. Note this list is created for the API version 1.3, but the codes should be valid for current version, too.

Published in: PHP Scripts

19 Comments

    1. Hi,

      me too, check the tutorial code :)
      This tutorial is for the people didn’t know how to add a subscribe function to their contact form.

  1. Hi Olaf,

    thanks for the example, using your code it was much easier to understand how it works.
    I used your code for some older site with a hand-written script and now I’m looking for a similar function for WordPress. Is it possible to add this feature to a comment form as well? I see your blog has this function already, but this is a plugin right?

  2. hello,
    I used this and working fine.. Thanks :) but user need to accept email to subscribe. Can we add user’s email without subscribe email?

  3. I downloaded your form entered my Api key, list id, and email. I get a two lines Warning: unexpected character in input: “\” (ASCII=92) state=1 /the file location/contactform.php on line 19. and Parser error: syntax error, T_STRING in /the file location/ contactform.php on line 19.

    any suggestions?

    Thanks, Dave

    1. Dave,

      looks like your PHP version is a bit outdated, this object declaration requires PHP 5.3 or higher:
      $mc = new DrewmMailChimp('YOUR_API_KEY');

  4. Thanks for the writeup. I am having a bit of trouble however. I downloaded the example files and replaced the API Key and the list ID values. I uploaded the folder to my server and tried filling in the form. I just receive a blank page. Nothing goes to mailchimp, i dont receive any validation errors like in your demo either. Any help would be appreciated.

    1. Hi Darrell,
      I think your PHP version is too old. You need at least PHP version 5.3 or higher.
      Let me know if it’s something else.

  5. Hi Olaf,

    Thanks for this tutorial, I used the same API Wrapper and it worked well.
    But yesterday it stopped for no reason.
    The result code I get is 1, I guess that means the function runs well? I cannot find this information on the Mailchimp API page.

    Thanks!

  6. Hey, trying to get this to work but can’t seem to..? The form is present but when I hit send it refreshes the page with no messages.

    I set up a text field in the List Fields and *|MERGE|* Tags section and labeled it subscription_via

    Put the API key in and list ID

    Added my email address to the $email variable

    added in MERGE4 from my created text field –
    $mvars = array('optin_ip'=> $_SERVER['REMOTE_ADDR'], 'FNAME' => $name, 'MERGE4');

    All from your source code but it’s not working… Am I missing something obvious? Running latest PHP. I noticed mailchimp is now on v3.0 will this be effecting it?

    Thanks in advance and very easy to digest tutorial I’m just pulling my hair out over this one!

    Pastebinned here http://pastebin.com/wQT2W90N

    1. Hello Ben,
      Like I said in my email, the problem is in your IF statement:
      if (isset($POST['Submit'])) {
      You need an underscore between $ and POST :)

  7. Hi, I would like to use this form in my production web site which is made in Joomla 3.2. How can I insert this “module” in the Joomla article for example or do I have to do it other way?

    Thanks

    1. Hi Eli,
      first you should update your Joomla system because all versions before 3.4.5 need to get patched.

      If you still think Joomla is the best way to create websites, you need to change your theme files to add the subscription feature to your website. I know it’s sometimes not a basic modification and a Mailchimp plugin might be an easier.

      One difference between Joomla and WordPress is that WordPress offers hundreds of (easy) options to add this Mailchimp feature. For Joomla you need to stick with a few options and most of them are less flexible and/or not free.

  8. Thanks Olaf,

    thank you. You are right. My old site is one year old and was off all the time. Now I used old website and made new one with template I purchased one year ago. New site is still not online. Yesterday I updated it to last Joomla 3.4.8. I am planning to migrate to WordPress but I wanted to use template and my knowledge of the Joomla because I am in a hurry. The site must go online and after that I will have a time to learn WordPress and to move the site to new technology. Maybe it sounds stupid but I can not afford new one now because of time pressure. I would buy a module that works for Joomla but I can not find anyone that is working as expected. Your code is just fine and it works localy on XAMP but I don’t know how to establish it on Joomla. I am not familliar with PHP and Joomla programming, I am more familiar with Java.

  9. I am using this code but I am getting this error . This is show by print_r($result);

    Array ( [status] => error [code] => 250 [name] => List_MergeFieldRequired [error] => NAME must be provided – Please enter a value )

    1. Like that error message states: the NAME field isn’t entered. Looks like you marked that field als required in your Mailchimp mailing list.

Comments are closed.