Josh-CO Dev

Solving the worlds problems one line of code at a time.

Leave a comment

Powershell – Sending an Email

Another task that I am commonly automating in Powershell is the sending of emails. As long as you have some SMTP credentials, this is relatively easy. Please note that I have removed any sensitive information.

#this function is responsible for all mail handling
#$to - the email address of the recipient
#$subject - the subject of the email
#$body - the body of the email
function sendMail($to, $subject, $body)
     Write-Host "Sending Email"

     #SMTP server name
     $smtpServer = ""     

     #Creating a Mail object
     $msg = new-object Net.Mail.MailMessage

     #Creating SMTP server object
     $smtp = new-object Net.Mail.SmtpClient($smtpServer)

     #Email structure
	 #all emails will come from the XXXXXX mailbox. 
     $msg.From = ""
     $msg.ReplyTo = ""
     $msg.subject = $subject
     $msg.body = $body

     #send the mail