Sending E-mail From PowerShell v1.0

While in PowerShell 2 there will be a “Send-Mail” cmdlet (as I heard), I needed something for current version. Here is the self-explaining PowerShell script for sending mails with optional attachments and multiple recipients.

Remember to change the hard-coded “mail.server.com” to your own mail server, otherwise nothing will work :).

##############################################################
# Send e-mail with optional attachments
#
function SendEmail
{
    param(
        $From,
        $To,
        $Subject,
        $Body,
        $Attach = $null
    )
    
    $msg = New-Object Net.Mail.MailMessage
    $msg.From = $From
    
    #Recipient address can be an array as well
    $addresses = $To
    if($To -isnot [Object[]])
    {
        $addresses = ([string]$To).Split(";")
    }
    
    foreach($singleAddress in $addresses)
    {
        $msg.To.Add($singleAddress)
    }
    
    $msg.Body = $Body
    $msg.Subject = $Subject
    
    if($Attach -ne $null)
    {
        if($Attach -is [String[]] -or $Attach -is [Object[]])
        {
            foreach($filePath in $Attach)
            {
                $att = New-Object Net.Mail.Attachment($filePath, "text/plain")
                $msg.Attachments.Add($att)
                Write-Output ([String]::Format("{0} attached", $filePath))
            }
        }
        elseif($Attach -is [string])
        {
            $att = New-Object Net.Mail.Attachment($Attach, "text/plain")
            $msg.Attachments.Add($att)
            Write-Output ([String]::Format("{0} attached", $Attach))
        }
        else
        {
            Write-Warning ([String]::Format("Attachment is of unknown type: {0}. Please use string or string/object arrays only", $Attach.GetType().Name))
        }
    }
    
    $client = New-Object net.Mail.SmtpClient("mail.server.com")
    $client.Send($msg)
    Write-Output "E-mail message sent"
}

Technorati Tags: , ,