Article

How to Validate an Email Address in C#: Syntax, DNS, and SMTP Checks

By Unlimited Verifier Team ·

Flowchart showing C# email validation in three layers: syntax check with MailAddress, DNS domain check, and SMTP mailbox check.

Summary

To validate an email address in C#, run three layered checks: syntax with System.Net.Mail.MailAddress, a DNS check for MX records with A-record fallback, and an optional SMTP mailbox probe. Only the SMTP layer tests the mailbox itself, and it is the least reliable to run at scale.

To validate an email address in C#, run three checks in order: syntax with System.Net.Mail.MailAddress, a domain check for MX records (falling back to A records), and a mailbox check over SMTP. Only the third check tests the mailbox itself, and it is the hardest to run reliably. Syntax checks cost microseconds, while each new domain adds a DNS lookup. For the broader picture of when to validate, read our pillar guide on real-time email validation.

Quick answer

What does "validate an email address" actually mean in C#?

Validation is a set of progressively stronger tests, and each one answers a different question. A passing syntax check means the string looks like an address. A passing domain check means the domain could receive mail. Only a mailbox check tells you the receiving server accepted this recipient, and even that can mislead.

Most teams stop at the first layer and assume the result means deliverability. It doesn't. A regex will approve jo@acme-corp.co long after that company has shut down its mail servers.

Layer Question it answers What it cannot tell you Cost to run
Syntax Is this a well-formed address? Whether the domain or mailbox exists Microseconds, no network
Domain (DNS) Does the domain publish MX or A records? Whether this specific person exists One DNS query per domain
Mailbox (SMTP) Does the receiving server accept this recipient? Whether the person wants your mail One SMTP session per address

The format rules come from RFC 5322 (message syntax) and RFC 5321 (SMTP transport). The mailbox layer depends on reply codes described in RFC 3463.

Bottom line: Treat validation as three separate tests. Build the cheap layers first, and treat the mailbox layer as the last and least certain.

How do you validate email syntax in C#?

Use System.Net.Mail.MailAddress for parsing, wrap it in a few explicit rules, and skip a hand-written RFC 5322 regex. The full grammar is permissive enough to accept forms no mail server will deliver to, while an overly strict pattern rejects valid addresses such as first+tag@example.com.

The snippet below needs .NET 7 or later because it uses RegexOptions.NonBacktracking, which avoids catastrophic backtracking on hostile input. On .NET Framework, which lacks that option, remove the flag and rely on the match timeout.

using System.Net.Mail;
using System.Text.RegularExpressions;

public static class EmailSyntax
{
    private static readonly Regex Shape = new(
        @"^[^@\s]+@[^@\s]+\.[^@\s]{2,}$",
        RegexOptions.CultureInvariant | RegexOptions.NonBacktracking,
        TimeSpan.FromMilliseconds(250));

    public static bool IsWellFormed(string? raw, out string normalized)
    {
        normalized = (raw ?? string.Empty).Trim().ToLowerInvariant();
        if (normalized.Length == 0 || normalized.Length > 254) return false;

        int at = normalized.LastIndexOf('@');
        if (at < 1 || at > 64) return false;   // RFC 5321 local-part limit

        if (!Shape.IsMatch(normalized)) return false;

        try
        {
            // MailAddress also accepts "Name <a@b.com>". Require the bare address to round-trip.
            return new MailAddress(normalized).Address == normalized;
        }
        catch (FormatException)
        {
            return false;
        }
    }
}

Three decisions in this code matter:

The built-in EmailAddressAttribute in System.ComponentModel.DataAnnotations is meant for form plumbing. Don't rely on it for data cleaning without reading its documentation and testing its behavior on your own data. If your front end is browser code, the same logic belongs in JavaScript validation rules, and the typed TypeScript version follows the same pattern.

Bottom line: Use MailAddress plus a length rule and a round-trip check. A passing syntax test means "well formed," never "deliverable."

How do you confirm a domain can receive email?

Query the domain's MX records with a DNS library, because .NET's base class library has no MX lookup. If no MX record exists, RFC 5321 says mail should go to the domain's address record, so an A record counts too. Skipping that fallback causes false rejections on small domains that depend on it.

The class below uses the DnsClient NuGet package. It returns three states rather than a bool, because a timeout is not the same as a dead domain.

using System.Collections.Concurrent;
using DnsClient;

public enum DomainStatus { Deliverable, NoMail, Unknown }

public sealed class DomainChecker
{
    private readonly LookupClient _dns = new(new LookupClientOptions
    {
        Timeout = TimeSpan.FromSeconds(3),
        UseCache = true
    });

    private readonly ConcurrentDictionary<string, DomainStatus> _cache =
        new(StringComparer.OrdinalIgnoreCase);

    public async Task<DomainStatus> CheckAsync(string domain, CancellationToken ct = default)
    {
        if (_cache.TryGetValue(domain, out var cached)) return cached;

        DomainStatus status;
        try
        {
            var mx = (await _dns.QueryAsync(domain, QueryType.MX, cancellationToken: ct))
                     .Answers.MxRecords().ToList();

            if (mx.Count > 0)
            {
                // RFC 7505 null MX: a single "MX 0 ." means the domain accepts no mail.
                bool nullMx = mx.Count == 1 && mx[0].Exchange.Value.Trim('.').Length == 0;
                status = nullMx ? DomainStatus.NoMail : DomainStatus.Deliverable;
            }
            else
            {
                // RFC 5321 implicit MX: fall back to the domain's A record.
                var a = await _dns.QueryAsync(domain, QueryType.A, cancellationToken: ct);
                status = a.Answers.ARecords().Any() ? DomainStatus.Deliverable : DomainStatus.NoMail;
            }
        }
        catch (Exception)   // timeouts and resolver failures
        {
            return DomainStatus.Unknown;   // not cached, so a later run can retry
        }

        _cache[domain] = status;
        return status;
    }
}

Two details separate a reliable domain check from a fragile one:

Bottom line: A domain check proves the domain can receive mail, not that a specific person does. Cache definitive answers per domain, and treat failures as unknown.

How do you check whether a mailbox exists over SMTP?

Open an SMTP session to the domain's lowest-preference MX host on port 25, send MAIL FROM and RCPT TO, and read the reply code. Never send DATA, because the probe must not deliver a message. A 250 means the server accepted the recipient, and a 550-class reply means it refused.

This is the only layer that touches the mailbox, and it is the least reliable one in practice:

The session below handles multi-line replies, which is where most hand-rolled SMTP clients break.

using System.Net.Sockets;

static async Task<int> ReadReplyAsync(StreamReader reader)
{
    string? line;
    do
    {
        line = await reader.ReadLineAsync()
               ?? throw new IOException("SMTP connection closed unexpectedly.");
    } while (line.Length > 3 && line[3] == '-');  // "250-" means more lines follow

    if (line.Length < 3) throw new IOException($"Malformed SMTP reply: '{line}'");
    return int.Parse(line.AsSpan(0, 3));
}

static async Task<int> ProbeRecipientAsync(string mxHost, string recipient)
{
    // Wrap the whole session in a timeout in production; these reads are not cancellable here.
    using var tcp = new TcpClient();
    await tcp.ConnectAsync(mxHost, 25);
    using var stream = tcp.GetStream();
    using var reader = new StreamReader(stream);
    using var writer = new StreamWriter(stream) { NewLine = "\r\n", AutoFlush = true };

    await ReadReplyAsync(reader);                                   // 220 greeting
    await writer.WriteLineAsync("EHLO verify.yourdomain.example");
    await ReadReplyAsync(reader);
    await writer.WriteLineAsync("MAIL FROM:<probe@yourdomain.example>");
    await ReadReplyAsync(reader);
    await writer.WriteLineAsync($"RCPT TO:<{recipient}>");
    int code = await ReadReplyAsync(reader);
    await writer.WriteLineAsync("QUIT");
    return code;
}

Read the reply code deliberately:

For a step-by-step version with more protocol detail, see our SMTP email check guide.

Bottom line: The SMTP probe is the only check that touches the mailbox, but port blocks, catch-alls and rate limits mean a 250 needs interpretation, not just a lookup.

How do you spot catch-all, disposable and role-based addresses?

Detect catch-all domains by probing a random local part on the same domain, and flag disposable and role-based addresses with lookup lists. These three categories are where a clean-looking list hides its risk.

A catch-all probe looks like this, using the lowest-preference MX host from the query in DomainChecker:

// mxHost: the lowest-preference host, e.g. mx.OrderBy(r => r.Preference).First().Exchange.Value.TrimEnd('.')
string probe = $"no-such-{Guid.NewGuid():N}@{domain}";
int code = await ProbeRecipientAsync(mxHost, probe);
bool isCatchAll = code is 250 or 251;

// A simple role-prefix heuristic. It misses some role accounts and flags some personal ones.
static readonly HashSet<string> RolePrefixes = new(StringComparer.OrdinalIgnoreCase)
{ "info", "sales", "admin", "support", "noreply", "no-reply", "hello", "contact" };

bool isRole = RolePrefixes.Contains(email[..email.IndexOf('@')]);

Be honest about the limits. A catch-all flag describes the server's configuration, not the person. A disposable list is only as complete as its last update. Building all of this yourself is worthwhile if you need control, but Unlimited Verifier flags catch-all domains, disposable addresses and role-based addresses for you. Read its catch-all email verification page to see how those results are handled, or run a single address through the free email checker before writing any code.

Bottom line: Route catch-all, disposable and role-based addresses to Risky, not Valid. A catch-all result means the server accepts everything, so it cannot confirm the mailbox.

Which validation approach should you choose?

Choose by where validation runs and how many addresses you check. A signup form, a nightly CRM job and a one-off cleanup of a 200,000-row purchased list need different tools, and no single approach covers all three well.

Approach What it proves What it can't prove Effort to build Cost Best fit
MailAddress plus rules Well-formed syntax Domain or mailbox existence Minutes Free Form UX and first-pass filter
DnsClient MX/A lookup Domain can receive mail Whether the person exists Hours Free (DNS queries) Pre-filter and domain caching
Raw SMTP probe in C# The receiving server's answer Catch-all truth; often blocked on cloud networks Days, with edge cases (rough estimate) Infrastructure and reputation risk Teams that own their sending infrastructure
Email verification API Syntax, domain/MX, SMTP mailbox, catch-all, disposable and role flags, sorted into Valid, Risky or Invalid Consent and intent Hours (one HTTP call) Pro includes API access; the Free plan has none Signup checks and scheduled batches
Bulk upload The same checks on a CSV or Excel file Real-time decisions Minutes Free for 25 lists of up to 150 emails a month; Pro for larger lists One-off cleaning and migrations

Two tradeoffs stand out. Building your own SMTP probe gives full control, but it puts your sending reputation at risk and needs upkeep for every edge case. A hosted service gives you a maintained engine and sorted results, but you depend on a third party's accuracy. Unlimited Verifier states 99.5% accuracy for its deep verification. That is the company's own figure, not an independent benchmark, so run a sample from your list before trusting any vendor number.

If your stack is Ruby or Go rather than C#, compare the Ruby gems or Go packages for the same three layers. For a wider view of the category, see the best email verification tools. For how teams wire verification into code and schedules, see email verification API and automation.

Bottom line: Build the free layers yourself, and buy the mailbox layer when you need volume or production reliability.

Where should validation run in a signup flow?

Run syntax checks in the browser for speed and on the server for truth, and run mailbox checks asynchronously so the user never waits on them. Client-side checks improve the form, but anyone can bypass them, so the server's result is the one you store.

A practical pattern:

  1. Client. Check the shape and show an inline hint. Never reject a submission on client logic alone.
  2. Server, synchronously. Run EmailSyntax.IsWellFormed and reject malformed input with a clear message.
  3. Server, asynchronously. Queue the domain and mailbox checks, and store the result as Valid, Risky, Invalid or Unknown.
  4. Gate by risk. Let Valid addresses through, send Risky ones to double opt-in, and hold Invalid ones back.

The reason to avoid blocking is that an SMTP handshake can take seconds on a slow receiving server, and users who wait and then see an error often abandon the form. If your frontend is React, the React Hook Form setup covers the client side. Adding real-time checks to signup forms covers the UX, and client-side vs server-side validation explains why the server has the final word. Plan the request volume for a signup API using the guidance on API rate limits. For long-term growth without bad addresses, see list growth strategies.

Bottom line: Validate syntax synchronously, verify mailboxes asynchronously, and let a confirmation email, not a probe, prove ownership.

How do you validate a CSV of addresses in C#?

This pipeline pre-filters a CSV with the free layers, then hands the survivors to a mailbox-level tool. It assumes a .NET 7 or later console app and an email address in the first column.

  1. Create the project. Run dotnet new console -n EmailCleaner, then cd EmailCleaner.
  2. Add the DNS package. Run dotnet add package DnsClient.
  3. Add the syntax class. Paste the EmailSyntax class into EmailSyntax.cs.
  4. Add the domain checker. Paste DomainChecker and the DomainStatus enum into DomainChecker.cs.
  5. Replace Program.cs with the pipeline below. It rejects malformed rows, removes duplicates, checks domains and writes three files.
  6. Run it. Run dotnet run, then open prefiltered.csv, rejected.csv and retry.csv to confirm the counts.
  7. Verify the survivors. Sign up for a free account, then upload and verify a list using prefiltered.csv. The upload accepts CSV or Excel files up to 10MB and detects the email column automatically.
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var domains = new DomainChecker();
var valid = new List<string> { "email" };                 // header row for the upload
var rejected = new List<string> { "email,reason" };
var retry = new List<string>();

foreach (var line in File.ReadLines("contacts.csv").Skip(1))   // skip input header
{
    var raw = line.Split(',')[0];                   // use CsvHelper for quoted fields
    if (!EmailSyntax.IsWellFormed(raw, out var email))
    {
        rejected.Add($"{raw},syntax");
        continue;
    }
    if (!seen.Add(email)) continue;                 // duplicate

    var domain = email[(email.LastIndexOf('@') + 1)..];
    var status = await domains.CheckAsync(domain);
    switch (status)
    {
        case DomainStatus.NoMail:
            rejected.Add($"{email},no-mx");
            break;
        case DomainStatus.Unknown:
            retry.Add(email);                       // DNS trouble: try again later
            break;
        default:
            valid.Add(email);
            break;
    }
}

File.WriteAllLines("prefiltered.csv", valid);
File.WriteAllLines("rejected.csv", rejected);
File.WriteAllLines("retry.csv", retry);
Console.WriteLine($"Kept {valid.Count - 1}, rejected {rejected.Count - 1}, retry {retry.Count}");

Two practical notes. First, Split(',') breaks on quoted fields, so use a real CSV parser for production files. Second, keep rejected.csv as your evidence trail. Unlimited Verifier keeps results for 24 hours on the Free plan and 30 days on Pro, so export the Valid, Risky and Invalid files as soon as each run finishes.

Bottom line: Local checks remove the obvious failures at no metered cost, so mailbox checks only run on addresses with a real chance of working.

How much does it cost to clean a 40,000-row list?

This example is illustrative. The percentages and domain counts are hypothetical, but the arithmetic and plan limits are real. It's a typical email verification for ecommerce and SaaS cleanup.

Starting point: A SaaS team exports 40,000 rows from an old CRM before a product launch.

Step 1: local pre-filter

Step 2: DNS caching

Assume the 36,000 addresses span about 1,400 distinct domains. Caching reduces lookups from 36,000 to 1,400:

1 − (1,400 ÷ 36,000) = about 96% fewer DNS queries

Step 3: upload within plan limits

On the Pro plan ($29 a month, or $25 a month billed annually), each list can hold up to 25,000 emails. Split the 36,000 rows into two files:

Pro includes 25,000 deep verifications a month. Check which of your runs draw on that quota before you plan. If all 36,000 rows needed deep verification, the run would exceed one month's allowance by 11,000:

36,000 − 25,000 = 11,000 over quota

Step 4: API alternative

Pro includes API access for 100,000 emails a month. Sending the same 36,000 addresses in batches of up to 10,000 takes four requests:

10,000 + 10,000 + 10,000 + 6,000 = 36,000, using 36% of the monthly API quota

Step 5: cost

Email verification pricing is a flat monthly fee, so the effective cost depends on how much of the quota you use:

Light users pay more per address, so the flat fee only makes sense at volume.

Illustrative outcome: If the mailbox pass returned 85% Valid, 8% Risky and 7% Invalid, the split on 36,000 addresses would be:

Send the Valid segment first, hold Risky addresses for double opt-in or a small test, and suppress Invalid addresses permanently. Replace the percentages with your own sample results.

Bottom line: Local checks cut 40,000 rows to 36,000 without metered spend, and the API pass for those survivors costs $0.29 per 1,000 at full quota.

What are the most common mistakes?

Most validation code fails in predictable ways. Each mistake delivers either false rejections or false confidence.

Bottom line: Most validation failures come from treating an inconclusive result as a definitive one. Label every result honestly.

How we compared (and limitations)

This guide is based on public documentation: the IETF RFCs linked above, Microsoft's .NET documentation for MailAddress, and the DnsClient package documentation. We have not benchmarked these approaches or any vendor's accuracy.

Where sources disagree, we say so. The practical maximum address length is commonly given as 254 characters, while RFC 5321's path limit is 256 octets including the angle brackets. We recommend 254 for input. Standards also differ on how strictly to treat quoted local parts, which is why we use a simple, explicit shape check.

Unlimited Verifier's figures come from its own published plan details. It states 99.5% accuracy for deep verification, which is the company's figure, not an independent benchmark. Worked-example percentages are hypothetical. Plan limits and prices can change, so check current pricing before you budget. For ongoing hygiene after the first cleanup, see our guide to email list maintenance best practices, and for teams validating outbound lists, read about email verification for sales prospecting.

Bottom line: Use the layered approach as your baseline, check the vendor figures against a sample from your own list, and recheck pricing before you commit.

Three-layer validation steps for a bulk list

  1. Syntax pass (local): Parse each string with MailAddress, enforce a length limit, and confirm the parsed address matches the original input. Discard failures immediately.
  2. Deduplicate and group: Lowercase addresses, remove exact duplicates, and group the rest by domain.
  3. Domain pass (one lookup per domain): Query MX records, fall back to A records, and cache the result. Mark domains with no records as Invalid.
  4. Mailbox pass (survivors only): Run SMTP probes asynchronously with a timeout. Record 550 as Invalid, 4xx and timeouts as Unknown, and 250 as Likely valid.
  5. Store the outcome: Save the layer results and timestamp so that Unknown addresses can be retried later.

Illustrative example: in a 40,000-row list where most addresses share a few hundred domains, step 3 turns tens of thousands of addresses into a small number of DNS queries, which keeps the slowest network work to the mailbox pass.

Frequently asked questions

Is a regex good enough to validate email in C#?

A regex can catch obvious typos, but it is not sufficient on its own. A full RFC 5322 pattern accepts forms that mail servers will not deliver to, and a simplified pattern can reject valid addresses such as first+tag@example.com. Using System.Net.Mail.MailAddress for parsing, plus a length limit and a round-trip check, is generally more reliable.

Does MailAddress fully validate an email address?

No. MailAddress confirms that the string parses as an address, but it does not check whether the domain has mail servers or whether the mailbox exists. It is the first layer of validation, and it should be followed by DNS and, optionally, SMTP checks.

How do I check whether a domain can receive email in C#?

Query the domain's MX records using a DNS library, such as DnsClient.NET. If no MX records exist, fall back to an A record, since some domains accept mail at their base address. Cache the result per domain so that repeated addresses on the same domain do not trigger new lookups.

Can I confirm a mailbox exists without sending an email?

You can open an SMTP session, issue HELO, MAIL FROM, and RCPT TO, then read the reply code without sending a message. However, many servers accept every recipient or block probing, so a positive result is not proof of a real mailbox. Treat the outcome as a signal, not a guarantee.

What SMTP reply codes indicate an invalid recipient?

A 550 reply to RCPT TO generally means the mailbox was rejected. A 4xx reply is temporary, such as a greylisting or rate-limit response, and should be recorded as Unknown rather than Invalid. Reply code meanings are described in RFC 3463 for enhanced status codes.

Should I block user signup until SMTP validation completes?

No. SMTP probes can be slow, time out, or be refused by the receiving server. Accept the signup, run the mailbox check asynchronously, and flag the account if the result is Invalid. Blocking the form on a network probe creates a poor user experience and false rejections.

How long should the SMTP timeout be?

There is no universal value, but short timeouts keep the process responsive. Many implementations use a timeout in the range of several seconds per connection and record any timeout as Unknown. Tune the value using your own logs, since networks and receiving servers vary.

Does .NET 7 change how I should write email regex validation?

Yes, in one useful way. RegexOptions.NonBacktracking, available from .NET 7, helps avoid catastrophic backtracking on hostile input. On older .NET Framework versions that lack this option, use a match timeout instead to protect the application from slow patterns.

How do I validate a large list of emails efficiently in C#?

Pre-filter the list with syntax checks, which are fast and local. Deduplicate addresses, group them by domain, and run one DNS lookup per domain. Send only the remaining addresses to mailbox verification, either through your own SMTP process or a third-party verification service.

Cut Bounces and Protect Your Sender Reputation With Unlimited Email Verification

Every invalid address you send to hurts your sender reputation and your inbox placement. Verifying your list before each send means fewer bounces, healthier deliverability, and a predictable cost. With Unlimited Verifier, standard verification is unlimited on every plan, with no per-email fees.

Unlimited Verifier checks syntax, domain, MX records and the SMTP mailbox. It also detects catch-all domains and flags disposable and role-based addresses. Export a CSV from your email platform or CRM, upload and verify the list, then re-import the clean results. You can also automate checks with the email verification API.

Free Pro
Price $0 $29/month ($25/month billed annually)
Lists 25 a month, up to 150 emails each Unlimited, up to 25,000 emails each
Deep verifications 750 a month 25,000 a month
API access No Yes (100,000 emails a month)
Result retention 24 hours 30 days

Why teams choose Unlimited Verifier

Unlimited Verifier states 99.5% accuracy for deep verification.

Create a free account and verify your next list before you hit send.

Want to test a single address first? Try the free email checker.