Home >Backend Development >C#.Net Tutorial >How to verify email address in C#?

How to verify email address in C#?

王林
王林forward
2023-08-25 16:41:131174browse

如何在 C# 中验证电子邮件地址?

There are multiple ways to verify an email address in C#.

System.Net.Mail - The System.Net.Mail namespace contains classes for sending e-mail messages to a Simple Mail Transfer Protocol (SMTP) server for delivery.

System.Text.RegularExpressions - Represents immutable regular expressions.

Use the following expression

@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([azA-Z]{2,4}|[0-9]{1,3})(\]?)$"

We can use the MailAddress class of the System.Net.Mail namespace to verify the email address

Example

Real-time demonstration

using System;
using System.Net.Mail;
namespace DemoApplication{
   class Program{
      public static void Main(){
         try{
            string email = "hello@xyzcom";
            Console.WriteLine($"The email is {email}");
            var mail = new MailAddress(email);
            bool isValidEmail = mail.Host.Contains(".");
            if(!isValidEmail){
               Console.WriteLine($"The email is invalid");
            } else {
               Console.WriteLine($"The email is valid");
            }
            Console.ReadLine();
         }
         catch(Exception){
            Console.WriteLine($"The email is invalid");
            Console.ReadLine();
         }
      }
   }
}

Output

The output of the above code is

The email is hello@xyzcom
The email is invalid

Example of using regular expressions -

We can also use regular expressions to verify email addresses.

Example

using System;
using System.Text.RegularExpressions;
namespace DemoApplication{
   public class Program{
      public static void Main(){
         string email = "hello@xyz.com";
         Regex regex = new Regex(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-
         9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$",
         RegexOptions.CultureInvariant | RegexOptions.Singleline);
         Console.WriteLine($"The email is {email}");
         bool isValidEmail = regex.IsMatch(email);
         if (!isValidEmail){
            Console.WriteLine($"The email is invalid");
         } else {
            Console.WriteLine($"The email is valid");
         }
         Console.ReadLine();
      }
   }
}

Output

The output of the above code is

The email is hello@xyz.com
The email is valid

The above is the detailed content of How to verify email address in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete