14

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)
abatishchev
  • 98,240
  • 88
  • 296
  • 433
TheLukeMcCarthy
  • 2,253
  • 2
  • 25
  • 34

7 Answers7

20

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

C:\PS>Send-MailMessage -from "User01 <user01@example.com>" `
                       -to "User02 <user02@example.com>", `
                           "User03 <user03@example.com>" `
                       -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
  • 194,368
  • 42
  • 353
  • 369
  • 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 Oct 25 '10 at 09:34
  • 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 Oct 26 '10 at 03:19
  • 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 server At line:1 char:17 + Send-MailMessage <<<< -from "Luke.McCathy@someDomain.com"` + CategoryInfo : InvalidOperation: (System.Net.Mail.SmtpClient:SmtpClient) [Send-MailMessage], SmtpException + FullyQualifiedErrorId : SmtpException,Microsoft.PowerShell.Commands.Send MailMessage Also I'm trying to run this from a client machine and not the exchange server. – TheLukeMcCarthy Oct 29 '10 at 09:36
  • @TheLukeMcCarthy Check the possibility of a virus scanner blocking port actions. – JustinStolle Aug 05 '15 at 20:12
14

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.

TheLukeMcCarthy
  • 2,253
  • 2
  • 25
  • 34
7

This worked for me using powershell-

Define Variables:

$fromaddress = "donotreply@pd.com" 
$toaddress = "test@pd.com" 
$Subject = "Test message" 
$body = "Please find attached - test"
$attachment = "C:\temp\test.csv" 
$smtpserver = "mail.pd.com" 

Use the variables in the script:

$message = new-object System.Net.Mail.MailMessage 
$message.From = $fromaddress 
$message.To.Add($toaddress)
$message.IsBodyHtml = $True 
$message.Subject = $Subject 
$attach = new-object Net.Mail.Attachment($attachment) 
$message.Attachments.Add($attach) 
$message.body = $body 
$smtp = new-object Net.Mail.SmtpClient($smtpserver) 
$smtp.Send($message)
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
P.D
  • 141
  • 4
  • 14
0

You can use send-mailmessage or system.net.mail.MailMessage to accomplish it. Interestingly, there is a significant execution time difference between the two approaches. You can use measure-command to observe the execution time of the commands.

Bill
  • 5,263
  • 6
  • 35
  • 50
0

I have experienced such problem, (windows 10 / PS 5.1) My SMTP is not authentified or secure ... I have to finish by this line "MyAttacheObject.Dispose()" ... / and finally that's work :!

$smtp = new-object Net.Mail.SmtpClient($smtpserver) 
$attach.Dispose()

this is my code with two attachments :

# Email configuration NO AUTH NO SECURE
$emailHost = "smtp.bot.com"
$emailUser = ""
$emailPass = ""
$emailFrom = "myemail@bot.com"
$emailsTo=@("toyoumylove@bot.com","toyoumybad@bot.com")
$emailSubject = $title
$emailbody=$body
$attachment1 = @($PATh+$outFile) 
$attachment2 = @($PATh+$inFile) 
#End of parameters

$msg = New-Object System.Net.Mail.MailMessage
$msg.from = ($emailFrom)
    foreach ($d in $emailsTo) {    
    $msg.to.add($d)
    }
$msg.Subject = $emailSubject
$msg.Body = $emailbody
$msg.isBodyhtml = $true   

$att = new-object System.Net.Mail.Attachment($attachment1)
$msg.Attachments.add($att)
$att = new-object System.Net.Mail.Attachment($attachment2)
$msg.Attachments.add($att)
$smtp = New-Object System.Net.Mail.SmtpClient $emailHost
$smtp.Credentials = New-Object System.Net.NetworkCredential($emailUser, $emailPass);
  $smtp.send($msg)
  $att.Dispose()
JMMDL
  • 1
  • 1
0
"yourpassword" | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Out-File "D:\Password.txt"

# The above command will encrypt the password you need to run this command only one time

# 1.Sign in to your work or school account, go to the My Account page, and select Security info.
2.Select Add method, choose App password from the list, and then select Add.
3.Enter a name for the app password, and then select Next. it will give password 
# you should use this password in above mentioned command

$User = "mymail@company.net"
$File = "C:\Users\username\Desktop\Mail\Password.txt"
$cred=New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, (Get-Content $File | ConvertTo-SecureString -AsPlainText -Force)
$EmailTo = "mymail@company.net"
$EmailFrom = "mymail@company.net"
$Subject = "SERVICE STOPPED"
$Body = "SERVICE STOPPED PFA Document to get more details."
$SMTPServer = "smtp.office365.com"
$filenameAndPath = "C:\Users\username\Desktop\new.txt"
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
$attachment = New-Object System.Net.Mail.Attachment($filenameAndPath)
$SMTPMessage.Attachments.Add($attachment)
$SMTPClient = New-Object Net.Mail.SmtpClient($SMTPServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($cred.UserName, $cred.Password);
$SMTPClient.Send($SMTPMessage)
Harsha
  • 61
  • 1
  • 2
0

I needed to drop the "-AsPlainText -Force"

$emailCred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $emailUser, (Get-Content $emailPasswordFile | ConvertTo-SecureString)
Daniel
  • 1