Sending emails is crucial to most scripts and of course all those
damn reports they want done everyday.
When using an Exchange EDGE server be sure to whitelist your script server
so you can send without issues. On the Receive connector in exchange management
GUI you find the ip whitelist.
Keywords:
SMTP Authentication Credentials Powershell Attachment Password Html Email
Example with authentication:
Source
#EMail Example
$smtp = new-object Net.Mail.SmtpClient("mailrelay.yourdomain1.com") #Dns name or IP
#Auth Stuff
$smtpuser = new-object System.Net.networkCredential
$smtpuser.domain = "mydomain" #Only needed if you have a domain
$smtpuser.username = "myusername"
$smtpuser.password = "mypassword"
$smtp.Credentials = $smtpuser
$smtp.Send("myaccount@email.edu", "someone@gmail.com", "PowerShell Email", "This is a email from powershell")
Example without authentication:
Source
#EMail Example
$smtp = new-object Net.Mail.SmtpClient("mailrelay.yourdomain1.com") #Dns name or IP
$smtp.Send("myaccount@email.edu", "someone@gmail.com", "PowerShell Email", "This is a email from powershell")
Example html with attachment option:
I use a function as it's simpler to copy between scripts and also a good example of its in use.. Though emailing
a html version of a directory dump isn't all to high tech lol. The lines for Attachments and IsBodyhtml are optional and
can be commented out if you don't wish to use them thou html you'll probably use it a lot as it's as answer to 2 problems.
It displays things in readable/pretty form immediately when a email is opened, and can be cut and pasted directly into excel for
sorting and what not.
Source
function do_mail ($myhtml) {
$attachmentpathandfilename = "C:\windows\WindowsUpdate.log"
$mymail = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient("mailrelay.yourdomain1.com") #Dns name or IP
$mymail.IsBodyHTML = $true
$mymail.From = "ServerReporting@Company.edu"
$mymail.To.Add("sysadmins@company.edu")
$mymail.Subject = ("My Html email example")
$mymail.Body = $myhtml
$mymail.Attachments.Add($attachmentpathandfilename)
$smtp.Send($mymail)
} #do_mail
$head = "<style>"
$head = $head + "BODY{background-color:#9FAEB5;}"
$head = $head + "TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}"
$head = $head + "TH{border-width: 1px;padding: 0px;border-style: solid;border-color: black;background-color:#999999}"
$head = $head + "TD{border-width: 1px;padding: 0px;border-style: solid;border-color: black;background-color:#CCCCCC}"
$head = $head + "</style>"
$myhtml = Get-childitem | select name, FullName, length | ConvertTo-HTML -head $head -body ("<H2>My Example Html email</H2>")
do_mail $myhtml