Perfect Email Address Validation In PowerShell

PowerShell Technique: Perfect Email Address Validation

Featured Programming Tips and Tricks Tips-And-Tricks

 

Implementing Email address format validation is pretty common and simple. Regardless of the technology or platform, it is usually accomplished through the use of regular expression. But in this little article we’ll proceed a couple of steps further by

  • getting the mail server
  • pinging the server to verify if its live and accessible.

Windows PowerShell ISE (Integrated Scripting Environment) is an editor and development environment specifically designed for writing, testing, and debugging PowerShell scripts. It provides a user-friendly interface for working with PowerShell, making it easier to create and run scripts, especially for beginners or those who want a more visual experience compared to the regular PowerShell console.

Now let’s get our feet a little wet by doing some coding in our favorite PowerShell editor.

Open Window PowerShell ISE. Create a scripting file namely EmailValidator.ps1. Copy and paste the following code in it.

function Get-ValidateEmail {

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)][ValidateNotNull()]
        [string]$EmailAddr       
    )
    

    $Regex = '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'

    if (($EmailAddr -match $Regex) -eq $true) {
        Write-Host ("{0} is formatted correctly." -f $EmailAddr)
    }else{
        Write-Host ("{0} is not formatted correctly." -f $EmailAddr)  
        return;
    }


    $mx = (Resolve-DnsName -Name $EmailAddr.Split('@')[1] -Type MX -ErrorAction Stop).NameExchange | Select-Object -First 1

    if ($null -ne $mx) {
        $EmailServer = ($mx -split ',')[0]
        Write-Host ("{0} is the valid email server." -f $EmailServer)    

        $PingReply = Test-NetConnection $mx
        Write-Host("IP address of " +$EmailServer+ " is " +$PingReply.RemoteAddress.IPAddressToString)

    }else{ 

        Write-Host ("Couldn't find a valid email server for the provided email address.")    
        return;
    }
}

This little program does several things but in a pretty simple manner.

  • Creates our own custom Get cmd-let, Get-ValidateEmail
  • Allows a parameter under [CmdletBinding()] attribute. The parameter EmailAddr is declared to be mandatory and not null.
  • $Regex = ‘^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$’ defines the familiar regular expression to match the given email address to validate email format.
  • $mx = (Resolve-DnsName -Name $EmailAddr.Split(‘@’)[1] -Type MX -ErrorAction Stop).NameExchange | Select-Object -First 1
    line is pretty significant. It parses EmailAddr to get the domain part to resolve the DNS name by making an MX query to Resolve-DnsName cmd-let.
  • And finally $PingReply = Test-NetConnection $mx sends a PING request to the mail server designated by $mx. The familiar PING command validates if the specified mail server is live and accessible.

Save the script. You’re done with your PowerShell script. Now is the time to run this script.

If you’re using Window PowerShell editor in its default layout, you can see another little section with blue background, right below the editor. That’s built in PowerShell console where you can run your PowerShell script you just created and other PowerShell commands.

Click on that console window and before proceeding to execute your script you need to do one thing as a pre-requisite in order to set execution policy to enable local script to run by PowerShell command prompt:

Set-ExecutionPolicy -Scope Process -ExecutionPolicy ByPass

then respond with Y to set it for the current session.

Your’re done. Now type in this to dot-source your script:

. F:\PowerShell\EmailValidator.ps1

Of course you may have to specify your own script file path.

Dot-sourcing in PowerShell is a technique used to make the content of a script (such as functions, variables, and aliases) available in the current session instead of running the script in a new, isolated scope. This is particularly useful when you want to load reusable functions or variables from a script file into your current PowerShell environment.

PowerShell will reply nothing in return, means there was no issue. Now invoke your custom cmd-let Get-ValidateEmail like the following:

Get-ValidateEmail -EmailAddr “somebody@yahoo.com”

The mail address should be a valid email address. If the provided EmailAddr is correct the response will be something like:

somebody@yahoo.com is formatted correctly.
mta7.am0.yahoodns.net is the valid email server.
IP address of mta7.am0.yahoodns.net is 98.136.96.77

Leave a Reply

Your email address will not be published. Required fields are marked *