Reputation: 1
I have a requirement to send email to thousands of different recipients with a different attachment to each of them. I have the list of recipients in a text file and the list of attachment paths in another text file. For the first recipient in the text file, first attachment path should be used. For the second recipient in the text file, second attachment path should be used.
The code below sends all attachments to all recipients separately. But I would like this to work as I described above. Only one email should be sent to each recipient with the corresponding attachment.
Please let me know if this is achievable. I can also copy the recipients and paths to attachments in two different columns of an Excel spreadsheet if it is possible with Excel.
I can achieve this by constructing thousand different send-mailmessage lines with Excel but that looks like an ugly way of doing. That's why I would like to know if there is a better way of doing this.
$attachments = get-content C:\attach.txt
$recipients = get-content C:\recip.txt
foreach ($attachment in $attachments)
{
foreach ($recipient in $recipients)
{
Send-MailMessage -From "[email protected]" -To $recipient -subject "Test" -smtpServer smtp.server.com -attachments $attachment
}
}
Upvotes: 0
Views: 1478
Reputation: 12321
Use a for loop to iterate through both files in tandem:
for ($i = 0; $i -lt $recipients.Count; $i++) {
Send-MailMessage -From "[email protected]" -To $recipients[$i] -Subject "Test" -SmtpServer smtp.server.com -Attachments $attachments[$i]
}
Presumably the number of lines in both files should be the same, so $recipients.Count
is the number of lines in both recip.txt and attach.txt; you could use $attach.Count
in the for loop just as well.
Import-Csv <path_to_csvfile> | %{Send-MailMessage -From "[email protected]" -To $_.Recipient -Subject "Test" -SmtpServer smtp.server.com -Attachments $_.Attachment}
That's probably a better idea, because you're less likely to have mistakes matching the attachments to the right recipients if they're in the same file. With separate lists, one error could result in all recipients after that point receiving the wrong attachments.
Upvotes: 0
Reputation: 68341
One possibility:
$MailParams =
@{
From = "[email protected]"
Subject = "Test"
SmtpServer = 'smtp.server.com'
}
$recipients = get-content C:\recip.txt
get-content C:\attach.txt |
foreach { $i=0 } { $_ | Send-MailMessage @MailParams -To $recipients[$i++] }
Upvotes: 1