2026-07-15

Validating an email address

Stefan Bogdanescu

Stefan Bogdanescu

Founder & Senior Architect

Validating an email address

Validating Email Addresses: Ensuring Successful Email Delivery in C#

Sending emails reliably is a core function of many applications, but it often introduces subtle failure points—especially when dealing with external data like user-provided email addresses. As a senior developer, I frequently encounter situations where seemingly simple string inputs lead to cryptic exceptions during the communication phase. The issue you are facing—where only some comma-delimited addresses cause failures while others succeed—is a classic problem of insufficient pre-validation.

This post will dive into how you can properly validate email addresses in C# to ensure that only correctly formatted addresses are sent, preventing those frustrating exceptions and ensuring your messages reach their intended recipients.

The Pitfall of Relying Solely on the SMTP Server

You mentioned reading that validating an email address is difficult, often citing the complexity of regular expressions. While true email format validation (adhering strictly to RFC standards) can be extremely complex, relying solely on sending an email to test validity is inefficient and error-prone. The problem arises because the failure you are seeing ("The specified string is not in the form required for an e-mail address.") occurs deep within the SMTP client handshake when the underlying system attempts to interpret a malformed address.

The solution, therefore, lies in performing rigorous client-side validation before engaging with the external mail server. We need a systematic way to check if the string adheres to basic email structure before we attempt the costly operation of sending the message.

The .NET Approach: Leveraging MailAddress for Validation

In the .NET ecosystem, the most robust and idiomatic way to validate an email address format is by using the built-in System.Net.Mail.MailAddress class. This class attempts to parse the string into a valid email structure. If the string is malformed (missing an "@" symbol, invalid characters, etc.), it will throw a FormatException, which we can catch gracefully.

Instead of trying to craft a perfect, massive regular expression—which often proves brittle for complex edge cases—we use exception handling as our primary validation tool. This approach is practical, readable, and leverages the framework's native capabilities.

Step-by-Step Validation Implementation

Here is how you can refactor your code to iterate through a list of addresses, validate each one individually, and filter out any invalid entries before attempting to send the email.

using System;
using System.Net.Mail;
using System.Net;
using System.Collections.Generic;
using System.Linq;

public class EmailSender
{
    public void SendValidatedEmail(string fromAddress, string[] toAddresses, string subject, string body)
    {
        // 1. Prepare the list of valid recipients
        List<string> validRecipients = new List<string>();

        foreach (var address in toAddresses)
        {
            try
            {
                // Attempt to create a MailAddress object. This validates the format.
                MailAddress mailAddress = new MailAddress(address);
                validRecipients.Add(mailAddress.Address);
            }
            catch (FormatException)
            {
                // If parsing fails, the address is invalid. We simply skip it.
                Console.WriteLine($"Skipping invalid email format: {address}");
            }
        }

        if (!validRecipients.Any())
        {
            Console.WriteLine("No valid email addresses found to send the message to.");
            return;
        }

        // 2. Proceed with sending only to the valid addresses
        MailMessage mail = new MailMessage();
        mail.From = new MailAddress(fromAddress, "Sender Name");
        
        foreach (var to in validRecipients)
        {
            mail.To.Add(to);
        }

        mail.Subject = subject;
        mail.Body = body;
        mail.IsBodyHtml = true;

        try
        {
            using (SmtpClient smtp = new SmtpClient("smtp.example.com")) // Replace with actual server
            {
                smtp.Credentials = System.Net.NetworkCredentialPassword.DefaultCredentials;
                // Add your specific SMTP settings here...
                smtp.Send(mail);
                Console.WriteLine($"Email successfully sent to {validRecipients.Count} recipients.");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error sending email: {ex.Message}");
        }
    }
}

Best Practices for Robust Data Handling

This approach shifts the responsibility of validation to a structured, predictable process. When building robust systems, whether you are handling user input or external API data, focusing on graceful error handling is paramount. This principle aligns with modern architectural thinking—ensuring that your system can handle bad data without crashing—which mirrors the focus on solid data contracts often championed by frameworks like Laravel, where data integrity is key to application reliability.

Remember, this validates the format. It does not guarantee that the mailbox actually exists or can receive mail (that requires a separate, more complex process). However, for filtering out basic typographical errors in an input string, this method is highly effective and far superior to relying on fragile regex patterns alone.

Conclusion

To effectively validate comma-delimited email addresses in C# before sending, avoid overcomplicating the task with intricate regular expressions. Instead, embrace the power of exception handling by utilizing the native MailAddress class within a loop. By attempting to parse each address and catching the resulting FormatException, you can systematically weed out invalid entries, ensuring that your email delivery attempts are focused only on addresses that have a legitimate structural format. This results in cleaner code, more stable applications, and reliable communication flows.

Tags:

Enhance your marketing setup with your own email marketing platform.

Join the growing number of SaaS platforms using Laravel Mail to offer email marketing solutions to their customers.