我有两个不同的脚本,并将它们组合起来检查新文件的特定文件夹,并将该文件作为附件发送。
这里的代码组合在一起:
Param (
$Path = "C:\path"
)
$File = Get-ChildItem $Path | Where { $_.LastWriteTime -ge [datetime]::Now.AddMinutes(-10) }
If ($File)
{
$emailSmtpServer = "smtp.xxxx.com"
$emailSmtpServerPort = "587"
$emailSmtpUser = "xxxx@xxxxxx.com"
$emailSmtpPass = "xxxxxxxx"
$emailMessage = New-Object System.Net.Mail.MailMessage
$emailMessage.From = "Xxxx Xxxx <xxxx@xxxxxx.com>"
$emailMessage.To.Add( "xxxx@xxxxxx.com" )
$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)
}
代码工作正常,它会查找新文件并发送电子邮件,但它不会附加文件,我收到以下错误
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
我认为这与使用$attachment = $File
有人可以帮忙吗?
答案 0 :(得分:0)
您可能必须首先创建一个Attachment
对象,并且还必须处理多个文件,因此请替换以下行:
$attachment = $File
$emailMessage.Attachments.Add($attachment)
使用:
$File | ForEach-Object {
$filePath = $_.FullName
$attachment = new-object Net.Mail.Attachment($filePath)
$emailMessage.Attachments.Add($attachment)
}
答案 1 :(得分:0)
我和您有相同的问题,因此已解决。 https://community.spiceworks.com/posts/8438625
只需更改: $ path =“ D:\ FTP-COR \ $($ today.Year)\ $($ today.ToString(” MM-dd-yyyy“))” 并添加您的凭据。
答案 2 :(得分:0)
我正在使用PowerShell :(我使用.NET,所以请不要忘记C#,请不要问):-) 创建一个.csv文件:
$collection | Export-Csv -Path $SaveAs -NoTypeInformation
要创建附件对象:
[System.Net.Mail.Attachment] $Attachment = [System.Net.Mail.Attachment]::new($SaveAs)
然后附加到消息对象:
$message.Attachments.Add($Attachment)
这应该有效。我一直在使用它,并且运行良好。我知道它在PowerShell中,但核心是相同的.NET