One of the most useful things I’ve found is using PowerShell to send an email… Doesn’t sound like much, but it provides power-users a nice “don’t worry, it’s done” email and everyone sleeps that little bit more soundly with some confirmation.
So lets hit the script then…
$msg = new-object System.Net.Mail.MailMessage $msg.From = new-object System.Net.Mail.MailAddress("Martyn@Developmentish.com") $msg.To.Add("Somebody@Someplace.com") $msg.Subject = "New Email" $msg.Body = "Look at this <b>TEXT</b>" $htmlView = [System.Net.Mail.AlternateView]::CreateAlternateViewFromString($msg.Body, "text/html") $msg.AlternateViews.Add($htmlView) $smtpClient = new-object System.Net.Mail.SmtpClient $smtpClient.Host = "MyEmailServer" $smtpClient.Port = 25 $smtpClient.Send($msg)
The more seasoned developer will point out that this script is using elements that are more common in .Net applications.
Why? Because PowerShell can!
Lets break it down…
Firstly we create a System.Net.Mail.MailMessage and bind it to the $msg variable.
Then we add a From, a To, a Subject and a body (notice the inclusion of HTML tags in the message).
We could just leave the $msg object as is, but the problem we have is that the body is in plain text… And our body contains HTML.
Here we create an “alternate view” from the message body converting text to HTML.
Then we add the alternate view to our $msg object.
Now comes the geeky part. We need to point our message code at an SMTP server… We create an SMTP client object… to this we declare the host (server) and the port (25 is default). Once we have this all set up, we use the SMTP Client to send our message object.
Once you’ve got the hang of it you can use it for things like error reporting when combined with the ole try catch method. Quick example below tries to get the contents of a folder, if it can’t it sends an email:
Try { Get-ChildItem "C:\SomePlace" } Catch { $msg = new-object System.Net.Mail.MailMessage $msg.From = new-object System.Net.Mail.MailAddress("Martyn@Developmentish.com") $msg.To.Add("Somebody@Someplace.com") $msg.Subject = "New Email" $msg.Body = "Look at this TEXT" $htmlView = [System.Net.Mail.AlternateView]::CreateAlternateViewFromString($msg.Body, "text/html") $msg.AlternateViews.Add($htmlView) $smtpClient = new-object System.Net.Mail.SmtpClient $smtpClient.Host = "MyEmailServer" $smtpClient.Port = 25 $smtpClient.Send($msg) }
Enjoy!