Posted On July 14, 2020

Using Telnet and PowerShell to Test SMTP Relay

kimconnect 0 comments
blog.KimConnect.com >> Codes >> Using Telnet and PowerShell to Test SMTP Relay
PowerShell Method:

Example of Failure:

PS C:\> sendTestEmail '[email protected]' 'password' '[email protected]'
Detected MX Record : ywpjf4z5siycosmh7uqymtuygcjehuc67wa6o4rq4k2a3g2aodma.mx-verification.google.com
Known SMTP Server : smtp.gmail.com
Secure SMTP Parameters detected.
WARNING: Error: email has NOT been sent.
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0
Authentication Required. Learn more at
False

Example of Success:

PS C:\> sendTestEmail '[email protected]' 'password' '[email protected]'
Detected MX Record : aspmx.l.google.com
Known SMTP Server : smtp.gmail.com
Secure SMTP Parameters detected.
Email has been sent to [email protected] successfully
True

Example of Google Gmail disallowing Unsecured App:

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0
Authentication Required.

Resolution for the Gmail Issue:

Enable less secure apps at: https://accounts.google.com/v3/signin/identifier?continue=https%3A%2F%2Fmyaccount.google.com%2Flesssecureapps%3Fpli%3D1&emr=1&followup=https%3A%2F%2Fmyaccount.google.com%2Flesssecureapps%3Fpli%3D1&ifkv=ARpgrqdaqxGyEtVgZROzKVBlclclzD4gnvr6dtjGTxrjKVYws5T5r-JwOcpQ86JQN-VvE6gX8A8H&mrp=security&osid=1&passive=1209600&rart=ANgoxcf6M_kJxxwM416Kc_oowXkiFn5uEj6KbYtLU5ZI9b6O2SEHMzHHeSq4_6yB-tShxhkuUp-CF8JvZs7__3jmshZHWrO9s04poFcEyws9X61wEgJd8Uc&service=accountsettings&flowName=GlifWebSignIn&flowEntry=ServiceLogin&dsh=S154145929%3A1728050781152957&ddm=0

Note: This setting is hidden if the organization’s administrator has locked less secure app account access feature

# This version has been deprecated by https://blog.kimconnect.com/powershell-script-to-send-emails/

$emailFrom="[email protected]"
$emailTo="[email protected]"
$cc=$null
$emailPassword="PASSWORD"
$subject="Test Email to Validate SMTP"
$body="This is a test email.<br><br>Please disregard"
$port=587
$encryptedPass=ConvertTo-SecureString -String $emailPassword -AsPlainText -Force
$emailCred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $emailAccount,$encryptedPass

function sendTestEmail{
    [CmdletBinding()]
    param(
    [Parameter(Mandatory)]$emailFrom,
    [Parameter(Mandatory)]$emailPassword,
    [Parameter(Mandatory)]$emailTo,    
    [Parameter(Mandatory=$false)]$cc,
    [Parameter(Mandatory=$false)]$subject="Test Email to Validate SMTP",
    [Parameter(Mandatory=$false)]$body="This is a test email.<br><br>Please disregard",
    [Parameter(Mandatory=$false)]$smtpServer=$null,
    [Parameter(Mandatory=$false)]$port=587
    )

    $encryptedPass=ConvertTo-SecureString -String $emailPassword -AsPlainText -Force
    $emailCred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $emailFrom,$encryptedPass

    function getMxRecord($emailAddress){
        $regexDomain="\@(.*)$"
        $domain=.{[void]($emailAddress -match $regexDomain);$matches[1]}
        $mxDomain=.{$result=(resolve-dnsname $domain -type mx).NameExchange
                    if ($result.gettype() -eq [String]){return $result}else{return $result[0]}}
        $smtpServer= switch -Wildcard ($mxDomain){ # need to build up this list
                            "*outlook.com" {"smtp.office365.com";break}
                            "*google.com" {"smtp.gmail.com";break}
                            "*yahoodns.net" {'smtp.mail.yahoo.com';break}
                            "*inbox.com" {'my.inbox.com;break'}
                            "*mail.com" {'smtp.mail.com';break}
                            "*icloud.com" {'smtp.mail.me.com';break}
                            "*zoho.com" {'smtp.zoho.com';break}
                            default {$mxDomain}
                        }
        if($mxDomain){
            write-host "Detected MX Record`t: $mxDomain`r`nKnown SMTP Server`t: $smtpServer"
            return $smtpServer
            }
        else{
            write-warning "MX record not available for $emailAddress"
            return $null
            }
    }
    
    $detectedSmtpServer=getMxRecord $emailFrom
    $smtpServer=if($smtpServer -ne $null -and $smtpServer -eq $detectedSmtpServer){
                    $smtpServer
                }elseif($smtpServer -ne $null -and $smtpServer -ne $detectedSmtpServer){
                    write-warning "Detected SMTP server $detectedSmtpServer does not match provided value $smtpServer"
                    $detectedSmtpServer
                }else{
                    $detectedSmtpServer
                    }
    
    $secureSmtpParams = @{        
        From                       = $emailFrom
        To                         = $emailTo
        cc                         = if($cc){$cc}else{$emailFrom}
        Subject                    = $subject
        Body                       = $body
        BodyAsHtml                 = $true
        DeliveryNotificationOption = 'OnFailure','OnSuccess'
        SmtpServer                 = $smtpServer
        Port                       = $port
        UseSSL                     = $true
        Credential                 = $emailCred
    }

    $relaySmtpParams=@{
        From                       = $emailFrom
        To                         = $emailTo
        Subject                    = $subject
        Body                       = $body
        BodyAsHtml                 = $true
        DeliveryNotificationOption = 'OnFailure', 'OnSuccess'
        SmtpServer                 = $smtpServer
        Port                       = 25
    }

    if ($port -ne 25){
        write-host "Secure SMTP Parameters detected."
        $emailParams=$secureSmtpParams
        }else{
            write-host "Unsecured SMTP Parameters detected."
            $emailParams=$relaySmtpParams
            }

    try{
        Send-MailMessage @emailParams -ErrorAction Stop
        write-host "Email has been sent to $emailTo successfully"
        return $true;
        }
    catch{
        $errorMessage = $_.Exception.Message
        $failedItem = $_.Exception.ItemName
        write-warning "Error: email has NOT been sent.`r`n$errorMessage`r`n$failedItem"
        return $false
        }

}
Telnet (old-school) Method:

Step 1: Get the Relay FQDN or IP of the target domain

PS C:\Windows\system32> nslookup
Default Server: dc1.kimconnect.net
Address: 192.168.0.21

> set type=mx
> contoso.com
Server: dc1.kimconnect.net
Address: 192.168.0.21

Non-authoritative answer:
contoso.com MX preference = 10, mail exchanger = mx1-us2.contoso.com
contoso.com MX preference = 10, mail exchanger = mx2-us2.contoso.com

mx1-us2.contoso.com internet address = 1.1.1.1
mx1-us2.contoso.com internet address = 2.2.2.2
mx2-us2.contoso.com internet address = 3.3.3.3
mx2-us2.contoso.com internet address = 4.4.4.4
> exit

Step 2: Test SMTP relay using Telnet

SET localecho
OPEN mx1-us2.contoso.com 25
EHLO contoso.com
MAIL FROM:<[email protected]>
RCPT TO:<[email protected]>
DATA
Subject: Test SMTP Relay
Testing...
.
QUIT

Example of source IP being blocked:

EHLO yomama.com 421 4.3.2 No system resources. Please provide the following IP address when reporting problems: x.x.x.x

Leave a Reply

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

Related Post

PowerShell: Scan a Subnet for Used and Unused IPs

A newer version of this script is available here. function scanForAvailableIPs{ param( $cidrBlock=$( $interfaceIndex=(Get-WmiObject -Class…

Python: Package Installer for Python (PIP)

This comes preinstalled with Python 3.4 or higher. Similar to the Microsoft PowerShell Gallery, Python.org…

How to Install Selenium for Python on Windows or Linux

Windows # This error would occur if pip is not up to date PS C:\WINDOWS\system32>…
Other project: DragonCoin.com