Send eMail and SMS Text Messages with PowerShell
Thanks to the .NET library sending emails with PowerShell is surprisingly very simple! One thing to remember is line breaks, when you need a new line, make sure to use the escape characters `n . In the first example, I’ll send just a regular email, in the second I’ll send a SMS text message.
1 2 3 4 5 6 7 8 9 | $emailFrom = "sender@example.com" $emailTo = "recipient@example.com" $subject = "Subject" $body = "This is my automated email`nThis is line number 2" $smtpServer = "localhost" $smtp = new-object Net.Mail.SmtpClient($smtpServer) $smtp.Send($emailFrom, $emailTo, $subject, $body) |
Now let’s send a SMS text massage alert, in this message we will include how much free space we have on our C: drive. Most cell carriers limit text messages to 160 characters, so we want to keep them as short and useful as possible. Check the list below to see see what the email address of your phone is and make sure to replace the $to variable.
1 2 3 4 5 6 7 8 9 10 11 12 | $freeSpace = gwmi win32_logicaldisk -filter "DeviceID=`"C:`"" | % { $_.freespace/1GB } $freeSpace = [System.Math]::round($FreeSpace,2) $from = "from@example.com" $to = "1234567890@example.com" $subject = "" $body = "C: free space is " + $freeSpace + " GB" $smtpServer = "localhost" $smtp = New-Object Net.Mail.SmtpClient($smtpServer) $smtp.Send($from, $to, $subject, $body) |
Now we need to figure out what email address to use so that we can send the SMS address, below are a few examples for several US carriers. Make sure to replace 1234567890 with your ten digit phone number.
Alltel
1234567890@message.alltel.com
AT&T
1234567890@txt.att.net
Boost Mobile
1234567890@myboostmobile.com
MetroPCS
1234567890@mymetropcs.com
Nextel
1234567890@messaging.nextel.com
Sprint PCS
1234567890@messaging.sprintpcs.com
T-Mobile
1234567890@tmomail.net
Verizon
1234567890@vtext.com
Virgin Mobile
1234567890@vmobl.com