Email Versand

Der Email-Versand mit Powershell erscheit auf den ersten Blick mit den Cmdlet Send-MailMessage recht einfach. Doch leider funktioniert das nur ohne SSL auf Port 25 recht einfach. Sobald SSL ins Spiel kommt muss mid. auf PS 3 (Windows Management Framework) upgegradet werden und der Port 465 funktioniert immer noch nicht. Somit verwende ich immer noch die alt hergebrachte Versandweise mittels System.Net.Mail.SmtpClient bzw. System.Web.Mail.MailMessage.

 

<##########################
# PowerShell Email Script #
# Michael Hölldobler # # http://www.alant.com #
###########################>
#Mail recipients comma separated
# $To = "John Doe<Diese E-Mail-Adresse ist vor Spambots geschützt! Zur Anzeige muss JavaScript eingeschaltet sein.>"
# $To = "John Doe<Diese E-Mail-Adresse ist vor Spambots geschützt! Zur Anzeige muss JavaScript eingeschaltet sein.>,Jane Doe<Diese E-Mail-Adresse ist vor Spambots geschützt! Zur Anzeige muss JavaScript eingeschaltet sein.>"
$To = "Diese E-Mail-Adresse ist vor Spambots geschützt! Zur Anzeige muss JavaScript eingeschaltet sein."
$Cc = ""
$Bcc = ""
$Subject = "PowerShell Test-Message"
$Body ="<HTML><BODY>Hello,<br />this is a message sent via <font color='red'><b>PowerShell</b></font>.</BODY></HTML>"
$BodyIsHTML = $True
#$Body = "Hello, this is a message sent via PowerShell."
#$BodyIsHTML = $False
# Is there an Attchment
$AttachmentPath = "attachmentPath"
# Mail Server settings

$from = "Diese E-Mail-Adresse ist vor Spambots geschützt! Zur Anzeige muss JavaScript eingeschaltet sein."
$SMTPUser = $from #"username"
$SMTPPasswort = "mysecretpassword"
$SMTPServer = "smtp.test.intern"
$SMTPServerPort = 465 #587 25
$timeout = 30000 # timeout in milliseconds
### Function Section ###
function sendemail { 
  # Check Port
  $implicitSSL = $true
  $enableSSL = $true
  switch ($SMTPServerPort) {
    25 {$enableSSL = $false} # default Port (unsecure, almost depreached)
    # 465 {} # connection buildup is secure
    # 8465 {}
    587 {$implicitSSL = $false} # connection buildup isn't secure  
    2525 {$implicitSSL = $false}
    8025 {$implicitSSL = $false}
  }

  # Ckeck Attachment
  if ($attachmentPath -ne "") {
    if (Test-Path $attachmentPath){
    } else {
      Write-Host "Anhang wurde nicht gefunden " + $attachmentPath $attachmentPath = ""
    }
  }
  # Check Password. Without Entry, check File. If it does't exist ask for Password
  if ($SMTPPasswort -eq "") {
    $SMTPPasswortFile = ".\MailPW.txt"
    If (!(Test-Path $SMTPPasswortFile)){
      (Get-Credential).password | ConvertFrom-SecureString > MailPW.txt
     }
    $SMTPPasswort = Get-Content $SMTPPasswortFile | ConvertTo-SecureString
   } Else {
     $SMTPPasswort = $SMTPPasswort | ConvertTo-SecureString -asPlainText -Force 
   }

   $credentials = New-Object System.Management.Automation.PSCredential($SMTPUser, $SMTPPasswort)  
   if ($implicitSSL) { 
     sentViaWebMail
  } else {
    sentViaSmtpClient
  }
}

function sentViaSmtpClient {
  # Set up server connection
  $smtpClient = New-Object System.Net.Mail.SmtpClient $SMTPServer, $SMTPServerPort
  $smtpClient.EnableSsl = $enableSSL
  $smtpClient.Timeout = $timeout $smtpClient.UseDefaultCredentials = $false;
  $smtpClient.Credentials = $credentials # Create mail message
  $message = New-Object System.Net.Mail.MailMessage $from, $to, $subject, $body
  $message.IsBodyHTML = $BodyIsHTML
  if ($attachmentPath -ne ""){
    $attachment = New-Object System.Net.Mail.Attachment $attachmentPath $message.Attachments.Add($attachment)
  }
  if ($Bcc -ne "") {$message.Bcc.Add($Bcc)}
  if ($Cc -ne "") {$message.Cc.Add($Cc)}
  # Send the message
  try {
    $smtpClient.Send($message)
    Write-Output "Message sent."
  }
  catch {
    Write-Error $_ Write-Output "Message send failed."
  }
}

function sentViaWebMail {
  # Load System.Web assembly
  [System.Reflection.Assembly]::LoadWithPartialName("System.Web") > $null
  $schema = "http://schemas.microsoft.com/cdo/configuration/"
  $Ptr = [System.Runtime.InteropServices.Marshal]::SecureStringToCoTaskMemUnicode($SMTPPasswort)
  # Convert to plain text
  $SMTPPlainPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($Ptr)
  # Create a new mail with the appropriate server settigns
  $mail = New-Object System.Web.Mail.MailMessage
  $mail.Fields.Add($schema + "smtpserver", $SMTPServer)
  if ($enableSSL) {
    $mail.Fields.Add($schema + "smtpserverport", $SMTPServerPort)
    $mail.Fields.Add($schema + "smtpusessl", $enableSSL)
  }
  $mail.Fields.Add($schema + "sendusername", $credentials.UserName)
  $mail.Fields.Add($schema + "sendpassword", $SMTPPlainPassword)
  $mail.Fields.Add($schema + "smtpconnectiontimeout", $timeout / 1000)
  # Use network SMTP server...
  $mail.Fields.Add($schema + "sendusing", 2)
  # ... and basic authentication
  $mail.Fields.Add($schema + "smtpauthenticate", 1)
  # Importance of email #$mail.Fields.Add("urn:schemas:httpmail:importance", 1) #0 = Low importance 1 = Normal importance (default) 2 = High importance
  # Set up the mail message fields
  $mail.From = $from
  $mail.To = $to
  if ($Cc -ne "") {$mail.Cc = $Cc}
  if ($Bcc -ne "") {$mail.Bcc = $bcc}
  $mail.Subject = $subject
  $mail.IsBodyHTML = $BodyIsHTML
  $mail.Body = $body
  if ($attachmentPath -ne "") {
    # Convert to full path and attach file to message
    $attachmentPath = (get-item $attachmentPath).FullName
    $attachment = New-Object System.Web.Mail.MailAttachment $attachmentPath
    $mail.Attachments.Add($attachment) > $null
  }
  # Send the message
  try {
   [System.Web.Mail.SmtpMail]::Send($mail)
   Write-Output "Message sent."
  }
  catch {
    Write-Error $_ Write-Output "Message send failed."
  }
}

### Script Section ###
sendemail
### EOS ###