Send an email via SMTP

PeterGPeterG Posts: 61 Silver 3
This script sends an email using SMTP using Powershell's built in mail cmdlet, by default this won't stop a deployment if it fails.
The emailUser must have permission to send from the given address
# Inputs:
# REQUIRED
# $smtpServer = smtp.example.com
# $emailFrom = user00@example.com
# $emailTo = user01@example.com, User2 <user02@example.com>
# $emailUser = example.com\user00
# $emailPassword = password
#
# Optional
# $emailSubject
# $emailCC = user01@example.com, User2 <user02@example.com>
# $emailBCC = user01@example.com, User2 <user02@example.com>
# $emailAttachements = foo.txt, bar.jpg
# $emailBody = Hello World

# For more information visit:
# http://technet.microsoft.com/en-us/library/hh849925.aspx

# $emailUser & $emailPassword are not needed if the agent service is running
# as a user who has permission to send email from $emailFrom

# Turn comma seperated list into Array
function splitString([string]$addresses){
	return $addresses.split(",") | foreach { $_.trim() }
}

# Accumulate any errors for required parameters
$errors = ""
if ($null -eq $smtpServer) {
	$errors = $errors + ", smtpServer"
}
if ($null -eq $emailFrom) {
	$errors = $errors + ", emailFrom"
}
if ($null -eq $emailTo) {
	$errors = $errors + ", emailTo"
}
if ($null -eq $emailUser) {
	$errors = $errors + ", emailUser"
}
if ($null -eq $emailPassword) {
	$errors = $errors + ", emailPassword"
}

if (0 -ne $errors.length) {
# Write a warning, stop execution but don't stop deployment
	Write-Warning ($errors.trim(", ") + " must be set to send emails")
	return
# Throw an error and stop deployment
#	Throw ($errors.trim(", ") + " must be set to send emails")
}

$secpasswd = ConvertTo-SecureString $emailPassword -AsPlainText -Force
$credentials = New-Object System.Management.Automation.PSCredential `
              ($emailUser, $secpasswd)

$parameters = @{
	SmtpServer = $smtpServer
	From = $emailFrom
	To = splitString($emailTo)
	Subject = if ($null -eq $emailSubject) { "" } else { $emailSubject}
        Credential = $credentials
}

# Add any defined optional parameters
if ($null -ne $emailCC) {
	$cc = splitString($emailCC)
	$parameters.Add("CC", $cc)
}
if ($null -ne $emailBCC) {
	$bcc = splitString($emailBCC)
	$parameters.Add("BCC", $bcc)
}
if ($null -ne $emailAttachments) {
	$attachments = splitString($emailAttachments)
	$parameters.Add("Attachments", $attachments)
}
if ($null -ne $emailBody) {
	$parameters.Add("Body", $emailBody)
# If you want to use Html in the body use BodyAsHTML
#	$parameters.Add("BodyAsHTML", $emailBody)
}

# And finally send the e-mail
try {
	Send-MailMessage @parameters
	"e-mail sent"
} catch {
	Write-Warning $_.ErrorDetails
}
# If deployment should fail don't use the try catch
Peter Gerrard

Software Engineer
Redgate Software
Sign In or Register to comment.