Send Email with PowerShell

The following script allows to send an email in HTML using SMTP with PowerShell.

The script does not prompt for credentials (the user account and its according password are set into the script itself). To avoid writing user account and password in the script, Get-Credentials can be used to prompt the user for username and password.

 

##*===============================================
##* SET VARIABLES
##*===============================================

$Exchange_Host = "owa.dbsnet.com"
$Exchange_User = "dam.dbs"
$Exchange_Pass = "xxxxxxxx"
$From_User = "dam.dbs@dbsnet.com"
$To_User = "receiver@dbsnet.com"
$Mail_Subject = "Test email powered by PowerShell"

$Mail_Body = @"
    <style type="text/css">
	    .texte_gris12 { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12px; font-style: normal;  color: #3F3F3F}
    </style>

    <table border="0" cellspacing="0" cellpadding="0" width="100%">
	    <tr>
		    <td class="texte_gris12">This is an email in HTML sent using a <b>PowerShell</b> script</td>
	    </tr>
    </table>
	
    &nbsp;<br>
    &nbsp;<br>
"@



##*===============================================
##* EMAILING FUNCTION
##*===============================================

function Send_HTML_Email{
	trap{return 1}
	$message = New-Object System.Net.Mail.MailMessage $From_User, $To_User
	$message.Subject = $Mail_Subject
	$message.IsBodyHTML = $true
	$message.Body = $Mail_Body
	$smtp_client = New-Object system.Net.Mail.SmtpClient
	$smtp_client.Host = $Exchange_Host
	$credentials = New-Object system.Net.NetworkCredential
	$credentials.UserName = $Exchange_User
	$credentials.Password = $Exchange_Pass
	$smtp_client.Credentials = $credentials
	$smtp_client.send($message)
	return 0
}



##*===============================================
##* CALL EMAILING FUNCTION
##*===============================================

Send_HTML_Email