我对PowerShell不太了解,但是我在Stack Overflow中找到了有关如何发送带有附件的电子邮件的代码。我想知道是否可以对其进行一些更改,以便我可以发送两个附件而不是一个。我想在不使用ZIP或RAR进行压缩的情况下发送文件:
附件: “ C:\ Users \ ricar \ Desktop \ impressora.txt” “ C:\ Users \ ricar \ Desktop \ impressora2.txt”
$Username = "myemail@sapo.pt";
$Password = "mypassword";
$path = "C:\Users\ricar\Desktop\impressora.txt";
function Send-ToEmail([string]$email, [string]$attachmentpath){
$message = new-object Net.Mail.MailMessage;
$message.From = "myemail@sapo.pt";
$message.To.Add($email);
$message.Subject = "Hello how are you";
$message.Body = "Is this really going to happen?????";
$attachment = New-Object Net.Mail.Attachment($attachmentpath);
$message.Attachments.Add($attachment);
$smtp = new-object Net.Mail.SmtpClient("smtp.sapo.pt", "587");
$smtp.EnableSSL = $true;
$smtp.Credentials = New-Object System.Net.NetworkCredential($Username, $Password);
$smtp.send($message);
write-host "Mail Sent" ;
$attachment.Dispose();
}
Send-ToEmail -email "myfriend@yahoo.com.br" -attachmentpath $path;
答案 0 :(得分:1)
我将通过使用-attachmentpath
为[string[]]
参数使用字符串数组。您还可以省去创建单独的Net.Mail.Attachment
对象的步骤,因为该对象已经包含在您已经拥有的基本Net.Mail.MailMessage
对象中。
示例:
$Username = "myemail@sapo.pt"
$Password = "mypassword"
$path = "C:\Users\ricar\Desktop\impressora.txt","C:\Users\ricar\Desktop\impressora2.txt"
function Send-ToEmail([string]$email, [string[]]$attachmentpath){
$message = new-object Net.Mail.MailMessage
$message.From = "myemail@sapo.pt"
$message.To.Add($email)
$message.Subject = "Hello how are you"
$message.Body = "Is this really going to happen?????"
$attachmentpath | foreach {$message.Attachments.Add($_)}
$smtp = new-object Net.Mail.SmtpClient("smtp.sapo.pt", "587")
$smtp.EnableSSL = $true
$smtp.Credentials = New-Object System.Net.NetworkCredential($Username, $Password)
$smtp.send($message)
write-host "Mail Sent"
}
Send-ToEmail -email "myfriend@yahoo.com.br" -attachmentpath $path
此外,在PowerShell中每行的末尾也不需要包含分号。如果符合当前代码样式准则,我只会使用它们。