Use Regular Expressions to Validate Email Addresses
Before you send email by using the API, use regular expressions (regex) to perform basic validation of the email addresses of your subscribers. This basic test helps reduce the number of messages you send to email addresses that aren’t valid.
Regex is a fast but basic method of detecting invalid email addresses. Don’t use it as your only method of detecting invalid addresses.
This regular expression performs two simple but essential checks:
- Verifies that the address contains only one @ character.
- Verifies that the address contains a domain and a top-level domain (TLD). The address can also include subdomains.
Remove email addresses that fail this basic validation from your lists.
After you remove the addresses that fail the basic regex validation, it’s a good idea to use an email validation library to test the remaining addresses.
Most programming languages have several packages that you can use to validate email addresses, and some even include built-in classes that handle this process. Examples of these validation packages include:
- .NET: MailAddress class
- Java: EmailValidator class
- Python: email-validator library
- JavaScript: email-addresses package