# Clean an email list

Sending to addresses that bounce hurts the reputation of your sending domain, and that reputation follows you to the next campaign. This guide cleans a list in four steps: prepare it, check it, sort the results, and come back for the addresses that could not be checked.

## 1. Prepare the list

- **Deduplicate.** Every row costs 1 credit, and a cached result costs the same as a fresh one. Ten copies of an address cost ten checks.
- **Trim the values** and lowercase the domain part. `Jane@Example.COM` and `Jane@example.com` reach the same mailbox: domain names are not case-sensitive.
- **Drop empty rows** and values longer than 320 characters: they are not email addresses.
- **Check only what you need.** If you plan a bulk job, upload the email column alone: the result file keeps every column you send, and files are stored for 30 days. Join the results back to your data afterwards.
- **Only check lists you have the right to use.** The [terms](/terms) exclude purchased and scraped lists.

## 2. Check the addresses

Two ways, depending on size:

| List size | Use | Why |
|---|---|---|
| Up to a few thousand addresses | [POST /batch](/docs/api-reference/batch) in chunks of 100 | Results come back as JSON in your script, no file handling |
| Larger lists, up to 2,000,000 rows | A [bulk job](/docs/api-reference/bulk) | Runs in the background, returns one result file |

Both cost the same: 1 credit per address. Use `full` mode, the default: a campaign needs to know whether mailboxes exist, not only whether domains do.

### Small lists: batch calls

This script reads `addresses.txt`, one address per line, and writes `addresses-checked.csv` with a decision for each address. It uses the [JavaScript SDK](/docs/sdk-js), which retries rate-limited calls on its own.

```javascript
import { readFile, writeFile } from 'node:fs/promises'
import { Client } from '@qelka/sdk'

const client = new Client({ apiKey: process.env.API_KEY })
const chunkSize = 100

const normalize = (address) => {
  const at = address.lastIndexOf('@')
  return at === -1 ? address : address.slice(0, at) + address.slice(at).toLowerCase()
}

const retryLater = new Set(['greylisted', 'smtp_timeout', 'smtp_unavailable', 'dns_error', 'mailbox_full'])

function decide(result) {
  if (result.object === 'error') return 'review'
  if (result.status === 'deliverable') return 'keep'
  if (result.status === 'undeliverable') return 'remove'
  if (result.reason === 'disposable') return 'remove'
  if (retryLater.has(result.reason)) return 'retry'
  return 'review'
}

const text = await readFile('addresses.txt', 'utf8')
const addresses = [
  ...new Set(
    text
      .split('\n')
      .map((line) => normalize(line.trim()))
      .filter((line) => line.length > 0 && line.length <= 320),
  ),
]

const rows = [['email', 'status', 'reason', 'decision']]
for (let start = 0; start < addresses.length; start += chunkSize) {
  const chunk = addresses.slice(start, start + chunkSize)
  const { data } = await client.batch(chunk.map((email) => ({ type: 'email', email })))
  data.forEach((result, index) => {
    rows.push([chunk[index], result.status ?? 'error', result.reason ?? result.error.type, decide(result)])
  })
  console.log(`${Math.min(start + chunkSize, addresses.length)} of ${addresses.length}`)
}

const cell = (value) => (/[",\n]/.test(value) ? `"${value.replaceAll('"', '""')}"` : value)
await writeFile('addresses-checked.csv', rows.map((row) => row.map(cell).join(',')).join('\n'))
```

A batch is synchronous, so each chunk takes as long as its slowest mailbox check. The script processes one chunk at a time, which keeps it far below the [rate limits](/docs/rate-limits).

The same loop in Python, with the `requests` library:

```python
import csv
import os

import requests

API = "https://api.qelka.com/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['API_KEY']}"}
RETRY_LATER = {"greylisted", "smtp_timeout", "smtp_unavailable", "dns_error", "mailbox_full"}


def normalize(address):
    local, at, domain = address.strip().rpartition("@")
    return f"{local}@{domain.lower()}" if at else address.strip()


def decide(result):
    if result["object"] == "error":
        return "review"
    if result["status"] == "deliverable":
        return "keep"
    if result["status"] == "undeliverable" or result["reason"] == "disposable":
        return "remove"
    return "retry" if result["reason"] in RETRY_LATER else "review"


with open("addresses.txt", encoding="utf-8") as source:
    addresses = sorted({normalize(line) for line in source if 0 < len(line.strip()) <= 320})

with open("addresses-checked.csv", "w", newline="", encoding="utf-8") as target:
    writer = csv.writer(target)
    writer.writerow(["email", "status", "reason", "decision"])
    for start in range(0, len(addresses), 100):
        chunk = addresses[start:start + 100]
        response = requests.post(
            f"{API}/batch",
            headers=HEADERS,
            json={"items": [{"type": "email", "email": email} for email in chunk]},
            timeout=120,
        )
        response.raise_for_status()
        for email, result in zip(chunk, response.json()["data"]):
            reason = result.get("reason") or result["error"]["type"]
            writer.writerow([email, result.get("status", "error"), reason, decide(result)])
```

### Large lists: a bulk job

Upload the file, wait for the job, download the results:

```bash
curl "https://api.qelka.com/v1/bulk?type=email&column=email" \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: text/csv" \
  --data-binary @emails.csv
```

The response is a `bulk_job` with its `id`. Creating it reserves 1 credit per row, and the credits that end up unused come back to your balance when the job ends. Follow the job with `GET /bulk/{id}`, or let the `bulk.completed` [webhook](/docs/webhooks) tell you when it is done:

```bash
curl https://api.qelka.com/v1/bulk/bulk_01M84BSX8MDFXRWMW580GKJWEY \
  -H "Authorization: Bearer $API_KEY"
```

When `status` is `completed`, download the file at `download_url`: a signed link that needs no API key. It keeps your columns and adds result columns, including `result_status`, `result_reason` and `result_error`; the [bulk reference](/docs/api-reference/bulk) lists them all and has a complete Node.js script. Bulk jobs need a live key.

This Python script splits the result file into one file per decision, using the decision table below:

```python
import csv

RETRY_LATER = {"greylisted", "smtp_timeout", "smtp_unavailable", "dns_error", "mailbox_full"}


def decide(row):
    if row["result_error"]:
        return "review"
    if row["result_status"] == "deliverable":
        return "keep"
    if row["result_status"] == "undeliverable" or row["result_reason"] == "disposable":
        return "remove"
    return "retry" if row["result_reason"] in RETRY_LATER else "review"


with open("emails-checked.csv", newline="", encoding="utf-8") as source:
    reader = csv.DictReader(source)
    fieldnames = reader.fieldnames
    rows = list(reader)

for decision in ("keep", "review", "retry", "remove"):
    selected = [row for row in rows if decide(row) == decision]
    with open(f"emails-{decision}.csv", "w", newline="", encoding="utf-8") as target:
        writer = csv.DictWriter(target, fieldnames=fieldnames)
        writer.writeheader()
        writer.writerows(selected)
    print(decision, len(selected))
```

The result file uses the delimiter of the file you uploaded. If that was a semicolon or a tab, pass `delimiter=";"` or `delimiter="\t"` to `csv.DictReader` and `csv.DictWriter`.

## 3. Sort the results

| Decision | `status` and `reason` | What to do |
|---|---|---|
| Keep | `deliverable` | Send. |
| Remove | `undeliverable`, any reason | Remove. These addresses will bounce, or the domain cannot receive mail at all. |
| Remove | `risky` with `disposable` | Remove from marketing lists: the inbox was meant to be thrown away. |
| Review | `risky` with `catch_all` | The domain accepts every address, so the mailbox could not be confirmed. Keep addresses you collected yourself and that engaged recently; send to the rest in a small, separate batch and watch the bounces. |
| Review | Rows with a `result_error` in a bulk file, or error items in a batch | The value could not be checked, often because the cell was empty or was not an email address. Look at them by hand. |
| Review | `unknown` with `provider_unverifiable` or `smtp_blocked` | The provider or server does not answer mailbox checks, and checking again is unlikely to change that. Treat them like catch-all addresses. |
| Retry | `unknown` with `greylisted`, `smtp_timeout`, `smtp_unavailable` or `dns_error` | Temporary. Check again later. |
| Retry | `risky` with `mailbox_full` | The mailbox exists but is over its quota. Check again later, and remove the address if it stays full. |

Role addresses, such as `info@` or `support@`, keep their status and have `checks.role: true`. They reach a team rather than a person, and they are often a poor fit for marketing email. Whether to drop them is your call.

## 4. Retry what could not be checked

Wait a few hours, then check the `retry` addresses again. Temporary results such as `greylisted` or `smtp_timeout` are not cached, so the new request runs the checks again. `"fresh": true` makes that explicit and also re-checks `mailbox_full` addresses, whose results are cached for 7 days.

```javascript
const { data } = await client.batch(
  retryAddresses.map((email) => ({ type: 'email', email, fresh: true })),
)
```

`retryAddresses` holds up to 100 addresses from the `retry` rows. An address whose check could not complete the first time (`smtp_unavailable` or `dns_error`) was not billed, so the retry is its only charge.

## Keep the list clean

- **Check at the point of collection.** [Validate signup forms](/docs/guides/validate-signup-forms) stops many bad addresses before they reach your list.
- **Re-check before a campaign to an old list.** Mailboxes get closed and domains expire.
- **Remove hard bounces** reported by your email provider, whatever the last check said.
