How to attach a file to an email with PowerShell

If you are on PowerShell 2.0, just use the built-in cmdlet Send-MailMessage:

C:\PS>Send-MailMessage -from "User01 <[email protected]>" `
                       -to "User02 <[email protected]>", `
                           "User03 <[email protected]>" `
                       -subject "Sending the Attachment" `
                       -body "Forgot to send the attachment. Sending now." `
                       -Attachment "data.csv" -smtpServer smtp.fabrikam.com

If you copy/paste this watch out for the extra space added after the backtick. PowerShell doesn't like it.


I got the above to work by removing the line

$attachment = new-object System.Net.Mail.Attachment $file

and changing

$message.Attachments.Add($attachment)

to

$message.Attachments.Add($file)

While the solution provided by @Keith Hill would be better, even with a lot of goggling I couldn't get it to work.