How To Send A Email Using Power Shell

Last week I have been installing a Oracle database on Windows 2012 R2. I like to send emails when start database event, shutdown and others. Of course, you can it from the database, but in this case I have prefered to try Power Shell, It is become a powerfull tool and direct competitor of Python.

First of all. How to kown wicht version have installed ?

 
PS C:\ANR_TEMPORARY\POWER> get-host

Name             : ConsoleHost
Version          : 4.0
InstanceId       : 1938a5ba-bb39-4f77-82a5-d81bbb7dfb2f
UI               : System.Management.Automation.Internal.Host.InternalHostUserInterface
CurrentCulture   : es-ES
CurrentUICulture : en-US
PrivateData      : Microsoft.PowerShell.ConsoleHost+ConsoleColorProxy
IsRunspacePushed : False
Runspace         : System.Management.Automation.Runspaces.LocalRunspace

The Version give us the current version, in this case is PowerShell 4.0, the last version (at 27.12.2016).

The first method to send a email is valid from PowerShell 1.0, please look at this code;

 
$smtp = New-Object Net.Mail.SmtpClient("smtp.server.com")
$smtp.Send("bbdd@mdb.com","anavarror@mydomain.es","Test Email","This is a test")

The second way, valid from PowerShell 2.0, is like show below;

 
$From = "bbdd@mdb.com"
$To = "anavarror@mydomain.es"
$Subject = "prueba 1"
$Body = "C.Q.D."
$SMTPServer = "smtp.server.com"
$SMTPPort = "25"
Send-MailMessage -From $From -to $To -Subject $Subject -Body $Body -SmtpServer $SMTPServer -port $SMTPPort  	

For both, save it in a file with ps1 extension and excute from PS console with ./<path_and_your_file_name>, an example;

 
PS C:\ANR_TEMPORARY\POWER> .\send_email.ps1

HTH – Antonio NAVARRO

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s