PoshCode Archive  Artifact [c1cbd6aeb1]

Artifact c1cbd6aeb1f020426e40e598ac7dbe1adbb10868d375e63f8dd4cfcf1a824bf3:

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

# 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: 4469
# x-archived: 2016-03-18T23:48:26
# x-published: 2016-09-15T03:52:00
#
# I just added attachments — Joel Bennett
#
##############################################################################
##
## 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",

    [string[]]$Attachments

)

## 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

foreach($path in Convert-Path $Attachments) {
    $email.Attachements.Add($path)
}


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