Script repository

Check suffixes of email addresses being added

Updated on: Jan 18, 2026, Views: 4566

Exchange

The script checks whether email addresses added to a mailbox belong to accepted domains in Exchange. If not, the operation is canceled. To execute the script, create a business rule triggering Before modifying Exchange properties of a user.

In the script, the $exchangeServer variable specifies the fully-qualified domain name or IP address of the Exchange server.

$exchangeServer = "exchangeserver.domain.com" # TODO: modify me

function VerifyMailAddress ($emailAddress, $acceptedDomainNames, [ref]$needCancelOperation)
{
    # Get domain part of the email address.
    $emailAddress = $emailAddress.ToString()
    
    $emailAddressDomainPart = $emailAddress.SubString($emailAddress.IndexOf("@") + 1)
    
    # Verify domain part.
    foreach ($domainName in $acceptedDomainNames)
    {
        if ($emailAddressDomainPart -eq $domainName)
        {
            return
        }
    }
    
    $Context.LogMessage("Email address '$emailAddress' not allowed" , "Error") # TODO: modify me
    $needCancelOperation.Value = $True
    return
}

try
{
    # Get all accepted domains.
    $session = New-PSSession -connectionURI "http://$exchangeServer/powershell" -ConfigurationName Microsoft.Exchange -Authentication Kerberos
    Import-PSSession -session $session
    $acceptedDomains = Get-AcceptedDomain | Where {$_.Name -like "%adm-ParentName%*"}
}
finally
{
    Remove-PSSession -Session $session
}

# Exit the script if no accepted domains found.
if ($acceptedDomains -eq $NULL)
{
    $Context.LogMessage("No accepted domains found for %cn%", "Warning") # TODO: modify me
    return
}

$acceptedDomainNames = @()
foreach ($domain in $acceptedDomains)
{
    $acceptedDomainNames += $domain.DomainName.ToString()
}

# Get email addresses.
$mailParams = $Context.Action.MailParameters
$emailAddresses = $mailParams.EmailAddresses
$needCancelOperation = $False
$operation = "ADS_PROPERTY_NONE"
for ($i = 0; $i -lt $emailAddresses.Count; $i++)
{
    $emailAddress = $emailAddresses.GetAddress($i, [ref]$operation)

    # Verify email addresses.
    if ($emailAddress.OverrideOldValues)
    {
        VerifyMailAddress $emailAddress $acceptedDomainNames ([ref]$needCancelOperation)
    }
    elseif (!($emailAddress.OverrideOldValues) -and ($operation -eq "ADS_PROPERTY_APPEND"))
    {
        VerifyMailAddress $emailAddress $acceptedDomainNames ([ref]$needCancelOperation)
    }
}

# Cancel operation if there any invalid email addresses.
if ($needCancelOperation)
{
    $Context.Cancel("You are trying to add invalid email addresses.")
}

Comments 0

You must be signed in to comment.

    Got questions?

    Support Questions & Answers

    We use cookies to improve your experience.
    By your continued use of this site you accept such use.
    For more details please see our privacy policy and cookies policy.