Reputation: 47
I got two different scripts and combined them to check a specific folder for new file and email that file as attachment.
Here's the code combined:
Param (
$Path = "C:\path"
)
$File = Get-ChildItem $Path | Where { $_.LastWriteTime -ge [datetime]::Now.AddMinutes(-10) }
If ($File)
{
$emailSmtpServer = "smtp.xxxx.com"
$emailSmtpServerPort = "587"
$emailSmtpUser = "[email protected]"
$emailSmtpPass = "xxxxxxxx"
$emailMessage = New-Object System.Net.Mail.MailMessage
$emailMessage.From = "Xxxx Xxxx <[email protected]>"
$emailMessage.To.Add( "[email protected]" )
$emailMessage.Subject = "File Test Report"
$emailMessage.IsBodyHtml = $false
$emailMessage.Body = "Weekly Report"
$SMTPClient = New-Object System.Net.Mail.SmtpClient( $emailSmtpServer , $emailSmtpServerPort )
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential( $emailSmtpUser , $emailSmtpPass );
$attachment = $File
$emailMessage.Attachments.Add($attachment)
$SMTPClient.Send($emailMessage)
}
The code works fine, it looks for new file and sends the email except it won't attach the file and I get the following error
Cannot find an overload for "Add" and the argument count: "1".
At D:\SendEmail2.ps1:24 char:1
+ $emailMessage.Attachments.Add($attachment)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodCountCouldNotFindBest
I think it has something to do with calling the file with $attachment = $File
Can anyone help?
Upvotes: 2
Views: 14177
Reputation: 46
I am using PowerShell: (I use .NET so don't forget C#, please don't ask):-) create a .csv file:
$collection | Export-Csv -Path $SaveAs -NoTypeInformation
To create the attachment object:
[System.Net.Mail.Attachment] $Attachment = [System.Net.Mail.Attachment]::new($SaveAs)
Then to attach to the message object:
$message.Attachments.Add($Attachment)
This should work. I have been using this and it's been working fine. I know it's in PowerShell, but at the core, same .NET
Upvotes: 0
Reputation: 1
i had the same issue as you and this fixed it. https://community.spiceworks.com/posts/8438625
just change: $path = "D:\FTP-COR\$($today.Year)\$($today.ToString("MM-dd-yyyy"))" and add your credentials.
Upvotes: 0
Reputation: 58931
You probably have to create a Attachment
object first and also have to deal with multiple files so replace the following lines:
$attachment = $File
$emailMessage.Attachments.Add($attachment)
with:
$File | ForEach-Object {
$filePath = $_.FullName
$attachment = new-object Net.Mail.Attachment($filePath)
$emailMessage.Attachments.Add($attachment)
}
Upvotes: 1