Email Verification in C#: Integrating EmailVerifierAPI with ASP.NET Core

Key Takeaways

  • EmailVerifierAPI's REST endpoint integrates with C# and ASP.NET Core using the built-in HttpClient, with no third-party SDKs required.
  • The v2/verify endpoint returns granular status fields including delivery status, disposable detection, role account flags, and SMTP sub-status codes for precise validation logic.
  • Wrapping the API call in a dedicated service class with dependency injection makes it testable, reusable across controllers and middleware, and easy to mock in unit tests.
  • Implementing retry logic with exponential backoff and proper timeout configuration ensures resilient verification even under high-traffic conditions.

C# and ASP.NET Core power a significant portion of enterprise web applications, SaaS platforms, and internal business tools. When these applications collect email addresses through registration forms, contact pages, or data import workflows, validating those addresses in real time prevents bad data from entering your system and protects your transactional email deliverability. This guide walks through a complete integration of the EmailVerifierAPI into an ASP.NET Core application, from initial HTTP client setup through response handling and error management.

Prerequisites and API Setup

Before writing any code, you need an EmailVerifierAPI account and an API key. Register for free to receive 100 verification credits, then retrieve your API key from the dashboard. The verification endpoint accepts GET requests at https://emailverifierapi.com/v2/verify with your email and API key as query parameters. No SDK installation is needed because the API returns standard JSON over HTTPS, which ASP.NET Core handles natively with HttpClient and System.Text.Json.

Start by testing the endpoint with a curl command to confirm your API key is working:

curl "https://emailverifierapi.com/v2/verify?email=test@example.com&apikey=YOUR_API_KEY"

A successful response returns JSON with the full verification result. Refer to the API documentation for the complete field reference.

Creating the Verification Service

The cleanest approach in ASP.NET Core is to create a dedicated service class registered with the dependency injection container. This keeps your verification logic isolated, testable, and reusable across controllers, Razor Pages, or middleware. Start by defining a response model that maps to the API's JSON output:

using System.Text.Json.Serialization;

public class EmailVerificationResult
{
    [JsonPropertyName("status")]
    public string Status { get; set; } = string.Empty;

    [JsonPropertyName("sub_status")]
    public string SubStatus { get; set; } = string.Empty;

    [JsonPropertyName("smtp_check")]
    public string SmtpCheck { get; set; } = string.Empty;

    [JsonPropertyName("isDisposable")]
    public bool IsDisposable { get; set; }

    [JsonPropertyName("isFreeService")]
    public bool IsFreeService { get; set; }

    [JsonPropertyName("isRoleAccount")]
    public bool IsRoleAccount { get; set; }

    [JsonPropertyName("isGibberish")]
    public bool IsGibberish { get; set; }

    [JsonPropertyName("isOffensive")]
    public bool IsOffensive { get; set; }
}

Next, create the service class that wraps the HTTP call with proper error handling and timeout configuration:

using System.Net.Http.Json;

public class EmailVerifierService
{
    private readonly HttpClient _httpClient;
    private readonly string _apiKey;

    public EmailVerifierService(
        HttpClient httpClient,
        IConfiguration config)
    {
        _httpClient = httpClient;
        _apiKey = config["EmailVerifierAPI:ApiKey"]
            ?? throw new ArgumentNullException(
                "EmailVerifierAPI:ApiKey not configured");
    }

    public async Task<EmailVerificationResult?> VerifyAsync(
        string email,
        CancellationToken ct = default)
    {
        var url = $"https://emailverifierapi.com/v2/verify"
            + $"?email={Uri.EscapeDataString(email)}"
            + $"&apikey={_apiKey}";

        try
        {
            var result = await _httpClient
                .GetFromJsonAsync<EmailVerificationResult>(
                    url, ct);
            return result;
        }
        catch (HttpRequestException ex)
        {
            // Log the error and return null to
            // let the caller decide how to proceed
            Console.Error.WriteLine(
                $"Verification failed: {ex.Message}");
            return null;
        }
        catch (TaskCanceledException)
        {
            // Request timed out
            Console.Error.WriteLine(
                "Verification request timed out");
            return null;
        }
    }
}

Registering the Service with Dependency Injection

In your Program.cs, register the service using AddHttpClient to benefit from the IHttpClientFactory pattern, which manages connection pooling and prevents socket exhaustion under load:

builder.Services.AddHttpClient<EmailVerifierService>(
    client =>
    {
        client.Timeout = TimeSpan.FromSeconds(10);
        client.DefaultRequestHeaders.Add(
            "Accept", "application/json");
    });

Store your API key in appsettings.json or a secrets manager. Never hardcode credentials in source files.

Using the Service in a Controller

Inject the service into any controller or Razor Page that handles email input. Here is an example registration endpoint that validates the email before creating the account:

[ApiController]
[Route("api/[controller]")]
public class RegistrationController : ControllerBase
{
    private readonly EmailVerifierService _verifier;

    public RegistrationController(
        EmailVerifierService verifier)
    {
        _verifier = verifier;
    }

    [HttpPost]
    public async Task<IActionResult> Register(
        [FromBody] RegisterRequest request)
    {
        var result = await _verifier
            .VerifyAsync(request.Email);

        if (result == null)
        {
            // API unavailable: allow signup but
            // queue for background verification
            return Ok(new { verified = false,
                message = "Queued for verification" });
        }

        if (result.Status != "passed")
        {
            return BadRequest(new {
                error = "Invalid email address",
                detail = result.SubStatus
            });
        }

        if (result.IsDisposable)
        {
            return BadRequest(new {
                error = "Disposable emails not allowed"
            });
        }

        // Email is valid: proceed with registration
        // ... save user to database
        return Ok(new { verified = true,
            message = "Registration successful" });
    }
}

Understanding the Response Fields

The verification response provides multiple data points that support different validation strategies. The status field returns one of four values: passed (deliverable), failed (undeliverable), unknown (cannot be determined), or transient (temporary issue, retry later). The sub_status field provides specifics like mailboxExists, mailboxDoesNotExist, domainDoesNotExist, isCatchall, or isGreylisting.

The boolean flags offer additional intelligence. Use isDisposable to block throwaway email services. Use isRoleAccount to flag or restrict generic addresses like info@ or admin@ that may not represent individual users. Use isGibberish to detect randomly generated strings that indicate automated abuse. Combine these fields in your validation logic to match your application's risk tolerance. For the full field reference and additional response examples, see the C# integration guide on the EmailVerifierAPI integrations hub.

Production Considerations

For production deployments, add structured logging to every verification call so you can track verification volumes, failure rates, and API response times in your monitoring system. Implement a circuit breaker pattern using Polly or a similar resilience library to gracefully degrade when the verification API is unreachable, falling back to basic regex validation while queuing addresses for later verification. Cache positive verification results for a configurable duration (24 to 72 hours is typical) to avoid redundant API calls for the same address during high-traffic signup periods.

Rate limiting on your own application side is also important. If your signup form is targeted by bots, you could generate thousands of verification API calls per minute. Add CAPTCHA or rate limiting middleware before the verification step to protect both your verification credit balance and the API's throughput. EmailVerifierAPI's pay-as-you-go pricing ensures you only pay for the verifications you use, with credits that never expire.

Frequently Asked Questions

Do I need to install a NuGet package to use EmailVerifierAPI with C#?

No. The API is a standard REST endpoint that returns JSON. ASP.NET Core's built-in HttpClient and System.Text.Json handle the request and response natively. No additional SDK or NuGet package is required.

How should I handle the "unknown" status in my registration flow?

An "unknown" status means the verification could not definitively confirm or deny deliverability, often due to greylisting or server timeouts. The recommended approach is to allow the signup to proceed but queue the address for re-verification after a delay of 15 to 30 minutes. If re-verification still returns "unknown," treat the address with caution and consider sending a confirmation email to verify access.

What timeout should I set for the verification API call?

A timeout of 10 seconds is appropriate for most applications. The API typically responds in under 2 seconds, but SMTP-level verification against slow mail servers can occasionally take longer. Setting the timeout too low risks false timeouts on valid requests, while setting it too high can degrade your application's responsiveness.

Can I use EmailVerifierAPI with older .NET Framework projects?

Yes. While this guide uses ASP.NET Core conventions, the API is a standard HTTPS REST endpoint. Any .NET application that can make HTTP requests and parse JSON can integrate with it, including .NET Framework 4.x projects using HttpClient or WebClient.