Quick function to send an HTML email with attachments from PowerShell
Notes:
- $to = array of strings containing one or more email addresses
- $cc = array of string(s) containing zero or more email addresses
- $subj = string
- $body = email message with (optional) HTML formatting
- $file1 = path to a file (global variable – not passed in the function call)
- $file2 =same as $file1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | function Send_Email ($to, $cc, $subj, $body) { $addr_from = new-object System.Net.Mail.MailAddress("noreply@mydomain.com") $mailmsg = new-object system.net.mail.mailmessage $mailmsg.Subject = $subj $mailmsg.IsBodyHtml = $true $mailmsg.Body = $body $mailmsg.Sender = $Sender $mailmsg.From = $addr_from foreach ($addr in $to) { $addr = $addr.trim() write-host "Sending to: $addr" $a = new-object System.Net.Mail.MailAddress($addr) $mailmsg.To.add($a) } foreach ($addr in $cc) { $addr = $addr.trim() if ($addr -ne "") { write-host "CCing to: $addr" $a = new-object System.Net.Mail.MailAddress($addr) $mailmsg.CC.add($a) } } #temporary BCC to monitor for errors $a = new-object System.Net.Mail.MailAddress("me@mydomain.com") $mailmsg.BCC.add($a) $mailmsg.Attachments.add($file1) $mailmsg.Attachments.add($file2) $smtpServer = "internal-mail-router.myorg.com" $smtp = new-object System.Net.Mail.SmtpClient($smtpServer) $smtp.Send($mailmsg) } |
Posted by xb90 at 3:07 pm Tagged with: PowerShell send html email attachments
Recent Comments