HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Validating email addresses through temporary mail message

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
emailtemporarymessagevalidatingaddressesmailthrough

Problem

I was given this project and have changed a lot of code on it, now I am going over the code to make sure that I know what everything does and can maintain it efficiently, and to make sure I want my name on it.

Here is the method they have been using to validate e-mail addresses from a textbox input.

private string ValidateEmailAddresses(string addressesIn)
{
    MailMessage msg = new MailMessage();

    if (!String.IsNullOrWhiteSpace(addressesIn))
    {
        string[] allAddresses = addressesIn.Split(";,".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

        foreach (string addy in allAddresses)
        {
            try
            {
                msg.To.Add(addy);
            }
            catch (FormatException)
            { }
        }
    }
    return msg.To.ToString();
}


Is there a better way to accomplish this task?

Solution

-
Well, it really depends on why addressesIn is a string. If it's input from the user, as I suspect, it is a fine method.

-
If I was to be a harsh critic I would ask why a method named "Validate" returns a string.

-
I think if you rename the method to like "ScrubEmailAddresses" or "SanitizeEmailAddresses" and envision it in an app that lets a user input email addresses to send an email to, it's kind of nifty. Basically instead of a roll-your-own-validations approach this says "hey, let the framework do it for me!" by taking advantage of the fact that .NET will just throw a FormatException if you try to add an invalid address. It's a fairly decent server-side equivalent to a RegularExpressionValidator using the predefined email regex. I also agree with Mike McCaughan's comment mentioning there is a resource hit when having the framework throw an exception.

Context

StackExchange Code Review Q#74706, answer score: 5

Revisions (0)

No revisions yet.