Skip to content

Marketing & email

Verify emails and clean your Mailchimp audience

Verify each address before it joins a Mailchimp audience through the Marketing API, then clean existing members with a script that tags and archives bad ones.

Updated 2026-11-26

This recipe keeps undeliverable addresses out of a Mailchimp audience in two places. Your signup code verifies the address before it adds the member through the Marketing API, and a one-off script verifies the members already in the audience, tags each one with its result and archives those that cannot receive mail. There is no native Qelka app for Mailchimp: both pieces are short Node.js scripts that call the two APIs.

Why bother: mail sent to an address that does not exist comes back as a hard bounce, and mailbox providers read many bounces as the sign of a poorly kept list. That costs your sending domain reputation, and the next campaign lands in spam more often. Mailchimp moves addresses that hard bounce, or keep soft bouncing, to the cleaned status and stops sending to them, but by then the bounce has happened. Checking first avoids it. See Email bounces explained.

What you need

  • A Mailchimp account, a Marketing API key created in your account settings, and the ID of your audience (the API calls it list_id).
  • Node.js 18 or later, for the built-in fetch.
  • A Qelka API key. A sk_test_ key returns simulated results and never spends credits: see Test mode. With a test key, the part before the @ picks the result, so add undeliverable@example.com, catchall@example.com and unknown@example.com to a test audience to see each branch.
  • Three environment variables: MAILCHIMP_API_KEY, MAILCHIMP_LIST_ID and QELKA_API_KEY. Never put a key in code or in a browser bundle.

Steps

1. Verify before adding a member

This module runs on your server when someone submits your signup form. It verifies the address, refuses it if mail cannot be delivered, and otherwise adds or updates the member with Mailchimp's add-or-update call, then tags the member with the result.

javascript
import { createHash } from 'node:crypto'

const mailchimpBase = 'https://api.mailchimp.com/3.0'
const listId = process.env.MAILCHIMP_LIST_ID
const unchecked = { status: 'unchecked', reason: null, did_you_mean: null }
const sleep = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds))

export async function verifyEmail(email) {
  for (let attempt = 1; attempt <= 3; attempt += 1) {
    let response
    try {
      response = await fetch('https://api.qelka.com/v1/email', {
        method: 'POST',
        headers: {
          Authorization: `Bearer ${process.env.QELKA_API_KEY}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ email }),
        signal: AbortSignal.timeout(10000),
      })
    } catch (error) {
      console.warn(`email check skipped: ${error.name}`)
      return unchecked
    }

    if (response.ok) return response.json()

    if ([429, 500, 502, 503].includes(response.status) && attempt < 3) {
      const retryAfter = Number(response.headers.get('Retry-After'))
      await sleep((retryAfter > 0 ? Math.min(retryAfter, 5) : attempt) * 1000)
      continue
    }

    const failure = await response.json().catch(() => null)
    console.warn(`email check skipped: ${failure?.error?.type ?? response.status} request ${response.headers.get('X-Request-Id')}`)
    return unchecked
  }
}

async function mailchimp(method, path, body) {
  const response = await fetch(`${mailchimpBase}${path}`, {
    method,
    headers: {
      Authorization: `Bearer ${process.env.MAILCHIMP_API_KEY}`,
      'Content-Type': 'application/json',
    },
    body: body === undefined ? undefined : JSON.stringify(body),
    signal: AbortSignal.timeout(30000),
  })
  if (!response.ok) throw new Error(`Mailchimp ${method} ${path} answered ${response.status}: ${await response.text()}`)
  return response.status === 204 ? null : response.json()
}

export async function subscribe(rawEmail) {
  const email = rawEmail.trim()
  const result = await verifyEmail(email)

  if (result.status === 'undeliverable') {
    return { ok: false, suggestion: result.did_you_mean }
  }

  const subscriberHash = createHash('md5').update(email.toLowerCase()).digest('hex')
  await mailchimp('PUT', `/lists/${listId}/members/${subscriberHash}`, {
    email_address: email,
    status_if_new: 'pending',
  })
  await mailchimp('POST', `/lists/${listId}/members/${subscriberHash}/tags`, {
    tags: [{ name: `email-${result.status}`, status: 'active' }],
  })
  return { ok: true, suggestion: null }
}
  • The subscriber hash is the MD5 of the lowercase address, as Mailchimp's reference defines it. The PUT call creates the member or updates an existing one, so a repeated signup does not fail.
  • status_if_new: 'pending' makes Mailchimp send its opt-in confirmation. Use subscribed only if you collect consent another way.
  • The check runs in full mode, the default, with a 10-second timeout. If that is too long for your form, send mode: 'fast' at submit: it catches typos, dead domains and disposable inboxes without waiting for a mail server, and returns unknown with smtp_not_checked for the rest. The cleaning script below picks those up later.
  • When subscribe returns ok: false, show the form again with "Did you mean" and the suggestion when there is one.

The verification never blocks a signup on its own failure: a timeout, a network error or an API error ends as unchecked, the member is added and tagged email-unchecked, and the log line carries the error type and the request id.

2. Clean the members already in the audience

This script reads every subscribed member, verifies the addresses with batch calls of 100, tags each member with its result and, when you pass --archive, archives the undeliverable ones at the end.

javascript
const mailchimpBase = 'https://api.mailchimp.com/3.0'
const listId = process.env.MAILCHIMP_LIST_ID
const archive = process.argv.includes('--archive')
const chunkSize = 100
const sleep = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds))

async function mailchimp(method, path, body) {
  const response = await fetch(`${mailchimpBase}${path}`, {
    method,
    headers: {
      Authorization: `Bearer ${process.env.MAILCHIMP_API_KEY}`,
      'Content-Type': 'application/json',
    },
    body: body === undefined ? undefined : JSON.stringify(body),
    signal: AbortSignal.timeout(60000),
  })
  if (!response.ok) throw new Error(`Mailchimp ${method} ${path} answered ${response.status}: ${await response.text()}`)
  return response.status === 204 ? null : response.json()
}

async function listSubscribedMembers() {
  const members = []
  for (let offset = 0; ; offset += 1000) {
    const page = await mailchimp(
      'GET',
      `/lists/${listId}/members?status=subscribed&count=1000&offset=${offset}&fields=total_items,members.id,members.email_address`,
    )
    members.push(...page.members)
    if (page.members.length === 0 || members.length >= page.total_items) return members
  }
}

async function verifyBatch(emails) {
  for (let attempt = 1; ; attempt += 1) {
    const response = await fetch('https://api.qelka.com/v1/batch', {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${process.env.QELKA_API_KEY}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ items: emails.map((email) => ({ type: 'email', email })) }),
      signal: AbortSignal.timeout(120000),
    })
    if (response.ok) return (await response.json()).data

    if (![429, 500, 502, 503].includes(response.status) || attempt === 5) {
      const failure = await response.json().catch(() => null)
      throw new Error(`batch stopped: ${failure?.error?.type ?? response.status} request ${response.headers.get('X-Request-Id')}`)
    }
    const retryAfter = Number(response.headers.get('Retry-After'))
    await sleep(retryAfter > 0 ? retryAfter * 1000 : attempt * 2000)
  }
}

const members = await listSubscribedMembers()
const undeliverable = []
const counts = {}

for (let start = 0; start < members.length; start += chunkSize) {
  const chunk = members.slice(start, start + chunkSize)
  const results = await verifyBatch(chunk.map((member) => member.email_address))

  for (const [index, result] of results.entries()) {
    const member = chunk[index]
    const status = result.object === 'error' ? 'unchecked' : result.status
    counts[status] = (counts[status] ?? 0) + 1
    await mailchimp('POST', `/lists/${listId}/members/${member.id}/tags`, {
      tags: [{ name: `email-${status}`, status: 'active' }],
      is_syncing: true,
    })
    if (status === 'undeliverable') undeliverable.push(member.id)
  }
  console.log(`${Math.min(start + chunkSize, members.length)} of ${members.length}`, counts)
}

if (archive) {
  for (const id of undeliverable) await mailchimp('DELETE', `/lists/${listId}/members/${id}`)
  console.log(`archived ${undeliverable.length} undeliverable members`)
}

Run it with node clean-audience.mjs first, look at the counts and the tags in Mailchimp, then run it again with --archive if you agree with the result. A few details matter:

  • A member's id in the list response is already its subscriber hash, so the script uses it directly.
  • Archiving happens after the scan, not during it. Archived members leave the subscribed filter, and archiving while paging by offset would make the script skip members.
  • is_syncing: true keeps tag-triggered automations quiet during the clean-up.
  • The script stops on an error a retry cannot fix, such as 402 insufficient_credits or 401 invalid_api_key. Members tagged before the stop keep their tag.
  • Mailchimp limits each user to 10 simultaneous connections and times out calls after 120 seconds, by its documentation at the time of writing. The script makes one call at a time, so it stays well inside both.

For a large audience, exporting it and running a bulk file check of up to 2,000,000 rows is faster than one tag call per member: you then re-import the addresses with a tag, or archive the undeliverable ones from the result file.

3. Act on the tags

Build a segment on each tag and decide what to do with it:

Tag Meaning Suggested action
email-undeliverable Bad syntax, a domain that takes no mail, or a mailbox the server refused Archive. Never send to it again
email-risky A disposable inbox, a catch-all domain or a full mailbox Exclude disposable inboxes from campaigns. Send to catch-all addresses in a small, separate batch and watch the bounces. Re-check full mailboxes later
email-deliverable The mail server accepted the mailbox Keep sending
email-unknown The checks could not conclude: greylisting, a timeout, a provider that does not answer mailbox checks Keep. Re-check later; never delete on this result
email-unchecked The API was not reached Keep, and re-check

A tag cannot tell catch_all from disposable: if you need the difference, add the reason as a second tag, such as email-reason-disposable. An unknown address is not a bad address. See the email reference for each reason, and Clean an email list for the full decision table.

Handle errors and rate limits

Nothing is billed on errors. In the signup code, every API problem ends as unchecked and the signup goes through; in the script, 429 and server errors are retried after Retry-After, and anything else stops the run with the error type and the request id. 401 and 403 mean a wrong or restricted key, 402 an empty balance: see Errors. A key allows 200 requests per 10 seconds, and a batch counts as one request whatever its size: see Rate limits. If Mailchimp answers an error, the scripts throw with its status and body, so you see the problem instead of a silent skip.

Frequently asked questions

Should I archive or permanently delete undeliverable members?
Archive them. Mailchimp itself recommends archiving cleaned contacts rather than deleting them, because an archived address stays known to the audience and is less likely to come back in a later import and bounce again. Archiving is the DELETE call on the member; Mailchimp's permanent delete is a separate action that you cannot undo.
Will the tags trigger my Mailchimp automations?
The cleaning script sends is_syncing set to true with each tag, which Mailchimp documents as suppressing the automations those tags would trigger. The signup code does not, so a tag-based automation fires for new members as usual. Remove is_syncing from the script if you want automations to react to the clean-up.
How much does it cost to clean an audience?
Each member costs 1 credit, and a cached result costs the same as a fresh one. Errors are not billed, and neither are checks that could not finish, with the reason smtp_unavailable or dns_error. Run the script on a test audience with a sk_test_ key first, then on a segment, before the whole audience.

More in Marketing & email

All integrations

Put this check in your product

Get an API key in under a minute. 100 free credits every month, no card required.

  • 100 free credits a month
  • No card
  • Test keys spend nothing
  • Cancel any time