Powershell在Excel电子表格中向收件人发送电子邮件

时间:2017-03-15 02:36:21

标签: powershell email

我的电子表格位于C:\ scripts \ test.csv,其中包含用户电子邮件地址列表。

我尝试将以下电子邮件发送给其中每个用户,但它只发送给其中一个用户。如何将其发送给所有用户?

$recipients = get-content C:\scripts\test.csv

$smtpServer = "mail.server.com"
$msg = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$msg.From = "FromUser@email.com"
$msg.To.Add($recipients)
$msg.subject = "Requiring Updates"
$msg.IsBodyHTML = $true
$body = @'
<html> 
  <body> 
    <font face="calibri">Hello, please read this test email.</font>
  </body> 
</html> 
'@ 

$msg.body = $body
$smtp.Send($msg)

2 个答案:

答案 0 :(得分:3)

所以你必须在 foreach 循环中逐个迭代它们。

将现有代码更改为:

$recipients = get-content C:\scripts\test.csv


foreach($rcpt in $recipients)
{
$smtpServer = "mail.server.com"
$msg = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$msg.From = "FromUser@email.com"
$msg.To.Add($rcpt)
$msg.subject = "Requiring Updates"
$msg.IsBodyHTML = $true
$body = @'
<html> 
  <body> 
    <font face="calibri">Hello, please read this test email.</font>
  </body> 
</html> 
'@ 

$msg.body = $body
$smtp.Send($msg)

}

希望它有所帮助。

答案 1 :(得分:0)

这是您现在更改要求后的新答案。

将emailIds直接放在csv文件中,没有引号,因为我已经附加了。现在,这将向从该文件中读取的所有收件人发送一封电子邮件。

$recipients = get-content C:\scripts\test.csv

Remove-Variable rcpt -ErrorAction Ignore

Remove-Variable result -ErrorAction Ignore

Remove-Variable final_result -ErrorAction Ignore
foreach($rcpt in $recipients)
{

$result += "'$rcpt'" + ","
$final_result=$result.Trim(',')

$smtpServer = "mail.server.com"
$msg = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$msg.From = "FromUser@email.com"
$msg.To.Add($final_result)
$msg.subject = "Requiring Updates"
$msg.IsBodyHTML = $true
$body = @'
<html> 
  <body> 
    <font face="calibri">Hello, please read this test email.</font>
  </body> 
</html> 
'@ 

$msg.body = $body


}
$smtp.Send($msg)