Sending Email From PowerShell

From vWiki
Jump to navigation Jump to search
See also Send-MailMessage
Since PowerShell v2, a standard CmdLet (Send-MailMessage) exists to send emails with. This page was originally created in the v1 days.

However, there are things that cannot be done with the standard CmdLet (eg set a Reply From address) which can be done by using the .NET MailMessage object as described below.

Emails can be sent very simply if no attachment is needed....

$smtp = New-Object Net.Mail.SmtpClient -arg $smtpServer 
  • $emailRcpt - Multiple email addresses need to be comma seperated

With Attachments

$smtp = New-Object Net.Mail.SmtpClient -arg $smtpServer 
$msg = New-Object Net.Mail.MailMessage
$attach = New-Object Net.Mail.Attachment($OutputFile)          # See note below
$msg.From = $emailFrom
$msg.Subject = $emailSubject
$msg.Body = $msgBody
  • $OutputFile - Will normally need to be a full path as the script needn't be executing where your script is, assuming attachment is in same directory as script use the following...
    • ((Get-Location -PSProvider FileSystem).ProviderPath) + "\" + $OutputFile

With SMTP Authentication

As above, but additionally create a credential object and link it to the SMTP Client object, so...

$cred = new-object
$cred.domain = "the domain you want"
$cred.userName = "username"
$cred.password = "password"
$smtp.credentials = $cred

With Embedded HTML

As above, but you need to set the IsBodyHTML option for the message, so...

$msg.IsBodyHTML = $true

Different Reply To

In order to set the ReplyTo field, so that replies get sent to a different address than the From field, use the following property...

$msg.ReplyTo = ""