Send Test Email using SMTP relay in PowerShell

If you work with web servers quite often, you might encounter a situation when a website hosted on Microsoft IIS server cannot send an email. In such situation, you might want to make sure if the web server can connect to SMTP server on specified SMTP ports (i.e. 25, 587, or 465). Nowadays, a lot of web hosts tend to block these well known SMTP ports for security. If you are configuring an on-premise web server for your client, you might want to test if their own firewall isn’t blocking the SMTP connection.

In this article, I will show you how you can create a PowerShell function which can help you send a test email using your username and password from PowerShell itself. Since you will be using your username and password for SMTP server, this method is purely legit and there is nothing wrong in this practice.

First of all, launch the Windows PowerShell console on your web server from where you are trying to and past the following code and hit enter:

function Send-TestEmail{
    [cmdletbinding()]
    Param (
    [Parameter(Mandatory=$true)]
        [String]$SMTPServer,
 
    [Parameter(Mandatory=$true)]    
        [String]$Username,

    [Parameter(Mandatory=$true)]    
        [String]$FromEmail,
            
    [Parameter(Mandatory=$true)]    
        [String]$ToEmail,

    [Parameter(Mandatory=$true)]    
        [int32]$Port
   )

   Process{

        $SecurePassword = Read-Host "Please type the password for $Username" -AsSecureString

        $Credentials = New-Object System.Management.Automation.PsCredential($Username, $SecurePassword)

        $Subject = "SMTP Server Test"

        $Body = "Hello, <br><br> This email message was sent to check the SMTP functionality. Please ignore this message.<br><br> Thank you!" 

try { 
Send-MailMessage -From $FromEmail -To $ToEmail -Subject $Subject -Body $Body -Priority High -SmtpServer $SMTPServer -Credential $Credentials -UseSsl -Port $Port -BodyAsHtml -ErrorAction Stop 

Write-Host "The test email was successfully sent. Please check the inbox of $ToEmail." -ForegroundColor Green 
} 

catch { Write-Host "Failed to send the email. Please make sure that the information entered is correct." -ForegroundColor Red } 

} 
}

If you don’t get any error after entering the above code, it means your Send-TestEmail function was successfully created and ready for use. Since this function is temporarily stored in current PowerShell console session, please don’t close this console.

Description

This function accepts five mandatory arguments like -SMTPServer,  -Username, -FromEmail, -ToEmail, and -Port which are self explanatory. Let me briefly explain the rest of the code:

$SecurePassword = Read-Host "Please type the password for $Username" -AsSecureString

The above line of code prompts the user to enter the password for SMTP user. This is a handy way to prevent requiring you to save the password in script itself. Saving the password in script can be pretty vulnerable.

$Credentials = New-Object System.Management.Automation.PsCredential($Username, $SecurePassword)

The above line of code creates a secure PsCredentials objects which temporarily stores the username and password securely in current PowerShell session.

The next two lines containing $Subject and $Body variables are also self-explanatory and only contains the subject and body of the test email message that will be sent. You can freely modify these fields as per your requirement.

Send-MailMessage -From $FromEmail -To $ToEmail -Subject $Subject -Body $Body -Priority High -SmtpServer $SMTPServer -Credential $Credentials -UseSsl -Port $Port -BodyAsHtml -ErrorAction Stop

The above line of code is the actual code which will send (or at least try to send) the test email using SMTP server and other information provided. If this code is able to send the email, you will see a green Success message otherwise you will see an Error.

Using the Send-TestEmail Function

Now that you understand how the function works, let me tell you how to use it by sending a test email. Please note that you need to keep the PowerShell console open after following the previous steps. In same same PowerShell console, copy the following command:

Send-TestEmail -SMTPServer 'smtp.sendgrid.net' -Username 'YourName' -FromEmail '[email protected]' -ToEmail '[email protected]' -Port 587

Make sure you change the values to match your own information. Now press the Enter button, you will be prompted to enter the password for username provided in -Username parameter. Just type your password and hit enter. If your server can connect to SMTP server and you have entered correct credentials, a test email will be sent.

Send-TestEmail

If the email could not be sent, you might have to contact your web host to allow the specific SMTP port. If the PowerShell function you just created can send the email but your website can’t, there is probably something wrong with the website’s code. So, you might have to contact the website developer to debug this further.

This PowerShell function may be useful for the server administrators for debugging the SMTP connectivity problems and the good thing about this function is that you can freely share this code with your friends since it doesn’t store any sensitive information like passwords.



Microsoft Certified | Cisco Certified