Integrating Mailchimp with a contact form

Use the Mailchimp API to automatically subscribe users to your newsletter when submitting a contact form

October 2019

Mailchimp is a popular service for managing email newsletters, and something which I find myself integrating with most projects. It offers a generous free tier, useful analytics and is a great way to improve user engagement with a brand or website.

It can be useful to subscribe users to your newsletter while submitting a contact form, rather than performing a completely separate action of subscribing through an embedded form. Integrating it with an existing form also allows complete control over the styling.

I will be using PHP for handling the logic and Bulma for simple form styling. The requests are made with curl, which means the calls can be converted to be performed in other languages.

Before getting started, ensure you have registered for a free account with Mailchimp and have created an audience which users will be subscribed to.

Mailchimp setup

First login to your account and click the profile at the top-right, and choose 'Profile':

Mailchimp profile

Navigate to the Extras -> API Keys section:

Mailchimp API Key

Scroll to the bottom of the page and click 'Create a Key'; copy the key provided to somewhere safe for now.

The other thing we need from the Mailchimp admin is the Audience ID.

Click on 'Audience' at the top of the page, then the 'View Contacts' button. After, go to Settings -> Audience names and defaults. The Audience ID will be shown on the right side. Copy this to somewhere safe as well for now.

Note: be careful when copying the Audience ID as Mailchimp shows it with a full-stop after which isn't part of the actual ID.

Contact form

For this example I am using a basic HTML contact form. Nothing fancy going on here, just a form that submits to a 'submit.php' file (which will be created after).

Add this to an 'index.html' file:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Mailchimp API</title>
    <link
      rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/bulma@0.8.0/css/bulma.css"
    />
  </head>
  <body>
    <section class="section">
      <div class="container">
        <div class="columns is-centered">
          <div class="column is-half">
            <form action="./submit.php" method="post">
              <div class="field">
                <label class="label" for="name">* Name</label>
                <div class="control">
                  <input
                    class="input"
                    id="name"
                    type="text"
                    name="name"
                    placeholder="Your name"
                    required
                  />
                </div>
              </div>

              <div class="field">
                <label class="label" for="email">* Email</label>
                <div class="control">
                  <input
                    class="input"
                    id="email"
                    type="email"
                    name="email"
                    placeholder="Email input"
                    required
                  />
                </div>
              </div>

              <div class="field">
                <label class="label" for="message">* Message</label>
                <div class="control">
                  <textarea
                    class="textarea"
                    id="message"
                    name="message"
                    placeholder="Your message"
                    required
                  ></textarea>
                </div>
              </div>

              <div class="field">
                <div class="control">
                  <label class="checkbox" for="newsletter">
                    <input
                      type="checkbox"
                      id="newsletter"
                      name="newsletter"
                      value="true"
                    />
                    Do you want to sign up to the newsletter?
                  </label>
                </div>
              </div>

              <div class="field is-grouped">
                <div class="control">
                  <button class="button is-link">Send Message</button>
                </div>
              </div>
            </form>
          </div>
        </div>
      </div>
    </section>
  </body>
</html>

And here's the result:

Contact form

Integration with Mailchimp

Now that the form is all set up and ready to go, we can perform some validation when the form is submitted and make the request to Mailchimp.

Create a file named 'submit.php' on the same level as the index file.

To start with, we must first check to make sure that the user didn't directly browse to this file, and ensure that the required fields were filled. Otherwise, the user is redirected back to the form:

<?php // Process form submission and integrate with Mailchimp API

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Handle unfinished form. Remember to perform additional suitable validation here
    if (!isset($_POST['name']) || !isset($_POST['email']) || !isset($_POST['message'])) {
        // Send user back to the form
        header('Location: /');
    }

The next step is to start building the API URL to use.

The API Key we got earlier should be added to the code below. The last section of the key (after the '-') will indicate the data center to use (such as 'us18'). Add in your Audience ID as well. This section will only run if the user has chosen to subscribe to the newsletter via the form checkbox:

// Set default to handle if the user wants to subscribe or not
$subscribed = false;

// Check user has accepted to sign up to the newsletter
if (isset($_POST['newsletter'])) {
    // Set API credentials and build URL
    $data_center = 'DATA_CENTER_HERE';
    $audience_id = 'AUDIENCE_ID_HERE';
    $api_key = 'API_KEY_HERE';
    $url = 'https://' . $data_center . '.api.mailchimp.com/3.0/lists/' . $audience_id . '/members';

The code above will generate a unique URL for interacting with the specific Mailchimp account and audience.

Remember to securely store your API key as it provides full access to your Mailchimp account

Next, we will create an array that will be sent to the Mailchimp API containing the relevant details of the user.

There are many options which can be found here, such as requiring the user to validate their email, or sending additional information to be stored via merge fields. For this example I'm saving the email address of the user and automatically subscribing them:

// Build user details array to send
$user_details = [
    'email_address' => $_POST['email'],
    'status' => 'subscribed'
];
$user_details = json_encode($user_details);

This next section will make the actual POST request to Mailchimp via curl. Most of this is standard curl code which won't need modified, so don't worry about it too much. All you need to know is that it is performing the request and returning a response:

// Send POST request with cURL
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_USERPWD, 'newsletter:' . $api_key);
curl_setopt($ch, CURLOPT_POSTFIELDS, $user_details);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
	'Content-Type: application/json',
	'Content-Length: ' . strlen($user_details)
]);
$result = curl_exec($ch);
$result_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

If you are having issues and want to debug, all you have to do is add the following which will return exact details of the API error returned from Mailchimp:

print_r($result);

All there is to do afterward is to check the end-result. At this point, the user will have been subscribed if successful, and the actual email can now be sent:

        if ($result_code === 200) {
			$subscribed = true;
      	}
	}

	// Send email functionality can go here. You can notify the user that they have been subscribed or not
	if ($subscribed) {
		echo 'You have been subscribed!';
	} else {
		echo 'Something went wrong';
	}

} else {
    // Send user back to the form if URL is accessed directly
    header('Location: /');
}

If everything worked as expected, you will now have a new subscription in your Mailchimp Audience!

Successfully subscribed


Want to hire me for a project, or to fix something on your website? Get in touch 😀