从内存发送邮件附件



我正在尝试使用我在此线程中找到的答案(指向此 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:Windowssystem32System.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?

让我先说一下出了什么问题。[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]

相关内容

  • 没有找到相关文章

最新更新