Home

C# Email Validation/Verify

Blog Date 30 April 2021

TLDR

    protected bool SendTheEmail(string MyPassword, string ThisEmail)
    {
        try
        {
            MailAddress MyTo = new MailAddress(ThisEmail);
            MailAddress MyFrom = new MailAddress("MyName@MyEmail.com");

            string qwe = "This is the text in the body"

            MailMessage MyMail = new MailMessage(MyFrom, MyTo);
            MyMail.Subject = "My Subject Line";
            MyMail.IsBodyHtml = true;
            MyMail.Body = qwe;
            SmtpClient MyClient = new SmtpClient("mail.mymainserver.com", 587);
            MyClient.Credentials = new NetworkCredential("MyName@MyEmail.com", "MyPassword");
            MyClient.EnableSsl = true;

            MyClient.Send(MyMail);
            return true;
        }
        catch (Exception ex)
        {
            ErrorDetails.Text = ex.Message;
            return false;
        }
    }

The Explanation.

No one likes a try - catch in code other than for "proper" use. Hmmm. I tend to agree. In this instance we really REALLY ought to ensure the email meets all the (latest) RFC specifications for an email address. 

We should you know, we really REALLY should.

So off we pop to our favourite search engine and look for "C# Email Address Validation". What you find are countless people with a perplexing plethora, a multitudinous compendium and a veritable fantasia of primarily Regex solutions. After each offering various commenters say "well yeah but it doesn't catch fred@fred with no dot something" and "I've implemented this and now fred@fred-fred.co.jp" can't send emails.

The problem is the RFCs appear to be quite complicated. Oh yeah? Before you start a tirade in the comments just go look at all the other posts re email validation. Ain't no-one got time to learn all the RFCs and then learn the dark arts of Regex and/or go through the address one character at a time and check the rules. Life, dear reader, is too damn short.

Anyhow, right, yeah, right. EVEN IF... even if the address is RFC compliant it don't mean it actually exists out there in the murky depths of emailland. No. I could have accidentally typed "ren@twchsolus.co.uk" rather than "ren@techsolus.co.uk" and the email would be anatomically correct. But it won't exist (I suspect).

So using the code above I am simply going to send the goddam email through C#'s email implementation. If C# spits out it's dummy then I'll capture the exception's "message" section and display it. While to many users it may be gobbledegook if they call me at least I've gotten a starter for 10 as to what the problem is.

It ain't purdy, but it's effective.

Reader's Comments

Post Your Comment Posts/Links Rules

Name

Comment

Add a RELEVANT link (not required)

Upload an image (not required)

No uploaded image
Real person number
Please enter the above number below




Home
Admin Ren's Biking Blog