Reputation: 45
I have written the following in Powershell to try and send an email with an attachment.
$FileDate = Get-Date
$SmtpServer = 'smtp.office365.com'
$SmtpUser = '[email protected]'
$smtpPassword = 'blah'
$MailtTo = '[email protected]'
$MailFrom = '[email protected]'
$MailSubject = "The file for $FileDate is attached."
$MailBody = "Please take action"
$attachment= "C:\Users\my user\myfile.txt"
$attach = new-object Net.Mail.Attachment ($attachment)
$Credentials = New-Object System.Management.Automation.PSCredential -
ArgumentList $SmtpUser, $($smtpPassword | ConvertTo-SecureString -
AsPlainText -Force)
Send-MailMessage -To "$MailtTo" -from "$MailFrom" -Subject $MailSubject -
Body $MailBody -SmtpServer $SmtpServer -UseSsl -Credential $Credentials -
attachments "$attach"
When I execute it, I get the following error in Powershell
Send-MailMessage : Could not find file
'C:\Users\myuser\System.Net.Mail.Attachment'.
At line:1 char:1
+ Send-MailMessage -To "$MailtTo" -from "$MailFrom" -Subject $MailSubject -
Body $ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Send-MailMessage],
FileNotFoundException+ FullyQualifiedErrorId :
System.IO.FileNotFoundException,Microsoft.PowerShell.Commands.SendMailMessage
But the file is 100% there. Can anyone help me with where I am going wrong?
Thanks in advance
Upvotes: 2
Views: 159
Reputation: 23355
The -Attachments
parameter of Send-MailMessage
expects a string input, so I don't think you need to create the $attach
variable at all, but instead just use $attachment
which already contains the string path of the file you want to attach:
.. -attachments $attachment
Upvotes: 1