I have a script that I would like to dynamically send an email containing some info and go to certain people based on who in the company is running the script thanks to ActiveDirectory.
I have another portion of code that detects which OU the user or service account is running this from so for the sake of this question don't worry about that.
What I have so far is something like this:
function SendEmail
{
Send-MailMessage -To $Recipients -From "Info <[email protected]>" -Subject "Account Report" -Body $Body -SmtpServer smtpserver.domain.com
}
$To = Get-ADUser -Filter "(Name -like '*')" -Properties Name, EmailAddress -Searchbase $OUDetected | Format-List EmailAddress | Out-String
I am trying to utilize the Send-MailMessage cmdlet but emails have to be sent in a particular format to recipients.
A single recipient is:
"John Doe <[email protected]>"
Multiple recipients should look like:
"John Doe
<[email protected]>", "Jane Doe <[email protected]>"
The issue is tricky then as the result of $To is in the format:
EmailAddress: [email protected]
EmailAddress: [email protected]
This format needs to be converted to the multiple recipient example as shown above.
I am at a loss at how to properly grab the data, format it and be sure it stays in the format that Send-Mailmessage can use.
TL;DR - There needs to be a way that grabs the email address(es) of each user(s) in a given OU in ActiveDirectory and format that/those email address(es) so it may send using Send-MailMessage