1

How can you check for a valid email address in Powershell?

I've googled this and most people say to use $toadr = new-object net.mail.mailaddress($to) with a try/catch.

However this doesn't check for .com etc at the end of the email.

Eg. $toadr = new-object net.mail.mailaddress("test@mailcom")

doesn't throw an exception even though there is no dot before com.

David Klempfner
  • 7,367
  • 16
  • 55
  • 115

2 Answers2

4

I'd recommend using a regular expression.

Using a regular expression to validate an email address

$EmailRegex = '^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$';
if ('test@mailcom' -match $EmailRegex) {
    # Matched
}
else {
    # Did not match
}
Community
  • 1
  • 1
2

It's not always possible to know whether an email address is valid on just analyzing the format of the string itself. test@mailcom may infact be a valid email-address (you wouldn't know without a DNS query), and so MailAddress cannot presume it's invalid.

As some of the popular email regex validators actually invalidate some valid email addresses, I would not recommend going beyond MailAddress for validation.

Mr. Smith
  • 4,130
  • 6
  • 37
  • 78