PoshCode Archive  Artifact [26f816ff1a]

Artifact 26f816ff1a75cbd8414886ff082fc5ade0c988172e545e6917a73e36df04dd57:

  • File Send-MailMessage.ps1 — part of check-in [1d80f76d97] at 2018-06-10 13:19:44 on branch trunk — From Windows PowerShell Cookbook (O’Reilly) by Lee Holmes (user: Lee Holmes size: 1979)

# encoding: ascii
# api: powershell
# title: Send-MailMessage.ps1
# description: From Windows PowerShell Cookbook (O’Reilly) by Lee Holmes
# version: 0.1
# type: script
# author: Lee Holmes
# license: CC0
# x-poshcode-id: 3060
# x-derived-from-id: 4663
# x-archived: 2016-03-19T00:34:39
# x-published: 2012-11-20T22:24:00
#
#
##############################################################################
##
## Send-MailMessage
##
## From Windows PowerShell Cookbook (O'Reilly)
## by Lee Holmes (http://www.leeholmes.com/guide)
##
## Illustrate the techniques used to send an email in PowerShell.
## In version two, use the Send-MailMessage cmdlet.
##
## Example:
##
## PS >$body = @"
## >> Hi from another satisfied customer of The PowerShell Cookbook!
## >> "@
## >>
## PS >$to = "guide_feedback@leeholmes.com"
## PS >$subject = "Thanks for all of the scripts."
## PS >$mailHost = "mail.leeholmes.com"
## PS >Send-MailMessage $to $subject $body $mailHost
##
##############################################################################

param(
    ## The recipient of the mail message
    [string[]] $To = $(throw "Please specify the destination mail address"),

    ## The subjecty of the message
    [string] $Subject = "<No Subject>",

    ## The body of the message
    [string] $Body = $(throw "Please specify the message content"),

    ## The SMTP host that will transmit the message
    [string] $SmtpHost = $(throw "Please specify a mail server."),

    ## The sender of the message
    [string] $From = "$($env:UserName)@example.com"
)

## Create the mail message
$email = New-Object System.Net.Mail.MailMessage

## Populate its fields
foreach($mailTo in $to)
{
    $email.To.Add($mailTo)
}

$email.From = $from
$email.Subject = $subject
$email.Body = $body

## Send the mail
$client = New-Object System.Net.Mail.SmtpClient $smtpHost
$client.UseDefaultCredentials = $true
$client.Send($email)