Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 824
TheLukeMcCarthy Avatar asked Oct 22 '10 13:10

TheLukeMcCarthy


People also ask

How do you attach a file to the body of an email?

Attach a file to a message Create a message, or for an existing message, click Reply, Reply All, or Forward. In the message window, on the Message tab, in the Include group, click Attach File. Browse to and click the file that you want to attach, and then click Insert.

How do I use PowerShell to email?

The Send-MailMessage cmdlet sends an email message from within PowerShell. You must specify a Simple Mail Transfer Protocol (SMTP) server or the Send-MailMessage command fails. Use the SmtpServer parameter or set the $PSEmailServer variable to a valid SMTP server.


1 Answers

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.

like image 200
Keith Hill Avatar answered Oct 01 '22 19:10

Keith Hill