Skip to the content.

Send email through SMTP and Powershell

<#  
.SYNOPSIS  
    Powershell script to send email
  
.PARAMETER smtpAddress 
    Address of the server: eg: smtp.example.com
      
.PARAMETER Port  
    port of the smtp server: eg: 25

.PARAMETER From
    User name of the account

.PARAMETER Password  
    password for the smtp server

.parameter ToAddress
	To address

.EXAMPLE  
    SendEmailTest -smtpAddress "smtp.example.com" -port 587 -from "testUser@example.com" -password "MySecurePassword" -to "testUser2@example.com"
#> 

param
(
	[parameter(Mandatory=$true)] 
	[string]$smtpAddress,
	
	[parameter(Mandatory=$true)] 
	[int]$Port,
	
	[parameter(Mandatory=$true)] 
	[string]$From,
	
	[parameter(Mandatory=$true)] 
	[string] $Password,

	[parameter(Mandatory=$true)]
	[string] $To
)

	 
function CreateMailAndSend
{
	[securestring]$secStringPassword = ConvertTo-SecureString $Password -AsPlainText -Force
	[pscredential]$EmailCredential = New-Object System.Management.Automation.PSCredential ($from, $secStringPassword)
	[string[]] $addresses =  @($to)

    [string]$emailBody = "Body of Test email"
    
    [string]$subject="Test Email"	

    Send-MailMessage -smtpserver $smtpAddress -Credential $EmailCredential -UseSsl -Port $port -from $from -to $addresses -subject $subject -body $emailBody 
}

CreateMailAndSend