我试图通过使用我在this thread(指向this URL)中找到的答案,先在Send-MailMessage中发送附件,而不先保存到磁盘。
它说要使用:
$attachment = [System.Net.Mail.Attachment]::CreateAttachmentFromString($attachmenttext,"test.txt")
但是当我尝试使用Send-MailMessage而不是它显示的复杂方式执行此操作时,出现此错误:
Send-MailMessage -From "email@email.com" -To "email@email.com" -Subject "Subject" -Body $body -SmtpServer "smtp.server.local" -Port 25 -BodyAsHtml -Attachments $attachment
Send-MailMessage : Could not find file 'C:\Windows\system32\System.Net.Mail.Attachment'.
At line:3 char:1
+ Send-MailMessage -From "email@email.com" -To "email@e ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Send-MailMessage], FileNotFoundException
+ FullyQualifiedErrorId : System.IO.FileNotFoundException,Microsoft.PowerShell.Commands.SendMailMessage
是否仍然可以继续通过此方法使用Send-MailMessage?还是有其他方法可以让我在仍然使用send-mailmessage的情况下附加文件而无需先保存到磁盘上?
答案 0 :(得分:2)
首先让我解决问题。 [System.Net.Mail.Attachment]::CreateAttachmentFromString
正在寻找System.Net.Mail.Attachment
字符串数组时,send-mailmessage -attachments
输出类型string[]
。这就是为什么该示例将失败的原因。
我编写了一个简单的函数,因此您可以使用示例中发布的附件,该附件创建一个MailMessage
并查找类型为[System.Net.Mail.Attachment]
的附件。
Function Try-SendMail([string[]]$To, [string]$From, [string]$SmtpServer, [int]$Port = 25, [pscredential]$SmtpCredential, [string]$Subject, [string]$Body, [System.Net.Mail.Attachment[]]$attachment, [switch]$IsBodyHTML){
[System.Net.Mail.MailMessage]$Mail = new-object System.Net.Mail.MailMessage
$To | %{$Mail.To.Add($_)}
$Mail.From = $From
$Mail.IsBodyHtml = $IsBodyHTML
$Mail.Body = $Body
$Mail.Subject = $Subject
$Attachment | %{$mail.Attachments.Add($_)}
[System.Net.Mail.SmtpClient]$SMTP = new-object System.Net.Mail.SmtpClient
$SMTP.Host = $SmtpServer
$SMTP.Port = $Port
If($SmtpCredential){
$NetCredential = New-Object System.Net.NetworkCredential
$NetCredential.UserName = $SmtpCredential.GetNetworkCredential().UserName
$NetCredential.Password = $SmtpCredential.GetNetworkCredential().Password
$SMTP.Credentials = $NetCredential
}
try{
$SMTP.Send($Mail)
}catch{
$_ | select *
}
}
您可以像使用它
$To = @("Person1@Test.com","Person2@Test.com")
$From = "MainGuy@PErson.com"
$Server = "SMTPSERVER.NET"
$Port = 587
$Attachments = @(
$([System.Net.Mail.Attachment]::CreateAttachmentFromString("HELLO", "Test.txt")),
$([System.Net.Mail.Attachment]::CreateAttachmentFromString("HELLO2", "Test2.txt"))
)
$SmtpCredential = Get-Credential
Try-SendMail -to $To -From $From -Subject "Hello" -Body "World" -Attachment $Attachments -SmtpServer $Server -port $Port -SmtpCredential $SmtpCredential
*编辑已忘记在功能参数中将[System.Net.Mail.Attachment]
设为[System.Net.Mail.Attachment[]]