# Add email validation and verification to your app

> Add email validation and verification with ScreenlyyID: the instance call, the request, the response fields, the decision rule, working Node, Python and Next.js code, and a checklist.

Canonical URL: https://www.screenlyyid.com/docs/guides/email-validation/

## Summary

Email validation checks the address and its domain without contacting the mailbox. Email verification also asks the mail server whether the mailbox exists. Use validation to catch typos and throwaway addresses cheaply at sign-up, and verification when a bounce or a fake address costs you something.

## When to use it / when not to

**Use it for:**

- `email-validate`: a sign-up or newsletter form. It checks syntax, the domain and its mail servers, and flags disposable and free-mail addresses.
- `email-verify`: before you send something important, or when fake accounts are a problem. It does everything validation does and also reports the mail server's answer for the mailbox (`Verified`, `SmtpStatus`, `IsCatchAll`, `IsDeferred`).
- `batch-email-verify`: clean a list.

**Do not use it for:**

- Some mail servers accept every address (`IsCatchAll`) or delay their answer (`IsDeferred`). Neither check can prove a mailbox belongs to the person: send a confirmation email if that matters.
- You want to check a phone number: [Phone validation](https://www.screenlyyid.com/docs/guides/phone-validation/).

## Before you start

- **API key:** read it from the environment variable `SCREENLYYID_API_KEY` on your **server only**. Use a `test_` key for the sandbox and a `prod_` key for live. Never put it in browser or mobile code. See [Get a test key](https://www.screenlyyid.com/docs/ai-quickstart/#get-a-test-key).
- **Base URL:** `https://api.screenlyyid.com`. HTTPS only.
- **Activation and plan:** The email verification product (`emv`) must be activated on the account.
- **Start with the Instance API.** Every flow starts with `POST /api/v1/instance/create`, listing this product's code (`emv`) in `CustomerIntelligence`. It returns a `CorrelationId` that you send as `x-correlation-id` on the product call, along with `x-api-key`. A product call can be accepted only **once per correlation id**: repeating it with the same id can return `409 duplicate_correlation_id`. Create a new instance for each check (for example one per checkout or per sign-up).

```bash
curl --request POST --url 'https://api.screenlyyid.com/api/v1/instance/create' \
  --header "x-api-key: $SCREENLYYID_API_KEY" --header 'Content-Type: application/json' \
  --data '{"GlobalScreening": [], "CustomerIntelligence": ["emv"]}'
# { "CorrelationId": "...", "webEnrolmentUrl": "..." }   (webEnrolmentUrl is only used by the hosted identity verification flow)
```

## Use it on its own or stacked

This product can be called on its own (one instance with just `emv`, as above) or stacked with other products for the same customer: list several product codes in the one instance call and send the same `CorrelationId` on each product's call. See [Run several checks in one session](https://www.screenlyyid.com/docs/guides/stacking-checks/). Example pairing: BIN + IP + email at checkout (`CustomerIntelligence`: `["bin", "ipv", "emv"]`).

Document and selfie identity verification is **not** part of this product. It only goes through the Instance API and the hosted capture page: see [Identity verification (mobile)](https://www.screenlyyid.com/docs/guides/identity-verification-mobile/) and [Identity verification (web)](https://www.screenlyyid.com/docs/guides/identity-verification-web/). Do not use the direct identity verification endpoints.

## Implementation steps

1. **Create the instance** in your server code, right before the check. Keep the `CorrelationId` with your own record (the user, the order). Do this on the server.
2. **Call the endpoint** `POST /api/v1/email-verify` with `x-api-key`, `x-correlation-id` and a JSON body (next section). In a typical app this is the sign-up or form-submit handler, before you create the account.
3. **Read the response** and apply the [decision logic](https://www.screenlyyid.com/docs/guides/email-validation/#decision-logic): the fields marked ★ are the ones to base a decision on.
4. **Act on the result:** accept, ask the customer to correct their input, flag for review, or block. Store the `CorrelationId` and the outcome: it is your audit trail, and the same id shows the check in the dashboard.
5. **Handle failures** (below) so a provider outage never breaks your flow.

## Request and response

### Request
```json
{
  "Email": "jane.citizen@gmail.com",
  "FixTypos": true
}
```

| Field | Type | Meaning | Example |
|---|---|---|---|
| `Email` | string | The address to check. | someone@example.com |
| `FixTypos` | boolean | Try to correct common typos in the domain. Sent as `false` when omitted. | true |

`email-validate` (`POST /api/v1/email-validate`) takes the same body and returns the same fields except the mailbox ones (`Verified`, `SmtpStatus`, `SmtpResponse`). Switch `path` to `/email-validate` to use it.

### Response
```json
{
  "SmtpStatus": "ok",
  "DomainError": false,
  "Verified": true,
  "IsFreemail": true,
  "IsDisposable": false,
  "Valid": true,
  "IsCatchAll": false,
  "IsDeferred": false,
  "Provider": "gmail.com",
  "Domain": "gmail.com",
  "SmtpResponse": "250 2.1.5 OK ffacd0b85a97d-4ac085bb561si8007213f8f.119 - gsmtp",
  "SyntaxError": false,
  "Email": "jane.citizen@gmail.com",
  "IsPersonal": true
}
```

| Field | Type | Meaning | Example |
|---|---|---|---|
| `Valid` | boolean | ★ Address is syntactically valid and its domain can receive mail. | true |
| `SyntaxError` | boolean | ★ The address is malformed. | false |
| `DomainError` | boolean | ★ The domain does not exist or cannot receive mail. | false |
| `IsDisposable` | boolean | ★ A throwaway-address domain. | false |
| `Verified` | boolean | ★ (`email-verify` only) The mail server confirmed the mailbox. | true |
| `IsCatchAll` | boolean | (`email-verify`) The server accepts any address, so `Verified` proves little. | false |
| `IsDeferred` | boolean | (`email-verify`) The server did not answer yet. | false |
| `IsFreemail` | boolean | A free provider such as a webmail service. | false |
| `IsPersonal` | boolean | Looks like a personal rather than a role address. | true |
| `Email` | string | The address, possibly with typos fixed. | someone@example.com |

★ = base your decision on this field.

## Decision logic

1. `SyntaxError` or `DomainError` is `true`, or `Valid` is `false`: reject and ask the customer to correct it.
2. `IsDisposable` is `true`: block or require another address, according to your policy.
3. `email-verify` only: `Verified` is `true`: accept. `Verified` is `false` and the address is not `IsCatchAll` or `IsDeferred`: reject. Catch-all or deferred: accept, then confirm with an email.
4. Always use the `Email` returned: with `FixTypos` it may differ from what was typed. Ask the customer to confirm a corrected address.

```javascript
function emailDecision(e) {
  if (e.SyntaxError || e.DomainError || !e.Valid) return { action: "reject", reason: "invalid_email" };
  if (e.IsDisposable) return { action: "reject", reason: "disposable" };
  if (e.Verified === false && !e.IsCatchAll && !e.IsDeferred) return { action: "reject", reason: "mailbox_not_found" };
  return { action: "accept", email: e.Email, confirmByEmail: e.IsCatchAll || e.IsDeferred };
}
```

## Errors and limits

| Status | When | Body |
|---|---|---|
| `400` | A required field is missing or the body is not valid JSON | A problem-details object: `{"type": "...", "title": "One or more validation errors occurred.", "status": 400, "errors": {"<Field>": ["The <Field> field is required."]}}` |
| `401` | `x-api-key` is missing or malformed, or the product is not activated on the account | Empty body with a `WWW-Authenticate` header |
| `409` | The same `x-correlation-id` was already used for this product | `{"error": "duplicate_correlation_id", "message": "Duplicate correlation id received."}` |
| `500` | The upstream data provider failed | `{"error": "internal_error", "message": "An unexpected error occurred"}` |

No rate limit is documented. `email-verify` contacts a mail server and can be slow: use a 15 to 30 second timeout. Do not retry `4xx`; retry a `500` or timeout at most once.

## Batch

`POST /api/v1/batch-email-verify`: Verify many addresses in one request, for example to clean a mailing list.

```json
[{"Email": "someone@example.com", "FixTypos": true}, {"Email": "other@example.org", "FixTypos": true}]
```

The body is a JSON array of the same objects as `email-verify`. The ScreenlyyID API sets no maximum batch size in its code, so send modest chunks with a generous timeout, and do not use batch in a live sign-up path.

## Code

Minimal working server-side code. It creates the instance, makes the call with a timeout and throws on a non-`2xx` response with the status and error body attached. The key is read from `SCREENLYYID_API_KEY`.

### JavaScript (Node 18+, fetch)
```javascript
// server only: this reads your API key. Node 18 or later, no dependencies.
const API = "https://api.screenlyyid.com";
const apiKey = process.env.SCREENLYYID_API_KEY; // test_ while building, prod_ in production
if (!apiKey) throw new Error("SCREENLYYID_API_KEY is not set");

// Step 1: one instance per check. It lists this product's code and returns the CorrelationId.
export async function createInstance() {
  const r = await fetch(`${API}/api/v1/instance/create`, {
    method: "POST",
    headers: { "x-api-key": apiKey, "Content-Type": "application/json" },
    body: JSON.stringify({ GlobalScreening: [], CustomerIntelligence: ["emv"] }),
  });
  if (!r.ok) throw new Error(`instance/create failed (HTTP ${r.status})`);
  const { CorrelationId } = await r.json(); // spelled exactly like this
  return CorrelationId;
}

// Step 2: Email validation checks the address and its domain without contacting the mailbox
export async function verifyEmail(email) {
  const correlationId = await createInstance();
  const r = await fetch(`${API}/api/v1/email-verify`, {
    method: "POST",
    headers: { "x-api-key": apiKey, "x-correlation-id": correlationId, "Content-Type": "application/json" },
    body: JSON.stringify({ Email: email, FixTypos: true }),
    signal: AbortSignal.timeout(15000),
  });
  if (!r.ok) {
    const error = new Error(`/email-verify failed (HTTP ${r.status})`);
    error.status = r.status;
    error.body = await r.json().catch(() => null);
    throw error;
  }
  return { correlationId, result: await r.json() };
}
```

### Python (requests)
```python
# server only: this reads your API key. Python 3.9 or later, pip install requests
import os
import requests

API = "https://api.screenlyyid.com"
API_KEY = os.environ["SCREENLYYID_API_KEY"]  # test_ while building, prod_ in production


def create_instance():
    """Step 1: one instance per check. It lists this product's code and returns the CorrelationId."""
    r = requests.post(
        f"{API}/api/v1/instance/create",
        headers={"x-api-key": API_KEY},
        json={"GlobalScreening": [], "CustomerIntelligence": ["emv"]},
        timeout=15,
    )
    r.raise_for_status()
    return r.json()["CorrelationId"]  # spelled exactly like this


def verify_email(email):
    """Step 2: Email validation checks the address and its domain without contacting the mailbox"""
    correlation_id = create_instance()
    r = requests.post(
        f"{API}/api/v1/email-verify",
        headers={"x-api-key": API_KEY, "x-correlation-id": correlation_id},
        json={"Email": email, "FixTypos": True},
        timeout=15,
    )
    r.raise_for_status()  # a requests.HTTPError carries r.status_code and r.json() for the error body
    return correlation_id, r.json()
```

### Next.js route handler
```javascript
// app/api/verifyEmail/route.js (Next.js App Router). The key is read on the server only.
import { verifyEmail } from "@/lib/screenlyyid";

export const dynamic = "force-dynamic";

export async function POST(request) {
  const input = await request.json();
  try {
    const { result } = await verifyEmail(input);
    return Response.json(result); // send the browser only what it needs, never the API key or the CorrelationId
  } catch (e) {
    // a provider outage or timeout must not break your own flow: decide fail-open or fail-closed here
    return Response.json({ error: "check_unavailable", status: e.status ?? null }, { status: 502 });
  }
}
```

## Test it

The sandbox runs real checks, so there are no special test addresses: use addresses you control. `email-verify` and `email-validate` count as the same product (`emv`): after one of them, the other with the same `CorrelationId` returns `409 duplicate_correlation_id`, so use a new instance for each.

| Input | Expected result |
|---|---|
| jane.citizen@gmail.com | `email-verify`: `Valid` `true`, `Verified` `true`, `SmtpStatus` `ok`, `IsFreemail` `true`, `IsPersonal` `true`. `email-validate` returns the same without the mailbox fields, plus `DomainStatus` `ok` and `MxIpAddress`. |
| not-an-email | `200` with `SyntaxError` `true`, `Valid` `false`, `Verified` `false`, `SmtpStatus` `invalid`. |
| someone@example.com | `DomainError` `true`, `IsDisposable` `true`, `Valid` `false`: example domains are not deliverable. |

## Done when

- [ ] The API key is read only on the server
- [ ] A new instance is created per check and its `CorrelationId` is sent
- [ ] Invalid and disposable addresses are rejected with a message the customer can act on
- [ ] The returned `Email` (typo-fixed) is confirmed with the customer before it is stored
- [ ] Catch-all and deferred results trigger a confirmation email instead of a hard accept
- [ ] Errors and timeouts do not block sign-up

## Related

- [Email verification (API reference)](https://www.screenlyyid.com/docs/api-reference/email-verification/)
- [Instance API](https://www.screenlyyid.com/docs/authentication/create-instance/)
- [Stacking checks](https://www.screenlyyid.com/docs/guides/stacking-checks/)
