How to Bulk Delete Mailchimp List Members using API

One of our team members needed to remove Mailchimp list members who were subscribed before a specified date.

Since this action is not possible directly through the Mailchimp user interface, we developed a PHP script that utilizes the Mailchimp API to delete all list members who subscribed before a defined date.

PHP Script Example

Below is an example script you can use for this task:

<?php

date_default_timezone_set('UTC');

function mailchimpRequest($type, $target, $data = false) {
    $api = array(
        'login' => 'anyuser',
        'key' => '27fd0105d2d0f76aa68405e4daecc028-us3', // Your API KEY
        'url' => 'https://us3.api.mailchimp.com/3.0/'
    );
    $ch = curl_init($api['url'] . $target);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Authorization: ' . $api['login'] . ' ' . $api['key']
    ));
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $type);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_USERAGENT, 'YOUR-USER-AGENT');
    if ($data)
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    $response = curl_exec($ch);
    if ($response === false) {
        echo curl_error($ch);
        die();
    }
    curl_close($ch);
    return json_decode($response, true);
}

function getMembersToDelete($listId, $breakingDate) {
    $offset = 0;
    $toDelete = array();
    while (true) {
        $subscribers = mailchimpRequest('GET', '/lists/' . $listId . '/members?count=100&offset=' . $offset);
        foreach ($subscribers['members'] as $member) {
            if (strtotime($member['timestamp_opt']) < strtotime($breakingDate)) {
                echo 'Scheduled to DELETE: ' . $member['email_address'] . "\n";
                $toDelete[] = $member['id'];
            } else {
                return $toDelete;
            }
        }
        if (count($subscribers['members']) == 0) {
            return $toDelete;
        }
        $offset += 100;
    }
    return $toDelete;
}

// Your list ID
$listId = 'cd17909729';

// Set the cutoff date
foreach (getMembersToDelete($listId, '2015-01-01') as $id) {
    mailchimpRequest('DELETE', '/lists/' . $listId . '/members/' . $id);
    echo 'Deleted ' . $id . "\n";
}

Note: Replace '27fd0105d2d0f76aa68405e4daecc028-us3' with your actual Mailchimp API key, and 'cd17909729' with your Mailchimp list ID.

You can find your Mailchimp API key by navigating to Account > Extras > API keys in your Mailchimp dashboard.

Warning: This script will permanently delete members from your list who subscribed before the specified date. Ensure you have a backup if needed.

Troubleshooting

If you encounter issues with the script, verify that your API key and list ID are correct and that your account has the necessary permissions to perform deletions.

×