Inviare email con Outlook in PowerShell

Questa funzione in Powershell permette di inviare e-mail tramite Outlook (che deve essere in esecuzione).

E’ basata sullo script presente su: http://www.andyparkhill.co.uk/2010/08/send-outlook-email-via-powershell.html a cui ho effettuato delle modifiche per l’invio dell’email a più destinatari e per l’invio degli allegati.

function Send-Email (
    [String[]]$recipientEmail = $(Throw "At least one recipient email is required!"),
    [String]$subject = $(Throw "An email subject header is required!"),
    [String]$body,
    [String]$attachment
) {
    $outlook = New-Object -comObject Outlook.Application
    $mail = $outlook.CreateItem(0)
    $recipientEmail | ForEach-Object { $mail.Recipients.Add($_) } | Out-Null
    $mail.Subject = $subject
    $mail.Body = $body

    # For HTML encoded emails
    # $mail.HTMLBody = "<HTML><HEAD>Text<B>BOLD</B>  <span style='color:#E36C0A'>Color Text</span></HEAD></HTML>"

    if ($attachment.Length -ne 0) {
        $mail.Attachments.Add($attachment) # | Out-Null
    }

    $mail.Send()
    # Write-Host "] Email sent!" -BackgroundColor Green -ForegroundColor Black;
}
# Main Script Body

Write-Host "] Start sending mail via Outlook . . ."

[String[]]$recipientEmail = 'mail_1@domain.test','mail_2@domain.test','mail_N@domain.test'
$subject = "This is a test"
$body = "Test test test" # Optional
$attachment = "C:\Temp\test.txt" # Optional

if (Test-Path $attachment) {
    Send-Email -recipientEmail $recipientEmail -subject $subject -body $body -attachment $attachment
}
else {
    Send-Email -recipientEmail $recipientEmail -subject $subject -body $body
}
# End of Script Body