Monday, October 21, 2013

Poweshell Send-MailMessage, sending an e-mail in one line of code

In powershell 2.0 you would of had to write function to send an e-mail from powershell. Lucky for us in Powershell 3.0 it's

Poweshell 3.0 
Send-MailMessage -To $Mailto -From "XYZ@XYZ.com.au" -Subject "XYZ" -SmtpServer "XYZ" -Body "TEST" -Attachments XYZ.csv

Powershell 2.0
Sendmail
 function sendMail{
     Write-Host "Sending Email"
     #SMTP server name
     $smtpServer = "smtpXXXX"
     #Creating a Mail object
     $msg = new-object Net.Mail.MailMessage
     #Creating SMTP server object
     $smtp = new-object Net.Mail.SmtpClient($smtpServer)
     #Attachment
     $att = new-object Net.Mail.Attachment($OUTfile)
     #Email structure
     $msg.From="test@XYZ.com.au"
     $msg.ReplyTo ="test@XYZ.com.au"
     $msg.To.Add("XYZ.XYZ@XYZ.com.au")
     $msg.subject = "TEST"
     $msg.body = "This is the email Body."
     $msg.Attachments.add($att)
     #Sending email
     $smtp.Send($msg)
     $att.Dispose()

}
I like the Powershell 3.0 version better.


If you find this article useful please leave me a comment or click on an ad to show your support.

No comments :

Post a Comment