views:

69

answers:

3

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)
+5  A: 

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.

Keith Hill
@Keith thanks for that, but I get "Unable to connect to the remote server" error when trying to use that, and the server is up.
TheLukeMcCarthy
That could be authentication, firewall, etc. Check out this thread for additional help - http://social.msdn.microsoft.com/Forums/en-US/netfxnetcom/thread/a75533eb-131b-4ff3-a3b2-b6df87c25cc8/ (towards the bottom).
Keith Hill
No matter what I do I can't get the above to work. I get the follow error. Send-MailMessage : Unable to connect to the remote serverAt line:1 char:17 + Send-MailMessage <<<< -from "[email protected]"`+ CategoryInfo : InvalidOperation: (System.Net.Mail.SmtpClient:SmtpClient) [Send-MailMessage], SmtpException + FullyQualifiedErrorId : SmtpException,Microsoft.PowerShell.Commands.Send MailMessageAlso I'm trying to run this from a client machine and not the exchange server.
TheLukeMcCarthy