Sending an Email with PowerShell
I was working on some build automation scripts today adding email notification of the build results. Since our automation scripts use PowerShell this is what I would be using to send the email. This turned out to be really straight forward task using the SmtpClient Class.
Here is a quick example using smtpclient to send a simple email.
$emailFrom = "fromuser@domain.com"
$emailTo = "touser@domain.com"
$subject = "Subject"
$body = "Message body"
$smtpServer = "mail.domain.com"
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($emailFrom, $emailTo, $subject, $body)The SMTP server I was using to relay the messages also required authentication. So I had to set the Credentials property of the SmtpClient object.
$smtp.Credentials = new-object System.Net.NetworkCredential("senduser", "pass")
Now you may ask how to add multiple lines to the email. There are a few ways to do this, but since this is for use internally I wanted to keep it simple so I just pass carriage return/newline `r`n`r`n at the end of the lines I want to break at.
Here is an example passing sender credentials and a couple of lines in the email body.
$emailFrom = "fromuser@domain.com"
$emailTo = "touser@domain.com"
$subject = "Subject"
$body = "Message body`r`n`r`n"
$body += "2nd Line`r`n`r`n"
$body += "3rd Line"
$smtpServer = "mail.domain.com"
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$smtp.Credentials = new-object System.Net.NetworkCredential("senduser", "pass")
$smtp.Send($emailFrom, $emailTo, $subject, $body)



