Josh-CO Dev

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

Powershell – Sending an Email

Leave a comment


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
#Params:
#$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 = "xxx.xxxxxxx.com"     

     #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 = "no-reply@noreply.com"
     $msg.ReplyTo = "no-reply@noreply.com"
     $msg.To.Add($to)
     $msg.subject = $subject
     $msg.body = $body

     #send the mail
     $smtp.Send($msg)
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s