使用powershell脚本使用多个附件发送电子邮件

时间:2021-01-04 08:02:07

标签: powershell

我存储了以下变量

PS C:>$PathArray
jagbir.singh1990@gmail.com
mr.singh@gmail.com

PS C:>$PathArray2
805775-1.zip
805775-2.zip

$Arrayresult = for ( $i = 0; $i -lt $max; $i++)
  {
      Write-Verbose "$($PathArray[$i]),$($PathArray2[$i])"
      [PSCustomObject]@{
          PathArray = $PathArray
          PathArray2 = $PathArray2
   
      }

PS C:>$Arrayresult

PathArray                                            PathArray2                                       
---------                                            ----------                                       
{jagbir.singh1990@gmail.com, mr.singh@gmail.com...}  {805775-1.zip, 805775-2.zip...}
{jagbir.singh1990@gmail.com, mr.singh@gmail.com...}  {805775-1.zip, 805775-2.zip...}

我想发送带有包含 zip file1 名称的正文文本的 email1 和带有包含 zip file2 名称的正文文本的 email2

例如: 发件人:jagbir.singh1990@gmail.com

正文:805775-1.zip 文件传输成功。

无需附件

代码:

foreach($X in $Arrayresult){
    Send-MailMessage -From $X.Patharray -To 'jagbir.singh1990@gmail.com' -Subject 'File Transfer completed successfully' -body 'File $X.PathArray2 transfer success'  -smtpServer 'smtp.gmail.com' -Port 465
}
Write-Host "Email sent.."

如何将每个 zip 文件的每封电子邮件分开 电子邮件 1 --> 文件 1 电子邮件 2 --> 文件 2

1 个答案:

答案 0 :(得分:1)

我不确定您为什么要将电子邮件地址和文件名保存在单独的数组中,然后为此将它们组合到一个 PSObject 数组中。

无论如何,第一个错误是您没有为变量 $max 指定值,它应该是两个数组中最小的一个的计数(我为这些数组使用了更具描述性的变量名称):

$max = [math]::Min($email.Count, $files.Count)

第二个是在您创建的每个 PSCustomObject 的属性中添加完整的数组,而不是输入数组的一个元素。

最后,我建议使用更简单的循环(而不是创建新的 PSObject 数组),使用 Splatting 作为 Send-MailMessage 的参数并在发送时添加一些错误检查:

类似于:

# array of email addresses to send TO
$email = 'jagbir.singh1990@gmail.com', 'mr.singh@gmail.com'
# array of filenames to use in the mail body
$files = '805775-1.zip', '805775-2.zip'

# determine the max number of iterations
$max = [math]::Min($email.Count, $files.Count)

# set up a hashtable for splatting the parameters to the Send-MailMessage cmdlet
$mailParams = @{
    From = 'me@gmail.com'
    Subject = 'File Transfer completed successfully' 
    SmtpServer = 'smtp.gmail.com'
    Port = 465
    # other parameters go here
}

for ($i = 0; $i -lt $max; $i++) {
    # inside the loop we add/update the parameters 'To' and 'Body'
    $mailParams['To'] = $email[$i]
    $mailParams['Body'] = "File $($files[$i]) transfer success" 

    try {
        Send-MailMessage @mailParams -ErrorAction Stop
        Write-Host "Email sent.."
    }
    catch {
        Write-Error "Email NOT sent.`r`n$($_.Exception.Message)"
    }
}