How to attach a file to an email with PowerShell

TheLukeMcCarthy picture TheLukeMcCarthy · Oct 22, 2010 · Viewed 81.9k times · Source

I have written a PowerShell script that will create an email, however I can't seem to attach a file. The file does exist and PowerShell can open it, Could anyone tell me what I'm doing wrong?

$ol = New-Object -comObject Outlook.Application 
$message = $ol.CreateItem(0)
$message.Recipients.Add("Deployment")  
$message.Subject = "Website deployment"  
$message.Body = "See attached file for the updates made to the website`r`n`r`nWarm Regards`r`nLuke"

# Attach a file this doesn't work
$file = "K:\Deploy-log.csv"
$attachment = new-object System.Net.Mail.Attachment $file
$message.Attachments.Add($attachment)

Answer

Keith Hill picture Keith Hill · Oct 22, 2010

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.