Join us
@sofiatarhonska ă» Oct 24,2022 ă» 9 min read ă» 2020 views ă» Originally posted on mailtrap.io
Email validation is crucial to help you maintain a list of valid and real email addresses. Keeping mistyped and non-existent emails will result in high bounces, low opens, and few conversions. Worse, it can also damage your sending reputation, which can be difficult to repair.Â
Hence, adding email validation in your C# code is essential. And fortunately, relatively painless! In this post, youâll learn several options on how to validate email in C#.Â
Letâs start!
Microsoft provides built-in support for sending emails to an SMTP server through the System.Net.Mail namespace. It contains the MailAddress class, which is used to store the sender and recipient email addresses. You can utilize this class to validate emails.
Note: This article focuses on email validation. If youâre looking for how to send and receive an email in C# using the classic SMTP protocol, see Send and Receive Emails in ASP.NET C#.
To see how we can use the MailAddress class to check whether an email is valid, letâs create a new C# Console App using Visual Studio. Either the .NET Framework or Core will work. Then, copy-paste the following code into the Program.cs file.
Letâs look at the IsValid method in the above code. It validates a single email by initializing a new instance of the MailAddress class using the string passed in the parameter. If succeeded, the email is considered valid, and the method returns true.
Run the project, and youâll see an output as follows:
Result of email validation using the MailAddress class
Based on the above screenshot, you can see the results for the email addresses provided. One interesting thing here is, it validates the email tony@example (without .com or .net or .co.uk) as valid.Â
You may want to have more control over the format you consider valid. In case you want to prevent emails without a top-level domain, you can try using regex.Â
A regular expression often called regex for short. Itâs a set of symbols that define a text pattern. Â
Email addresses, newsletters, text messagesâall these are text. Using a regex, you can define what pattern an email must have so that itâs considered a valid address, based on your needs.Â
Suppose you want to define only email addresses with .com, .net, .org, and .gov top-level domains are valid. You can use the following regex:
^[^@\s]+@[^@\s]+\.(com|net|org|gov)$
Copy
See the following interpretation for the regex above:
Regex is very flexible and powerful to check the email format. However, you canât use it to verify whether an email address actually exists.Â
To use a regex in your C# code, you need to include the System.Text.RegularExpressions namespace. See an example code below:
The IsValid method in the above code returns true if the email string matches the regex and false if it doesnât. Notice that the regex is using the RegexOptions.IgnoreCase flag. This option ignores case-sensitive matching.
If you run the code, youâll get the result as follows:
Based on the result above, the regex has validated emails with .com, .net, and .gov as valid addresses. Also, see that TONY@EXAMPLE.GOV validates to true. Itâs because we set the regex to ignore case-sensitive matching.Â
Letâs look at another example. The following is a regex used by Microsoft in their EmailAddressAttribute class:
Quite long, right?
Yet, there is this interesting part at the very end of the regex.Â
The above symbols will allow a dot (â.â) at the end of an email address. Test the following email using the above regex. Expectedly, the result will show that itâs a valid email.
So, the âperfectâ regex defined by someone else does not necessarily mean that it will be the same for you. Additionally, the more reliable the regex you try to write, the pattern can become complex and difficult to debug or improve.Â
By validating user input, you can ensure that valid data is entered into your database. Moreover, it helps users enter accurate information as smoothly as possible while making as few mistakes as possible.Â
You can take advantage of the System.ComponentModel.DataAnnotations namespace to create client-side validations without too many lines of code. It contains attribute classes for validating user inputs, including email addresses.
Letâs start with the EmailAddress attribute.
We will start by creating a new .NET Core Web Application project. Then, we will add a simple form that allows a user to enter their name and email. We will also validate their email address.
Follow the simple steps below to create the new project:
Once youâve created the project, open Solution Explorer. You will see the structure of your project, as the following screenshot shows:
Letâs add a new class under the Models folder and name it ContactViewModel. Copy-paste the following code into the new class:
Notice that the above code requires the System.ComponentModel.DataAnnotations namespace. Also, see that the Email property has two validation attributes applied to it. Those are EmailAddress and Required attributes.
Under the Views/Home folder, look for the Index.cshtml file. Then, copy-paste the following code into the file:Â
Notice that below the Email textbox, we have a span element:
The element will display the error message âInvalid email address.â whenever an invalid email is entered.
At the bottom of the code, the script renders the _ValidationScriptsPartial file. If you expand the Shared folder, you will find a file named _ValidationScriptsPartial.cshtml there. Open it, and you will see that the validations specifically need these jQuery scripts:
Now, letâs run the project by clicking the âRunâ button in the toolbar. Try inputting several email addresses. When the code detects an email as invalid, it will display an error message under the Email text box, as the following image shows:
Form validation using EmailAddress attribute
The EmailAddressAttribute is quite useful for validating an email address. However, its purpose is just to prevent small typing mistakes. To make the result more reliable, you can add a RegularExpression attribute.
You can apply more than one validation attribute to a property in your model class. See the following code snippet as an example:Â
Modify your ContactViewModel class to use the above code for the Email property.Â
Now, rerun the code and see that the regex validation is also applied.
Form validation using RegularExpression attribute
From the above image, we can see that tony@example.com.au is considered invalid. This is because the regex attribute defines only email addresses with .com, .net, .org, and .gov. as valid.Â
Many external email solutions support integration with .NET code. To name just a few : SendGrid, GemBox.Email, Aspose.Email for .NET, EASendEmail, and many more.Â
Usually, they have their own methods to validate email addresses. Some of them even provide detailed results on the domain validation, mail server validation, and the existence of the email address itself. So, if youâre using an external library to send emails, you might want to utilize their validation methods.
Letâs now discuss these two libraries: Gembox.Email and EASendMail
GemBox.Email is a .NET component that allows you to read, write, receive, and send emails efficiently from your code using the POP, IMAP, SMTP, and EWS protocols.
GemBox.Emailâs features for email validations:
They provide methods that enable you to validate a single or a list of email addresses from your C# or VB.NET code.
You can install it by running the following command in the Package Manager Console:
See an example C# Console App code below that uses GemBox.Email to validate email addresses.Â
Hereâs the output of the above code.Â
You can see the different values returned by the method represent the results of the validation.Â
Note: The validation process can be affected by multiple factors, like DNS settings, firewalls, and ISP settings. After you run the code, you might see the validation result for the first email only. The rest might take longer, and some of them might return ServerConnectionError because it failed to connect to the GemBox server. In case your code doesnât work, and youâre unsure about what causes it, try to contact your IT Support (or maybe even the GemBox Support Team).Â
EASendMail offers support to work with email for various environments, including C#, VB.NET, Delphi, C++/CLI, and many others. They also support several protocols, such as SMTP, SSL, EWS, TLS, Live OAUTH, S/MIME, HTML, Gmail OAUTH, and many more.
You can install EASendMail in your .NET Framework project by entering the following command in the Package Manager Console:
To test if an email exists in the real world, they provide the TestRecipients method. See an example code below:
The above code shows how to use EASendMailâs TestRecipients method to validate an email address.Â
Use âTryItâ as the license code for evaluation use (it usually works for 1-2 months). If the license code is incorrect, youâll get an âInvalid License Codeâ exception. Also, note that you need to pass an empty string to the SmtpServer. Otherwise, you will be testing whether the specified SMTP server will accept the email address.
Hereâs the output of the above code:
The above result shows that the recipientâs email address does not exist. It suggests you double-check for typos and unnecessary spaces.
Note: Again, the validation process can be affected by multiple factors, like firewalls, DNS settings, and ISP settings. You will get a âconnection attempt failedâ error if it canât connect to the EASendMail server. In case your code doesnât work, and youâre unsure about what causes it, try to contact your IT Support (or maybe even GemBox Support Team).Â
Weâve explored several options to validate email addresses using C#. By doing email validation, you are one step further to reaching out to real customers.Â
The next thing to do is testing whether the emails are sent out as expected. However, when doing this kind of testing in Development and Staging environments, you might spam your real customers.
A solution you may want to try is using Mailtrap! Itâs a safe testing environment for emails sent from pre-production environments. By using Mailtrap, you donât need to worry that your testing emails will spam real users or flood your own inbox. How cool is that?!
That's it! Thank you for reading our guide on regular expression for email validation in C# that was originally published on Mailtrap Blog by Piotr Malek.
Join other developers and claim your FAUN account now!
Influence
Total Hits
Posts
Only registered users can post comments. Please, login or signup.