SQL Clone
SQLServerCentral is supported by Redgate
Log in  ::  Register  ::  Not logged in

Send email from Powershell with attachment

This post  describes how to call  to add an email attachment using Powershell.

In an earlier post - SQL Server – Send email using Powershell – the new-object Net.Mail.SmtpClient() Class was used.

To add an email attachment , use New-Object System.Net.Mail.MailMessage and New-Object System.Net.Mail.Attachment, which are part of the .Net Framework

The example script includes creating the variables, the function and calling the function .


$emailFrom = "jvamvas@sqlserver-dba.com"
$emailTo = "jvamvas@sqlserver-dba.com"
$subject = "SQLServer-DBA.com: Powershell Function calling an SMTP server with attachment"
$body = "SQLServer-DBA.com : Send an email through SMTP in Powershell with attachment "
$smtpServer = "mysmtpserver"
$filePath = "C:\sql_server_health_sqlserver_jobs_2012-02.html"

Function sendEmail([string]$emailFrom, [string]$emailTo, [string]$subject,[string]$body,[string]$smtpServer,[string]$filePath)
#initate message
$email = New-Object System.Net.Mail.MailMessage 
$email.From = $emailFrom
$email.Subject = $subject
$email.Body = $body
# initiate email attachment 
$emailAttach = New-Object System.Net.Mail.Attachment $filePath
#initiate sending email 
$smtp = new-object Net.Mail.SmtpClient($smtpServer)

#Call Function 
sendEmail $emailFrom $emailTo $subject $body $smtpServer $filePath


See Also

Powershell - run script on all sql servers

Author: Jack Vamvas (http://www.sqlserver-dba.com)


Leave a comment on the original post [www.sqlserver-dba.com, opens in a new window]

Loading comments...