June 5, 2009

Send email using powershell

Sending an email in powershell is actually very easy using .NET. Here is how you would do it:


Set-PSDebug -Strict

# Create mail and set priority
$mail = new-object Net.Mail.MailMessage
$mail.Priority = [System.Net.Mail.MailPriority]::High

# Create from, to, and bcc
$mail.From = "test@test.com"
$mail.To.Add("test2@test2.com")
$mail.CC.Add("cc@test.com")
$mail.BCC.Add("bcc@test.com")

# Create the message
$mail.Subject = "Test Email from POSh" + " (" + [System.DateTime]::Now.ToString("yyyy-MM-dd HH:mm") + ")"
$mail.Body = "<b>Testing Application</b>"
$mail.IsBodyHtml = $true

# Set SMTP Server and create SMTP Client
$smtp = new-object Net.Mail.SmtpClient
$smtp.Host = "127.0.0.1"
$smtp.Port = "25"
$smtp.EnableSsl = $false

# Send message
try {
$smtp.Send($mail)
}
catch {
"Exception caught: {0}" -f $Error[0]
}

No comments:

Post a Comment