To all,
I have a csv where every row has a contractors samaccount, its account expiration date, the contractor's supervisor name and respective email address.
I have the following data in my csv:
Name,AccountExpirationDate,Submitter,SubmitterEmail
Username1,9/21/2019,Submitter1,[email protected]
Username2,9/22/2019,Submitter2,[email protected]
Username3,9/23/2019,Submitter3,[email protected]
When I execute the code below, it does send an email for each row but the message only states username3 data in each email. How can I correct this so that [email protected] receives username1 data, likewise for submitter2 receiving username2 data, etc?
$from = "Your Friends in IT <[email protected]>"
$subject = "Your contractors's login account will expire soon!"
$body = "Hello <br>"
$body += "Your contractor's login account for <b>$Name</b></font> is set to expire on<b> $AccountExpirationDate</b>.<br>"
$body += "Kind Regards,<br><br>"
$body += "Your friends in IT"
$csv = Import-Csv -Path "C:\ps\SAC-Accounts-ExpiringSoon.csv"
$csv | foreach {
$Name = $_.name
$to = $_.SACSubmitterEmail
$_.AccountExpirationDate = $_.AccountExpirationDate -as [datetime]
$_
}
ForEach ($user in $csv)
{
$mail = New-Object System.Net.Mail.Mailmessage $from, $to, $subject, $body
$mail.IsBodyHTML=$true
$server = "mail.b.com"
# $port = 25
$Smtp = New-Object System.Net.Mail.SMTPClient $server,$port
$Smtp.Credentials = [system.Net.CredentialCache]::DefaultNetworkCredentials
$smtp.send($mail)
}
$csv | foreach {}is not needed if you already have a foreach loop after it that iterates over the same data. Combining your efforts into one loop will probably fix most of the problems. Since you aren't doing anything with theforeach-objectexcept setting variables, when you reach the next loop you only have the last values set by the previousforeach-object. Your intention appears to be to loop twice but simultaneously, but it doesn't have that effect.$_.SACSubmitterEmailis not mentioned in the script or CSV columns. You might fix the stated problem by changing this line:$mail = New-Object System.Net.Mail.Mailmessage $from, $to, $subject, $bodyto$mail = New-Object System.Net.Mail.Mailmessage $from, $user.SubmitterEmail, $subject, $body