Sending Email From PowerShell
Jump to navigation
Jump to search
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