pf-email.ps1
function Send-Email([string[]] $recipients, [string] $subject, [boolean] $usehtmlbody, [string] $body, [string[]] $attachments) { [string] $SMTPServer = "smtpserver" [string] $pathToZipExe = "C:\Program Files\7-zip\7z.exe" # Initialise the email. $mailmessage = New-Object system.net.mail.mailmessage $mailmessage.From = "smptuser@CORP.com" $mailmessage.Subject = $subject # Set the email body content (HTML or Plain Text). if ($usehtmlbody){ $mailmessage.IsBodyHtml = $true # When getting the contents of the system test report, the input is automatically delimitted by newline characters, which are not added again when sending the e-mail. # To get around this, each line is explicitly joined together by newline characters. # It is also encoded in UTF8 as that is what the HTML file is encoded in (in order to support non-ASCII characters). $mailmessage.Body = [string]::join("`r`n", (Get-Content -path $body -encoding UTF8)) # Set the encoding of the e-mail to UTF8 to correctly show non-ASCII characters too $mailmessage.BodyEncoding = $([system.text.encoding]::utf8) } else { $mailmessage.Body = $body } # Add all desired recipients. foreach ($recipient in $recipients){ $mailmessage.To.Add($recipient) } # Add all desired attachments. if ($null -ne $attachments){ foreach ($attachment in $attachments){ # Check the file exists. if (Test-Path($attachment)){ # Zip the file. $zipfile = "$attachment.zip" [Array]$arguments = "a", "-tzip", "$zipfile", "$attachment", "-r" & $pathToZipExe $arguments | Out-Null # Attach the file. $attachment = New-Object System.Net.Mail.Attachment($zipfile, 'text/plain') $mailmessage.Attachments.Add($attachment) } } } # Send the email. $SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer) try { $SMTPClient.Send($mailmessage) Write-Host "Email sent : $subject" } catch { [system.exception] Write-Warning "Email sending failed : $subject" Write-Warning $_ } finally { $mailmessage.Dispose() } } function Get-Email_AddressList { [CmdletBinding()] Param( [Parameter(ValueFromPipeline=$true, Mandatory=$true)] $value ) process{ $emailList = $value $emailList = $emailList -replace '"','' -replace '<','' -replace '>','' -split ' ' -split ';' $emailList = $emailList | Where-Object { $_.contains('@') } | Select-Object -Unique return $emailList } } function Test-Email_Address([string] $address) { # Try created an email address out of it - an exception is thrown if it is invalid try { $email = New-Object System.Net.Mail.MailAddress($address) $email | Out-Null return $true } catch { Write-Warning "$line is not a valid email address" return $false } } |