Code samples · C#
C# code samples
Copy-paste C# examples that validate one address, send the API key in the Authorization header, retry 429 and 503 answers after Retry-After when the wait is at most 10 seconds (never key_daily_cap, which lasts until the next UTC day), and report other errors with their code and request id. Each uses the free test address accepted@sandbox.email-validation.org; replace it with a real address when you are ready. The same samples in other languages: all code samples.
Set your key first: export EV_API_KEY="ev_live_…".
The samples call https://api.email-validation.org. For EU data residency, replace it with https://api-eu.email-validation.org, or pass the SDK's EU base URL constant; there /v1/validate takes POST only (EU data residency).
With the official SDK
The official C# and .NET SDK does the retries, timeouts and error mapping for you: one call validates an address and every failure arrives as a typed error. There are official SDKs for JavaScript/TypeScript, Python, Go, PHP, Ruby, C#, Rust and Swift; those for Java, Kotlin, Dart, Elixir, C and Perl are built and tested and coming soon to their package registries. The plain HTTP samples further down call the API directly.
C#
using EmailValidation;
using var client = new EmailValidationClient(Environment.GetEnvironmentVariable("EV_API_KEY")!);
try
{
var result = await client.ValidateAsync("accepted@sandbox.email-validation.org");
Console.WriteLine($"{result.Status} {result.Reason} {result.Action}"); // valid accepted send
}
catch (InsufficientCreditsException)
{
Console.WriteLine("buy credits; nothing was charged");
}
catch (EmailValidationException e)
{
Console.WriteLine($"{e.Code} {e.RequestId}");
}Validate an address
C#
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json.Serialization;
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(20) };
http.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("EV_API_KEY"));
var result = await Validate(http, "accepted@sandbox.email-validation.org");
Console.WriteLine($"{result.Status} {result.Reason} {result.Action} {result.CreditsUsed}");
static async Task<ValidationResult> Validate(HttpClient http, string email, int attempts = 3)
{
for (var attempt = 1; ; attempt++)
{
using var response = await http.PostAsJsonAsync("https://api.email-validation.org/v1/validate", new { email });
if (response.IsSuccessStatusCode)
return (await response.Content.ReadFromJsonAsync<ValidationResult>())!;
var body = await response.Content.ReadFromJsonAsync<ErrorEnvelope>();
// Never wait out a long Retry-After: key_daily_cap lasts until the next UTC day.
var wait = response.Headers.RetryAfter?.Delta ?? TimeSpan.FromSeconds(1);
var retryable = (response.StatusCode is HttpStatusCode.TooManyRequests or HttpStatusCode.ServiceUnavailable)
&& body?.Error.Code != "key_daily_cap" && wait <= TimeSpan.FromSeconds(10);
if (retryable && attempt < attempts)
{
await Task.Delay(wait);
continue;
}
throw new HttpRequestException($"{body?.Error.Code}: {body?.Error.Message} ({body?.Error.RequestId})");
}
}
record ValidationResult(
[property: JsonPropertyName("email")] string Email,
[property: JsonPropertyName("status")] string Status,
[property: JsonPropertyName("reason")] string Reason,
[property: JsonPropertyName("action")] string Action,
[property: JsonPropertyName("credits_used")] int CreditsUsed,
[property: JsonPropertyName("request_id")] string RequestId);
record ApiError(
[property: JsonPropertyName("code")] string Code,
[property: JsonPropertyName("message")] string Message,
[property: JsonPropertyName("request_id")] string RequestId);
record ErrorEnvelope([property: JsonPropertyName("error")] ApiError Error);Verify a webhook
C#
using System.Security.Cryptography;
using System.Text;
public static class WebhookVerifier
{
/// Throws unless the delivery is authentic and recent. Pass the raw body as received.
public static void Verify(string rawBody, string? id, string? timestamp, string? signatures, string secret)
{
if (string.IsNullOrEmpty(id) || string.IsNullOrEmpty(timestamp) || string.IsNullOrEmpty(signatures))
throw new CryptographicException("Missing webhook headers");
if (!long.TryParse(timestamp, out var ts) ||
Math.Abs(DateTimeOffset.UtcNow.ToUnixTimeSeconds() - ts) > 300)
throw new CryptographicException("Timestamp outside tolerance");
var key = Convert.FromBase64String(secret.StartsWith("whsec_") ? secret[6..] : secret);
var expected = HMACSHA256.HashData(key, Encoding.UTF8.GetBytes($"{id}.{timestamp}.{rawBody}"));
foreach (var entry in signatures.Split(' '))
{
var parts = entry.Split(',', 2);
if (parts.Length != 2 || parts[0] != "v1") continue;
try
{
if (CryptographicOperations.FixedTimeEquals(Convert.FromBase64String(parts[1]), expected)) return;
}
catch (FormatException)
{
// not base64: try the next signature
}
}
throw new CryptographicException("No valid signature");
}
}Other calls
- Read the credit balance: samples in curl, JavaScript and Python (all code samples).
- Create a bulk job: samples in curl, JavaScript and Python (all code samples).
Notes
- Use
POSTwith a JSON body; it keeps addresses out of URLs and logs. - Set the HTTP timeout to about 20 seconds: a check may take up to 15 seconds (10 by default).
- A
200answer with the statusunknownis a normal, free result, not an error. - Every endpoint, field and error: the API reference.