Created
December 25, 2018 08:04
-
-
Save krymtkts/71d40a23ef4bb3816af9608e59c0f1d3 to your computer and use it in GitHub Desktop.
send mail message instead of `Send-MailMessage`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<# | |
.SYNOPSIS | |
Send-Mail | |
.DESCRIPTION | |
Send mail message. use this instead of Send-MailMessage. | |
not supported pileline. | |
#> | |
function global:Send-MailMessage2 { | |
Param ( | |
[Parameter(Mandatory = $True)][string]$smtpserver, | |
[Parameter(Mandatory = $True)][int]$port, | |
[Parameter(Mandatory = $True)][string]$userName, | |
[Parameter(Mandatory = $True)][string]$password, | |
[Parameter(Mandatory = $True)][string]$from, | |
[Parameter(Mandatory = $True)][string[]]$tos, | |
[string[]]$ccs, | |
[Parameter(Mandatory = $True)][string]$subject, | |
[string]$body | |
) | |
$smtp = New-Object Net.Mail.SmtpClient($smtpserver, $port) | |
$smtp.Credentials = New-Object System.Net.NetworkCredential($userName, $password, $smtpserver) | |
$email = New-Object System.Net.Mail.Mailmessage | |
$email.Subject = $subject | |
$email.Body = $body | |
$email.IsBodyHTML = $true | |
$email.From = $from | |
foreach ($to in $tos) { | |
$email.To.Add($to) | |
} | |
if ($ccs -ne $null) { | |
foreach ($cc in $ccs) { | |
$email.CC.Add($cc) | |
} | |
} | |
$email.BCC.Add($from) | |
try { | |
$smtp.Send($email) | |
Write-Output "Success." | |
Write-Output ("FROM: " + $email.From) | |
Write-Output ("TO: " + $email.To) | |
Write-Output ("CC: " + $email.CC) | |
Write-Output ("Subject: " + $email.Subject) | |
} | |
catch [System.Net.Mail.SmtpFailedRecipientsException] { | |
Write-Error "Cannot deliver the message to any of MailMessage.To, MailMessage.CC, or MailMessage.Bcc." | |
Write-Error $_.exception.FailedRecipient | |
} | |
catch [System.Net.Mail.SmtpException] { | |
Write-Error "Smtp server connection failure." | |
Write-Error $_.exception | |
Write-Error $_.exception.StatusCode | |
Write-Error "read -> https://docs.microsoft.com/en-us/dotnet/api/system.net.mail.smtpstatuscode" | |
} | |
catch [System.InvalidOperationException] { | |
Write-Error "Invalid SMTP settings." | |
} | |
catch { | |
Write-Error "Something wrong." | |
Write-Error $_.exception | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment