Best way to validate email address format in C#

561 views Asked by At

Hi I am working on a bulk email sending feature. Below is my loop that validates email and sends them to each recipient:

foreach (var userID in recipientUserIds)
{
    var userInfo = //getting from database using userID.

    try
    {
        to = new MailAddress(userInfo.Email1, userInfo.FirstName + " " + userInfo.LastName);
    }
    catch (System.FormatException fe)
    {
        continue;
    }

    using (MailMessage message = new MailMessage(from, to))
    {
        //populate message and send email.
    }
}

Since the recipientUserIds is always more than 2000, using try-catch seems to be very expensive for each user in this case just to validate the email address format. I was wondering to use regex, but not sure if that will help with performance.

So my question is if there is any better or performance optimized way to do the same validation.

1

There are 1 answers

0
Rufus L On BEST ANSWER

Validating email addresses is a complicated task, and writing code to do all the validation up front would be pretty tricky. If you check the Remarks section of the MailAddress class documentation, you'll see that there are lots of strings that are considered a valid email address (including comments, bracketed domain names, and embedded quotes).

And since the source code is available, check out the ParseAddress method here, and you'll get an idea of the code you'd have to write to validate an email address yourself. It's a shame there's no public TryParse method we could use to avoid the exception being thrown.

So it's probably best to just do some simple validation first - ensure that it contains the minimum requirements for an email address (which literally appears to be user@domain, where domain does not have to contain a '.' character), and then let the exception handling take care of the rest:

foreach (var userID in recipientUserIds)
{
    var userInfo = GetUserInfo(userID);

    // Basic validation on length
    var email = userInfo?.Email1?.Trim();
    if (string.IsNullOrEmpty(email) || email.Length < 3) continue;

    // Basic validation on '@' character position
    var atIndex = email.IndexOf('@');
    if (atIndex < 1 || atIndex == email.Length - 1) continue;

    // Let try/catch handle the rest, because email addresses are complicated
    MailAddress to;
    try
    {
        to = new MailAddress(email, $"{userInfo.FirstName} {userInfo.LastName}");
    }
    catch (FormatException)
    {
        continue;
    }

    using (MailMessage message = new MailMessage(from, to))
    {
        // populate message and send email here
    }
}