#################################################################################################### # SendMail with Example # Version 1.0.0 # July 27, 2010 # Copyright (C) 2010 Johan Cyprich. All rights reserved. # # Minimum Requirements: PowerShell 2.0 # Licence: released under GPL 3: http://www.gnu.org/licenses/gpl.html. #################################################################################################### function SendMail ([string] $sHost, [string] $sFrom, [string] $sTo, [string] $sSubject, [string] $sMessage, [string] $sUserName, [string] $sPassword) #################################################################################################### # PURPOSE: # Sends an e-mail to an SMTP server. It will also authenticate to the server if a user name and # password are sent to the function. If authentication is not used, leave $sUserName and $sPassowrd # blank, i.e. ''. # # PARAMETERS: # $sHost (in) - host name of mail server # $sFrom (in) - e-mail address of mail sender # $sTo (in) - e-mail address of mail recipient # $sSubject (in) - subject title of message # $sMessage (in) - message sent to recipient # $sUserName (in) - user name for authentication # $sPassword (in) - password for authentication # # RETURN: # True - mail was sent succesfully # False - mail was not sent #################################################################################################### { [bool] $bSuccess = 1 # was mail sent without problems? $SmtpClient = new-object system.net.mail.smtpClient $smtpclient.Host = $sHost # Authenticate only if a user name and password are set. if (($sUsername -ne '') -band ($sPassword -ne '')) { $Credentials = new-object System.Net.networkCredential $Credentials.domain = "" $Credentials.UserName = $sUserName $Credentials.Password = $sPassword $SMTPClient.Credentials = $Credentials } # if (($sUsername -ne '') -band ($sPassword -ne '')) # Send the mail. try { $smtpclient.Send($sFrom, $sTo, $sSubject, $sMessage) } catch { $bSuccess = 0 } $bSuccess } # SendMail #################################################################################################### # Main. #################################################################################################### $bSent = SendMail 'smtp.mail.com' 'sender@website.com' 'recipient@website.com' 'Test' 'This is a test.' 'sender@website.com' 'abc123' if ($bSent) { "Mail sent successfully." } else { "Mail not sent." }