# Limpieza de listas por lotes

Un lote verifica una lista en segundo plano. Lo creas, esperas a que termine y descargas un resultado por fila.

## El flujo

1. `POST /batches` con una lista JSON o un fichero CSV. Responde `202` al instante con un lote en estado `queued`.
2. Espera: consulta `GET /batches/{batch_id}` o recibe el [webhook `batch.completed`](https://docs.salchimail.com/es/webhooks.md).
3. Descarga las filas de `GET /batches/{batch_id}/results`, en JSON o CSV.

**curl**

```bash
# 1. Create the batch. It answers 202 with the batch object.
curl https://api.salchimail.com/v1/batches \
  -H "Authorization: Bearer $SALCHIMAIL_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: 6f1c1c0e-6d1f-4f0e-9f58-0d6b0a1c2e3f" \
  -d '{"emails": ["ana@example.com", "luis@example.org", "not-an-email"], "mode": "mailbox", "name": "November newsletter"}'

# 2. Check the status until it is "completed" (use the id from step 1).
curl https://api.salchimail.com/v1/batches/bat_5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b \
  -H "Authorization: Bearer $SALCHIMAIL_API_KEY"

# 3. Read the results.
curl "https://api.salchimail.com/v1/batches/bat_5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b/results?limit=1000" \
  -H "Authorization: Bearer $SALCHIMAIL_API_KEY"
```

**JavaScript / TypeScript**

```js
const API = "https://api.salchimail.com/v1";

async function api(path, init = {}) {
  const response = await fetch(API + path, {
    ...init,
    headers: { Authorization: `Bearer ${process.env.SALCHIMAIL_API_KEY}`, ...init.headers },
  });
  const body = await response.json();
  if (!response.ok) throw new Error(`${body.error.code}: ${body.error.message}`);
  return body;
}

// 1. Create the batch. The Idempotency-Key makes a retry return the same batch.
let batch = await api("/batches", {
  method: "POST",
  headers: { "Content-Type": "application/json", "Idempotency-Key": crypto.randomUUID() },
  body: JSON.stringify({
    emails: ["ana@example.com", "luis@example.org", "not-an-email"],
    mode: "mailbox",
    name: "November newsletter",
  }),
});

// 2. Poll until it reaches a final status (or use the batch.completed webhook).
while (batch.status === "queued" || batch.status === "processing") {
  await new Promise((resolve) => setTimeout(resolve, 5000));
  batch = await api(`/batches/${batch.id}`);
}

// 3. Page through the results.
let cursor = null;
do {
  const query = new URLSearchParams({ limit: "1000", ...(cursor && { cursor }) });
  const page = await api(`/batches/${batch.id}/results?${query}`);
  for (const row of page.data) console.log(row.row, row.email, row.verdict);
  cursor = page.next_cursor;
} while (cursor);
```

**Python**

```python
import json
import os
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid

API = "https://api.salchimail.com/v1"


def api(method, path, body=None, headers=None):
    request = urllib.request.Request(API + path, method=method, headers=headers or {})
    request.add_header("Authorization", f"Bearer {os.environ['SALCHIMAIL_API_KEY']}")
    if body is not None:
        request.data = json.dumps(body).encode()
        request.add_header("Content-Type", "application/json")
    try:
        with urllib.request.urlopen(request, timeout=30) as response:
            return json.load(response)
    except urllib.error.HTTPError as error:
        problem = json.load(error)["error"]
        raise SystemExit(f"{problem['code']}: {problem['message']}")


# 1. Create the batch. The Idempotency-Key makes a retry return the same batch.
batch = api(
    "POST",
    "/batches",
    {
        "emails": ["ana@example.com", "luis@example.org", "not-an-email"],
        "mode": "mailbox",
        "name": "November newsletter",
    },
    {"Idempotency-Key": str(uuid.uuid4())},
)

# 2. Poll until it reaches a final status (or use the batch.completed webhook).
while batch["status"] in ("queued", "processing"):
    time.sleep(5)
    batch = api("GET", f"/batches/{batch['id']}")

# 3. Page through the results.
query = {"limit": 1000}
while True:
    page = api("GET", f"/batches/{batch['id']}/results?{urllib.parse.urlencode(query)}")
    for row in page["data"]:
        print(row["row"], row["email"], row["verdict"])
    if not page["next_cursor"]:
        break
    query["cursor"] = page["next_cursor"]
```

**PHP**

```php
<?php
const API = "https://api.salchimail.com/v1";

function api(string $method, string $path, ?array $body = null, array $headers = []): array
{
    $headers[] = "Authorization: Bearer " . getenv("SALCHIMAIL_API_KEY");
    $ch = curl_init(API . $path);
    curl_setopt_array($ch, [CURLOPT_CUSTOMREQUEST => $method, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30]);
    if ($body !== null) {
        $headers[] = "Content-Type: application/json";
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
    }
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    $raw = curl_exec($ch);
    if ($raw === false) {
        throw new RuntimeException(curl_error($ch));
    }
    $data = json_decode($raw, true);
    if (curl_getinfo($ch, CURLINFO_HTTP_CODE) >= 400) {
        throw new RuntimeException("{$data['error']['code']}: {$data['error']['message']}");
    }
    return $data;
}

// 1. Create the batch. The Idempotency-Key makes a retry return the same batch.
$batch = api("POST", "/batches", [
    "emails" => ["ana@example.com", "luis@example.org", "not-an-email"],
    "mode" => "mailbox",
    "name" => "November newsletter",
], ["Idempotency-Key: " . bin2hex(random_bytes(16))]);

// 2. Poll until it reaches a final status (or use the batch.completed webhook).
while (in_array($batch["status"], ["queued", "processing"], true)) {
    sleep(5);
    $batch = api("GET", "/batches/{$batch['id']}");
}

// 3. Page through the results.
$query = ["limit" => 1000];
do {
    $page = api("GET", "/batches/{$batch['id']}/results?" . http_build_query($query));
    foreach ($page["data"] as $row) {
        echo "{$row['row']} {$row['email']} {$row['verdict']}\n";
    }
    $query["cursor"] = $page["next_cursor"];
} while ($page["next_cursor"]);
```

**Go**

```go
package main

import (
	"bytes"
	"crypto/rand"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"net/url"
	"os"
	"time"
)

const api = "https://api.salchimail.com/v1"

type batch struct {
	ID     string `json:"id"`
	Status string `json:"status"`
}

type resultPage struct {
	Data []struct {
		Row     int    `json:"row"`
		Email   string `json:"email"`
		Verdict string `json:"verdict"`
	} `json:"data"`
	NextCursor *string `json:"next_cursor"`
}

type apiError struct {
	Error struct {
		Code    string `json:"code"`
		Message string `json:"message"`
	} `json:"error"`
}

var client = &http.Client{Timeout: 30 * time.Second}

// call sends one request and decodes the JSON answer into out.
func call(method, path string, body any, idempotencyKey string, out any) error {
	var payload bytes.Buffer
	if body != nil {
		if err := json.NewEncoder(&payload).Encode(body); err != nil {
			return err
		}
	}
	req, err := http.NewRequest(method, api+path, &payload)
	if err != nil {
		return err
	}
	req.Header.Set("Authorization", "Bearer "+os.Getenv("SALCHIMAIL_API_KEY"))
	if body != nil {
		req.Header.Set("Content-Type", "application/json")
	}
	if idempotencyKey != "" {
		req.Header.Set("Idempotency-Key", idempotencyKey)
	}
	res, err := client.Do(req)
	if err != nil {
		return err
	}
	defer res.Body.Close()
	if res.StatusCode >= 400 {
		var e apiError
		if err := json.NewDecoder(res.Body).Decode(&e); err != nil {
			return fmt.Errorf("HTTP %d", res.StatusCode)
		}
		return fmt.Errorf("%s: %s", e.Error.Code, e.Error.Message)
	}
	return json.NewDecoder(res.Body).Decode(out)
}

func main() {
	// 1. Create the batch. The Idempotency-Key makes a retry return the same batch.
	var b batch
	request := map[string]any{
		"emails": []string{"ana@example.com", "luis@example.org", "not-an-email"},
		"mode":   "mailbox",
		"name":   "November newsletter",
	}
	if err := call("POST", "/batches", request, rand.Text(), &b); err != nil {
		log.Fatal(err)
	}

	// 2. Poll until it reaches a final status (or use the batch.completed webhook).
	for b.Status == "queued" || b.Status == "processing" {
		time.Sleep(5 * time.Second)
		if err := call("GET", "/batches/"+b.ID, nil, "", &b); err != nil {
			log.Fatal(err)
		}
	}

	// 3. Page through the results.
	query := url.Values{"limit": {"1000"}}
	for {
		var page resultPage
		if err := call("GET", "/batches/"+b.ID+"/results?"+query.Encode(), nil, "", &page); err != nil {
			log.Fatal(err)
		}
		for _, r := range page.Data {
			fmt.Println(r.Row, r.Email, r.Verdict)
		}
		if page.NextCursor == nil {
			break
		}
		query.Set("cursor", *page.NextCursor)
	}
}
```

## Crear un lote desde JSON

Envía hasta 10.000 direcciones en `emails`. `mode` es `basic` salvo que indiques otro, y `name` es una etiqueta opcional que se muestra en el panel.

```json
{
  "emails": [
    "ana@example.com",
    "luis@example.org",
    "not-an-email"
  ],
  "mode": "mailbox",
  "name": "November newsletter"
}
```

La respuesta es el lote nuevo, anunciado también en la cabecera `Location`:

```json
{
  "id": "bat_5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b",
  "object": "batch",
  "livemode": true,
  "name": "November newsletter",
  "source": "json",
  "mode": "mailbox",
  "status": "queued",
  "total": 3,
  "unique": 3,
  "processed": 0,
  "summary": {
    "valid": 0,
    "invalid": 0,
    "risky": 0,
    "unknown": 0
  },
  "credits": {
    "type": "mailbox",
    "reserved": 3,
    "charged": 0
  },
  "created_at": "2026-11-17T09:50:00Z",
  "started_at": null,
  "finished_at": null,
  "deadline_at": null,
  "results_expire_at": null
}
```

## Crear un lote desde CSV

Sube el fichero como `multipart/form-data`:

```bash
curl https://api.salchimail.com/v1/batches \
  -H "Authorization: Bearer $SALCHIMAIL_API_KEY" \
  -H "Idempotency-Key: 6f1c1c0e-6d1f-4f0e-9f58-0d6b0a1c2e3f" \
  -F "file=@contacts.csv;type=text/csv" \
  -F "mode=mailbox" \
  -F "email_column=email" \
  -F "delimiter=comma" \
  -F "name=November newsletter"
```

| Campo | Obligatorio | Por defecto | Descripción |
| --- | --- | --- | --- |
| `file` | Sí | | CSV en UTF-8 con fila de cabecera. Hasta 10 MB y 100.000 filas de datos |
| `email_column` | No | `email` | Nombre exacto de la cabecera que contiene las direcciones |
| `delimiter` | No | `comma` | `comma`, `semicolon` o `tab` |
| `mode` | No | `basic` | `basic` o `mailbox` |
| `name` | No | | Etiqueta que se muestra en el panel, hasta 120 caracteres |

Solo se guarda la columna del email: el resto de columnas se descarta al subir el fichero. Cruza los resultados con tu fichero por `row`, el número de fila de datos sin contar la cabecera.

## Seguir el progreso

```bash
curl https://api.salchimail.com/v1/batches/bat_5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b \
  -H "Authorization: Bearer $SALCHIMAIL_API_KEY"
```

```json
{
  "id": "bat_5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b",
  "object": "batch",
  "livemode": true,
  "name": "November newsletter",
  "source": "json",
  "mode": "mailbox",
  "status": "processing",
  "total": 3,
  "unique": 3,
  "processed": 2,
  "summary": {
    "valid": 1,
    "invalid": 1,
    "risky": 0,
    "unknown": 0
  },
  "credits": {
    "type": "mailbox",
    "reserved": 1,
    "charged": 2
  },
  "created_at": "2026-11-17T09:50:00Z",
  "started_at": "2026-11-17T09:50:02Z",
  "finished_at": null,
  "deadline_at": "2026-11-23T09:50:02Z",
  "results_expire_at": null
}
```

| Campo | Significado |
| --- | --- |
| `status` | `queued` → `processing` → `completed`. También `canceled`, y `failed` si hay un error interno |
| `total` | Filas aceptadas, duplicados incluidos |
| `unique` | Direcciones distintas tras normalizar |
| `processed` | Filas que ya tienen un resultado final |
| `summary` | Resultados finales hasta el momento, por veredicto |
| `credits` | `reserved` para las filas pendientes y `charged` hasta el momento |

Consulta como mucho cada pocos segundos. Para no tener que consultar, suscríbete al [webhook `batch.completed`](https://docs.salchimail.com/es/webhooks.md). `GET /batches` lista tus lotes, del más reciente al más antiguo.

## Descargar los resultados

Los resultados vienen ordenados por `row`. Cada uno es una [verificación](https://docs.salchimail.com/es/veredictos.md) con tres campos más: `row`, `input` (el valor tal como lo enviaste) y `duplicate`.

```json
{
  "object": "list",
  "data": [
    {
      "row": 1,
      "input": "Ana@Example.com",
      "duplicate": false,
      "id": "ver_8c1d2e3f4a5b6c7d8e9f0a1b2c3d4e5f",
      "object": "verification",
      "livemode": true,
      "email": "ana@example.com",
      "mode": "mailbox",
      "verdict": "valid",
      "reason_code": "mailbox_exists",
      "reason": "The mail server accepts this recipient and rejects a random one.",
      "flags": {
        "disposable": false,
        "free": false,
        "catch_all": false
      },
      "checks": [
        {
          "name": "syntax",
          "status": "ok"
        },
        {
          "name": "dns",
          "status": "mx"
        },
        {
          "name": "smtp",
          "status": "accepted"
        },
        {
          "name": "catch_all",
          "status": "missing"
        }
      ],
      "mx": [
        {
          "host": "mx1.example.com",
          "preference": 10
        }
      ],
      "smtp": {
        "mx": "mx1.example.com",
        "code": 250,
        "enhanced_code": null,
        "tls": true
      },
      "cached": false,
      "credits_charged": 1,
      "checked_at": "2026-11-17T09:50:04Z",
      "retry_at": null
    },
    {
      "row": 3,
      "input": "not-an-email",
      "duplicate": false,
      "id": "ver_1b2c3d4e5f60718293a4b5c6d7e8f9a0",
      "object": "verification",
      "livemode": true,
      "email": "not-an-email",
      "mode": "mailbox",
      "verdict": "invalid",
      "reason_code": "syntax_invalid",
      "reason": "The address is not a valid email.",
      "flags": {
        "disposable": false,
        "free": false,
        "catch_all": null
      },
      "checks": [
        {
          "name": "syntax",
          "status": "invalid"
        }
      ],
      "mx": [],
      "smtp": null,
      "cached": false,
      "credits_charged": 1,
      "checked_at": "2026-11-17T09:50:02Z",
      "retry_at": null
    }
  ],
  "has_more": true,
  "next_cursor": "eyJyb3ciOjN9"
}
```

Las páginas traen 100 filas salvo que indiques `limit` (hasta 1.000 en JSON). Mientras `has_more` sea `true`, pide la página siguiente con `cursor=<next_cursor>`. Añade `verdict=valid` (o `invalid`, `risky`, `unknown`) para recibir solo esas filas.

### En CSV

```bash
curl "https://api.salchimail.com/v1/batches/bat_5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b/results?format=csv&limit=10000" \
  -H "Authorization: Bearer $SALCHIMAIL_API_KEY" \
  -D headers.txt -o results.csv
```

```csv
row,input,email,verdict,reason_code,disposable,free,catch_all,credits_charged,checked_at
1,Ana@Example.com,ana@example.com,valid,mailbox_exists,false,false,false,1,2026-11-17T09:50:04Z
3,not-an-email,not-an-email,invalid,syntax_invalid,false,false,,1,2026-11-17T09:50:02Z
```

Una página CSV trae hasta 10.000 filas. Cuando hay más, la respuesta incluye una cabecera `Link` con la página siguiente (`rel="next"`). En la última página la cabecera no aparece.

Solo se listan las filas con resultado final, así que las páginas pedidas mientras el lote está en `processing` son parciales. Espera a un estado final antes de hacer una exportación completa.

## Cuánto tarda un lote

| Fase | Plazo |
| --- | --- |
| Creación | `202` al instante. El lote empieza en `queued` |
| Lote `basic` | No se contacta con ningún servidor de correo |
| Lote `mailbox` | Respeta cuotas de sondeo por dominio y por servidor de correo, y reintenta las direcciones aplazadas. Una lista grande concentrada en pocos dominios puede tardar horas o días |
| Fecha límite | `deadline_at`, 6 días después de que empiece el lote. Las filas sin resolver terminan como `unknown` y **no se cobran** |
| Resultados disponibles | Hasta `results_expire_at`, 30 días después de terminar el lote. Después, el endpoint de resultados responde `404` |
| Modo de pruebas | Los lotes creados con una clave `sk_test_` terminan en segundos |

SalchiMail nunca rota direcciones IP ni esquiva los límites de un servidor de correo para ir más rápido, así que el ritmo de un lote `mailbox` depende de los servidores que hay detrás de tu lista.

## Créditos en un lote

- Al crear el lote se reservan créditos para cada dirección **única**. Si el saldo no llega, la petición responde `402 insufficient_credits` y no se crea nada.
- Cada fila se cobra cuando alcanza un resultado final, con las mismas reglas que una verificación individual. En modo `mailbox`, las filas `unknown` son gratis.
- Las direcciones duplicadas se verifican una vez y se cobran una vez. Las filas repetidas vuelven con `"duplicate": true`.
- Los créditos no usados se devuelven cuando el lote termina o se cancela.

Consulta [Créditos y facturación](https://docs.salchimail.com/es/creditos.md).

## Cancelar un lote

```bash
curl -X POST https://api.salchimail.com/v1/batches/bat_5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b/cancel \
  -H "Authorization: Bearer $SALCHIMAIL_API_KEY"
```

Cancelar detiene un lote en `queued` o `processing`. Los resultados ya producidos siguen disponibles y cobrados, y los créditos reservados para el resto se devuelven. Las filas que no llegaron a procesarse no aparecen en los resultados. Un lote `completed` o `failed` responde `409 batch_not_cancelable`.

## Límites y errores

| Límite | Valor |
| --- | --- |
| Direcciones en un lote JSON | 10.000 |
| Cuerpo JSON | 2 MB |
| Fichero CSV | 10 MB y 100.000 filas de datos |
| Tu plan | `limits.max_batch_size` y `limits.max_concurrent_batches` en `GET /account` |

| HTTP | `code` | Significado |
| --- | --- | --- |
| 400 | `batch_empty` | La lista o el fichero no tienen direcciones |
| 400 | `batch_too_large` | Más filas de las que tu plan acepta en un lote |
| 400 | `csv_invalid` | El fichero no es un CSV legible en UTF-8 con fila de cabecera |
| 400 | `csv_column_not_found` | Ninguna cabecera coincide exactamente con `email_column` |
| 402 | `insufficient_credits` | No hay créditos suficientes para reservar el lote |
| 413 | `payload_too_large` | El cuerpo supera 2 MB (JSON) o 10 MB (CSV). Divide la lista |
| 429 | `concurrent_batches_exceeded` | Demasiados lotes en `queued` o `processing` a la vez. Espera a que termine uno |

Envía siempre una [`Idempotency-Key`](https://docs.salchimail.com/es/idempotencia.md) al crear un lote: así, un reintento tras un error de red devuelve el mismo lote en lugar de crear otro y reservar sus créditos.
