emailpowershellattachmentpowershell-2.0

How to attach a file to an email with PowerShell


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)

Solution

  • 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.