Powershell: an email sending script (or how to send mail in Windows via PowerShell)

Practice



Here is a little script that sends a letter to a recipient specified in its body, with a predefined subject and body text. For example, it can be used to automatically send emails in response to certain events.

mysendmail.ps1

$EmailFrom = "from@mydomain.com"
$EmailTo = "to@mydomain.com"
$Subject = "Subject text"
$Body = "This is a body of this message"
$SmtpServer = "mail.mydomain.com"
$smtp = New-Object net.mail.smtpclient($SmtpServer)
$smtp.Send($EmailFrom, $EmailTo, $Subject, $Body)


I think everything is clear from the text. In the variable "$SmtpServer", put the address of your SMTP server.

If you want to send emails from other scripts or on a schedule, you'll need to create one more file - a VBS file. The thing is that, for security reasons, PowerShell scripts can't just be run directly, but we can take a workaround - run a VisualBasic script that will in turn launch our desired PS1 script.

mysendmail.vbs

Set objShell = CreateObject("WScript.Shell")
objShell.Run("powershell.exe c:\my_path_to_script\mysendmail.ps1")

See also

  • [[b6841]]
  • [[b11166]]
  • [[b11329]]
  • [[b730]]
  • [[b8929]]
  • [[b11558]]
  • [[b5196]]
  • [[b11273]]
  • [[b6020]]
  • [[b11601]]
  • [[b11276]]
  • [[b11625]]
  • [[b11545]]
  • [[b11659]]
  • [[b11165]]
  • [[b4749]]
  • [[b11845]]
  • [[b6409]]
  • [[b5963]]
  • [[b4379]]

See also

Comments

To leave a comment

If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Lectures and tutorial on "Operating Systems and System Programming"

Terms: Operating Systems and System Programming