Sending Email From PowerShell

From vwiki
Jump to navigation Jump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.
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 
$smtp.Send($emailFrom,$emailRcpt,$emailSubject,$msgBody)
  • $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.To.Add($emailRcpt)
$msg.Subject = $emailSubject
$msg.Body = $msgBody
$msg.Attachments.Add($attach)
    
$smtp.Send($msg)
$attach.Dispose()
  • $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 System.net.networkCredential
$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

http://msdn.microsoft.com/en-us/library/system.net.mail.smtpclient.aspx

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 = "someone@domain.com"