# Determinare il genere da un indirizzo email

> Usa l'indizio di nome contenuto in un indirizzo email con GenderAPI.io V2. Prova una richiesta in tempo reale, confronta le opzioni tra set di dati e IA e scopri come gestire i risultati sconosciuti e gli elenchi di indirizzi email.

Canonical HTML: https://www.genderapi.io/it/determine-gender-from-email

Last reviewed: 2026-09-28

## Che cosa dice un indirizzo email?

Invia un indirizzo email sintatticamente valido con type: email. GenderAPI.io cerca un indizio di nome nella parte prima della @ e restituisce poi una previsione strutturata. La casella di posta non viene verificata, non viene collegata a un titolare e l'identità di genere del titolare non viene stabilita.

La corrispondenza con il set di dati ricava i candidati dalle parti dell'indirizzo e può controllare sottostringhe limitate. La modalità nickname mantiene la corrispondenza su parti intere ma non aggiunge questi candidati basati su sottostringhe. Se più voci corrispondono, viene scelto il candidato con il conteggio totale memorizzato più alto, che non è necessariamente il nome proprio previsto. Verifica data.name e data.match prima di usare un nome estratto in un'anagrafica di contatti.

| Esempio di input | Interpretazione |
| --- | --- |
| `alice.smith@example.com` | La parte locale contiene possibili parti di un nome. Una corrispondenza è possibile, ma l'input da solo non determina quale candidato viene scelto. |
| `alice+news@example.com` | La ricerca nel set di dati rimuove il suffisso dopo il segno più per i propri candidati. All'IA viene chiesto di ignorarlo, ma riceve il valore inviato. |
| `support@example.com` | Un indirizzo di ruolo non fornisce un indizio affidabile di un nome di persona. Non attribuire all'intera casella condivisa il genere di una persona. |
| `prenses@example.com` | L'opzione facoltativa forceToGenderize consente un tentativo basato sul significato di un nickname quando il set di dati non dà un risultato. In questa modalità non serve un vero nome. |
| `not-an-email` | Una sintassi non valida restituisce un errore di convalida invece di un risultato sconosciuto riuscito. |

## Inviare una richiesta per un indirizzo email dalla tua applicazione

L'esempio usa la tua chiave API esistente nell'intestazione Bearer e indica fallback in modo esplicito. Sostituisci l'indirizzo di esempio con un input che hai il diritto di trattare. Indica country solo se disponi di un contesto pertinente; il dominio email non mostra dove si trova una persona. Senza contesto del paese, ometti il campo.

Esegui l'esempio sul tuo server dopo aver impostato GENDERAPI_API_KEY. Con POST l'indirizzo email resta fuori dall'URL della richiesta. Il risultato in tempo reale può essere diverso dalla risposta di esempio della demo.

Esegui questi esempi sul tuo server. Imposta GENDERAPI_API_KEY nell'ambiente del processo con la tua chiave API esistente. Verifica che meta.access.mode sia api_key: una chiave non riconosciuta può portare alla prova IP.

Ogni richiesta di previsione è una nuova operazione a pagamento, anche quando è un nuovo tentativo. Questi esempi non riprovano automaticamente. Controlla lo stato dell'addebito prima di inviare un'altra richiesta.

Per le risposte JSON con HTTP 4xx e 5xx, il corpo dell'errore viene conservato e l'esempio termina con un codice di uscita diverso da zero. Controlla code, action e meta.usage.billing_status prima di riprovare.

**cURL**

cURL 7.76+ in una shell POSIX. Esegui nel terminale.

```bash
curl --silent --show-error --fail-with-body --max-time 30 \
  --request POST 'https://api.genderapi.io/api/v2/gender' \
  --header "Authorization: Bearer ${GENDERAPI_API_KEY:?Set GENDERAPI_API_KEY}" \
  --header 'Content-Type: application/json' \
  --data '{
  "type": "email",
  "value": "alice.smith@example.com",
  "country": "US",
  "options": {
    "ai_mode": "fallback"
  }
}'
```

**JavaScript / Node.js**

Node.js 22+; fetch integrato. Salva come example.mjs ed esegui node example.mjs.

```javascript
// Server-side Node.js. Save as example.mjs.
const apiKey = process.env.GENDERAPI_API_KEY;
if (!apiKey) throw new Error("Set GENDERAPI_API_KEY");
const body = {
  "type": "email",
  "value": "alice.smith@example.com",
  "country": "US",
  "options": {
    "ai_mode": "fallback"
  }
};

const response = await fetch("https://api.genderapi.io/api/v2/gender", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${apiKey}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify(body),
  signal: AbortSignal.timeout(30_000),
  redirect: "error",
});
const raw = await response.text();
if (!(response.headers.get("content-type") ?? "").includes("json")) {
  throw new Error(`HTTP ${response.status}: expected JSON; request ID ${response.headers.get("x-request-id")}`);
}
const result = JSON.parse(raw); // Also accepts application/problem+json.
if (!response.ok) {
  console.error(`HTTP ${response.status}`, result);
  process.exitCode = 1; // A retry is a new operation; inspect billing first.
} else {
  console.log(JSON.stringify(result, null, 2));
  // For batches, inspect every item: HTTP 200 may contain item errors.
}
```

**Python**

Python 3.10+; libreria standard. Salva come example.py ed esegui python3 example.py.

```python
import json
import os
import sys
import urllib.error
import urllib.request

api_key = os.environ.get("GENDERAPI_API_KEY")
if not api_key:
    raise RuntimeError("Set GENDERAPI_API_KEY")
body = json.loads("{\"type\":\"email\",\"value\":\"alice.smith@example.com\",\"country\":\"US\",\"options\":{\"ai_mode\":\"fallback\"}}")

class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None

request = urllib.request.Request(
    "https://api.genderapi.io/api/v2/gender",
    method="POST",
    data=json.dumps(body).encode("utf-8"),
    headers={
        "Authorization": "Bearer " + api_key,
        "Content-Type": "application/json",
    },
)
opener = urllib.request.build_opener(NoRedirect())
try:
    response = opener.open(request, timeout=30)
except urllib.error.HTTPError as error:
    response = error  # Keep the Problem Details body on non-2xx responses.
with response:
    status = response.status
    raw = response.read().decode("utf-8")
    if "json" not in response.headers.get("Content-Type", ""):
        raise RuntimeError(f"HTTP {status}: expected a JSON response")
    result = json.loads(raw)
print(json.dumps(result, indent=2), file=sys.stderr if status >= 300 else sys.stdout)
if not 200 <= status < 300:
    sys.exit(1)  # Inspect code, action and billing before retrying.
# For batches, inspect every item even when HTTP status is 200.
```

**PHP**

PHP 8+ con l'estensione cURL. Salva come example.php ed esegui php example.php.

```php
<?php
$apiKey = getenv('GENDERAPI_API_KEY');
if (!$apiKey) {
    throw new RuntimeException('Set GENDERAPI_API_KEY');
}
$body = json_decode('{"type":"email","value":"alice.smith@example.com","country":"US","options":{"ai_mode":"fallback"}}', true, 512, JSON_THROW_ON_ERROR);

$ch = curl_init('https://api.genderapi.io/api/v2/gender');
curl_setopt_array($ch, [
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => false,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . $apiKey,
        'Content-Type: application/json',
    ],
    CURLOPT_POSTFIELDS => json_encode($body, JSON_THROW_ON_ERROR),
]);
$raw = curl_exec($ch);
if ($raw === false) {
    throw new RuntimeException(curl_error($ch));
}
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE) ?: '';
curl_close($ch);
if (strpos($contentType, 'json') === false) {
    throw new RuntimeException("HTTP $status: expected a JSON response");
}
$result = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
$output = json_encode($result, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR) . PHP_EOL;
if ($status < 200 || $status >= 300) {
    fwrite(STDERR, $output); // Preserve the Problem Details body.
    exit(1);
}
echo $output;
// For batches, inspect every item; HTTP 200 can contain item errors.
```

**Java**

Java 17+; client HTTP standard. Salva come GenderApiExample.java ed esegui java GenderApiExample.java.

```java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;

public class GenderApiExample {
    private static String requiredEnv(String name) {
        String value = System.getenv(name);
        if (value == null || value.isBlank()) throw new IllegalStateException("Set " + name);
        return value;
    }

    public static void main(String[] args) throws Exception {
        String apiKey = requiredEnv("GENDERAPI_API_KEY");
        String body = "{\"type\":\"email\",\"value\":\"alice.smith@example.com\",\"country\":\"US\",\"options\":{\"ai_mode\":\"fallback\"}}";
        HttpClient client = HttpClient.newBuilder()
            .connectTimeout(Duration.ofSeconds(10))
            .followRedirects(HttpClient.Redirect.NEVER)
            .build();
        HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.genderapi.io/api/v2/gender"))
            .timeout(Duration.ofSeconds(30))
            .header("Authorization", "Bearer " + apiKey)
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(body, StandardCharsets.UTF_8))
            .build();
        HttpResponse<String> response = client.send(request,
            HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
        if (!response.headers().firstValue("content-type").orElse("").contains("json")) {
            throw new IllegalStateException("HTTP " + response.statusCode() + ": expected JSON");
        }
        // JSON text; parse with your application's JSON library when integrating.
        if (response.statusCode() < 200 || response.statusCode() >= 300) {
            System.err.println(response.body()); // Includes Problem Details.
            System.exit(1);
        }
        System.out.println(response.body());
        // For batches, inspect each item's data or error, including on HTTP 200.
    }
}
```

**C# / .NET**

Applicazione console .NET 8+. Usalo come Program.cs in un progetto console, poi esegui dotnet run.

```csharp
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;

string RequiredEnv(string name) =>
    !string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable(name))
        ? Environment.GetEnvironmentVariable(name)!
        : throw new InvalidOperationException($"Set {name}");

var apiKey = RequiredEnv("GENDERAPI_API_KEY");
using var handler = new HttpClientHandler { AllowAutoRedirect = false };
using var client = new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(30) };
using var request = new HttpRequestMessage(HttpMethod.Post, "https://api.genderapi.io/api/v2/gender");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
request.Content = new StringContent("{\"type\":\"email\",\"value\":\"alice.smith@example.com\",\"country\":\"US\",\"options\":{\"ai_mode\":\"fallback\"}}", Encoding.UTF8, "application/json");

using var response = await client.SendAsync(request);
var raw = await response.Content.ReadAsStringAsync();
if (!(response.Content.Headers.ContentType?.MediaType?.Contains("json") ?? false))
    throw new InvalidOperationException($"HTTP {(int)response.StatusCode}: expected JSON");
using var result = JsonDocument.Parse(raw);
if (!response.IsSuccessStatusCode)
{
    Console.Error.WriteLine(result.RootElement); // Preserve Problem Details.
    Environment.ExitCode = 1;
}
else
{
    Console.WriteLine(result.RootElement);
    // For batches, inspect every item even on HTTP 200.
}
```

**Go**

Go 1.22+; libreria standard. Salva come main.go ed esegui go run main.go.

```go
package main

import (
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "os"
    "strings"
    "time"
)

func requiredEnv(name string) string {
    value := os.Getenv(name)
    if value == "" { panic("Set " + name) }
    return value
}

func run() error {
    apiKey := requiredEnv("GENDERAPI_API_KEY")
    body := "{\"type\":\"email\",\"value\":\"alice.smith@example.com\",\"country\":\"US\",\"options\":{\"ai_mode\":\"fallback\"}}"
    request, err := http.NewRequest("POST", "https://api.genderapi.io/api/v2/gender", strings.NewReader(body))
    if err != nil { return err }
    request.Header.Set("Authorization", "Bearer " + apiKey)
    request.Header.Set("Content-Type", "application/json")
    client := &http.Client{
        Timeout: 30 * time.Second,
        CheckRedirect: func(req *http.Request, via []*http.Request) error {
            return http.ErrUseLastResponse
        },
    }
    response, err := client.Do(request)
    if err != nil { return err }
    defer response.Body.Close()
    raw, err := io.ReadAll(response.Body)
    if err != nil { return err }
    if !strings.Contains(response.Header.Get("Content-Type"), "json") || !json.Valid(raw) {
        return fmt.Errorf("HTTP %d: expected a JSON response", response.StatusCode)
    }
    if response.StatusCode < 200 || response.StatusCode >= 300 {
        return fmt.Errorf("HTTP %d: %s", response.StatusCode, raw)
    }
    fmt.Println(string(raw))
    // For batches, inspect every item even on HTTP 200.
    return nil
}

func main() {
    if err := run(); err != nil {
        fmt.Fprintln(os.Stderr, err) // Keep Problem Details for error handling.
        os.Exit(1)
    }
}
```

- [Riferimento V2 completo per gli indirizzi email](https://www.genderapi.io/it/docs/v2/gender-from-email)

## Salvare il risultato insieme alle evidenze

Un'associazione dedotta non è il genere dichiarato da una persona. Salva separatamente l'input originale, le evidenze restituite e ciò che la persona ha dichiarato. Un risultato sconosciuto è un risultato valido e non dovrebbe diventare una categoria indovinata nella tua applicazione.

| Campo | Utilizzo |
| --- | --- |
| `data.gender / data.result_status` | Usa male o female solo con identified. In caso di risultato sconosciuto conserva il valore JSON null nativo. |
| `data.name / data.match` | Verifica il nome restituito e il candidato selezionato. Una corrispondenza su una sottostringa non dimostra che l'input appartenga a una persona con quel nome. |
| `data.confidence / data.confidence_kind` | La confidenza è su una scala da 0 a 1 oppure è null. observed_frequency si basa su frequenze memorizzate; model_reported è un valore fornito dall'IA. Valuta le soglie separatamente per ciascun tipo. |
| `data.source / data.sample_count` | Distingui tra dataset, ai e none. I risultati dell'IA non hanno una dimensione del campione memorizzata. Una dimensione del campione non è un valore di accuratezza misurato. |
| `meta.access.mode` | In un'integrazione con account verifica che venga riportato api_key. Le chiavi mancanti o non riconosciute possono invece usare la prova IP condivisa. |
| `meta.usage` | Leggi charged_credits e billing_status. Un risultato sconosciuto riuscito viene addebitato. Una risposta persa non dimostra che la richiesta sia stata gratuita. |

- [Campi della risposta e risultati sconosciuti](https://www.genderapi.io/it/docs/v2/responses)
- [Accuratezza e confidenza spiegate](https://www.genderapi.io/it/accuracy-methodology)
- [Fonti dei dati e profilo datato del database](https://www.genderapi.io/it/data-provenance)

## Decidere quando usare l'IA

forceToGenderize è facoltativo per nomi, indirizzi email e nomi utente. Quando è attivo, ometti ai_mode o usa fallback; off e always non possono essere combinati con questa opzione e restituiscono 422. Un saldo iniziale positivo basta per avviare una richiesta, anche se l'addebito finale rende il saldo negativo.

La modalità nickname può restituire un genere insieme a name: null. Può anche dare un risultato sconosciuto. Né il normale fallback IA né l'interpretazione dei nickname garantiscono una risposta corretta o un valore diverso da null.

| Opzione della richiesta | Comportamento | Crediti per una ricerca riuscita |
| --- | --- | --- |
| options.ai_mode: off | Usa solo il set di dati. | 1, anche per un risultato sconosciuto |
| options.ai_mode: fallback | Consulta prima il set di dati e poi usa la normale IA se non viene restituito un genere. È il valore predefinito per le richieste singole. | 1 in totale, fallback IA incluso |
| options.ai_mode: always | Usa direttamente l'IA. | 2 |
| forceToGenderize: true | Consulta prima il set di dati e poi lascia che l'IA interpreti un nickname personale o un alias, anche senza un vero nome proprio. | 1 per un risultato trovato nel set di dati; 2 in totale se viene usata l'IA |

- [Opzioni IA e interpretazione dei nickname](https://www.genderapi.io/it/docs/v2/ai-options)
- [Crediti e utilizzo](https://www.genderapi.io/it/docs/v2/credits-and-usage)

## Elaborare un elenco di indirizzi email in batch

Usa POST /api/v2/gender/batch con un array items di elementi con type: email. L'accesso con una chiave API registrata supporta fino a 50 elementi, la prova IP fino a 10. Mantieni un id univoco per ogni elemento, così puoi abbinare i risultati alla riga originale. La risposta segue inoltre l'ordine di input e indica index.

Per impostazione predefinita, gli elementi di un batch usano solo il set di dati. Imposta options.ai_mode: fallback per ogni elemento che richiede il normale fallback IA. Due elementi riusciti con fallback costano 2 crediti in totale, anche quando i risultati sono sconosciuti; una richiesta HTTP non corrisponde a un credito per previsione.

Controlla ogni elemento, anche quando il batch restituisce HTTP 200. Salva i risultati riusciti e sconosciuti, poi controlla gli errori e l'addebito confermato prima di reinviare gli elementi non riusciti. Dopo un timeout non reinviare per intero un batch riuscito senza aver prima controllato l'addebito.

- [Esempi di batch, limiti ed errori parziali](https://www.genderapi.io/it/docs/v2/batch)

## Sapere che cosa invii

La demo in tempo reale invia il valore inserito a GenderAPI.io solo quando lo invii tu. Se viene usata l'IA, type, value e il contesto del paese inviati vengono trasmessi al servizio configurato per le previsioni. Per una previsione basata solo sul set di dati, nella tua integrazione imposta options.ai_mode: off senza forceToGenderize.

L'informativa sulla privacy, l'accordo sul trattamento dei dati e l'elenco dei sub-responsabili descrivono le condizioni di trattamento pubblicate. Un risultato è un'associazione dedotta e ciò che una persona dichiara ha la precedenza. Non usarlo come base per decisioni con conseguenze rilevanti per una persona.

- [Informativa sulla privacy](https://www.genderapi.io/it/privacy-policy)
- [Accordo sul trattamento dei dati](https://www.genderapi.io/it/data-processing-agreement)
- [Sub-responsabili del trattamento](https://www.genderapi.io/it/subprocessors)

## L'API può estrarre un nome proprio da un indirizzo email?

Può restituire un candidato di nome quando la parte locale contiene un indizio utilizzabile. Sono possibili corrispondenze sia su parti intere sia su sottostringhe, quindi verifica data.match. Il risultato non indica il nome proprio della persona titolare della casella.

## Un indirizzo info@ o support@ restituisce un genere?

Gli indirizzi di ruolo condivisi di solito non forniscono evidenze di un nome di persona. Un risultato sconosciuto è valido. L'IA o la modalità nickname non vanno considerate una conferma per le persone che usano una casella condivisa.

## Un risultato sconosciuto per un indirizzo email consuma crediti?

Sì. Una normale richiesta riuscita per un indirizzo email costa 1 credito, inclusi il fallback IA e i risultati sconosciuti. L'interpretazione forzata dei nickname costa 1 credito per un risultato trovato nel set di dati o 2 in totale se viene usata l'IA. In caso di errore, l'addebito è indicato separatamente in meta.usage.

## Il dominio email viene rimosso prima che l'IA elabori l'indirizzo?

Non è garantito. I candidati del set di dati provengono dalla parte locale, mentre l'IA riceve il valore inviato con l'istruzione di ignorare il dominio e il suffisso dopo il segno più. Usa la modalità basata solo sul set di dati se il tuo flusso di lavoro lo richiede.
