Email.psm1

<#
.SYNOPSIS
    This function verifies if an email address follows a valid pattern.
.PARAMETER emailAddress
    The email address to verify.
.EXAMPLE
    Test-EmailAddressValidity -EmailAddress "mailbox@domain.com"
#>

function Test-EmailAddressValidity {
    param (
        # The email address to verify
        [Parameter(Mandatory=$true)]
        [String]$emailAddress
    )

    # Check for null/whitespce
    if ([String]::IsNullOrWhiteSpace($emailAddress)) {
        return $false
    }

    # Try to cast to MailAddress type
    try {
        $null = [MailAddress]$emailAddress
        return $true
    }

    # Exception means email is not valid
    catch {
        return $false
    }
}

<#
.SYNOPSIS
    This function verifies if a domain name follows a valid pattern.
#>

function Test-DomainValidity {
    param (
        # The domain to verify
        [Parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [String]$domain
    )

    # Check against basic regex
    return [Regex]::New("^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$").IsMatch($domain)
}

<#
.SYNOPSIS
    This function extracts the domain portion of an email address.
.DESCRIPTION
    This function extracts the domain portion of an email address.
    The domain is the portion of the email after the '@' character.
    If the email is invalid, null is returned.
.PARAMETER emailAddress
    The email address which the domain will be extracted from.
.EXAMPLE
    Get-EmailAddressDomain -EmailAddress "mailbox@domain.com"
#>

function Get-EmailAddressDomain {
    param (
        # The email address which the domain will be extracted from.
        [Parameter(Mandatory=$true)]
        [String]$emailAddress
    )

    # Check email validity
    if (!(Test-EmailAddressValidity -EmailAddress $emailAddress)) {
        return $null
    }

    # Extract domain
    return $emailAddress.Remove(0, $emailAddress.IndexOf('@') + 1)
}

<#
.SYNOPSIS
    This function extracts the username portion of an email address.
.DESCRIPTION
    This function extracts the username portion of an email address.
    The domain is the portion of the email before the '@' character.
    If the email is invalid, null is returned.
.PARAMETER emailAddress
    The email address which the username will be extracted from.
.EXAMPLE
    Get-EmailAddressUsername -EmailAddress "mailbox@domain.com"
#>

function Get-EmailAddressUsername {
    param (
        # The email address which the domain will be extracted from.
        [Parameter(Mandatory=$true)]
        [String]$emailAddress
    )

    # Check email validity
    if (!(Test-EmailAddressValidity -EmailAddress $emailAddress)) {
        return $null
    }

    # Extract domain
    return $emailAddress.Substring(0, $emailAddress.IndexOf('@'))
}