Hello.
I've been trying to figure out how to send out email reminders when password is about to expire. This is done by powershell from our Domain Controller.
So far the results have been inconsistant.
1 out of 10 emails will be sent, and the rest gets the following error:
Send-Mailmessage : Unable to read data from the transport connection: net_io_connectionclosed.
At line:48 char:1
+ Send-Mailmessage -smtpServer $smtpServer -from $from -to ..
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.Mail.SmtpClient:SmtpClient) [Send-MailMessage], SmtpException
+ FullyQualifiedErrorId : SmtpException,Microsoft.PowerShell.Commands.SendMailMessage
What really throws me off here, is the fact that sometimes it works, and sometimes it doesn't.
I've tried with -port 587 aswell, to specify which port to use, but this makes the same failure.
When i try to run this script from my own PC instead of the Domain Controller, there is no errors. Even though they are on the same network.
Success and failure is with identical code:
$Credential = Get-Credential
$smtpServer="smtp.office365.com"
$expireindays = 7
$from = "UsingMyEmail"
Import-Module ActiveDirectory
$users = get-aduser -filter * -properties Name, PasswordNeverExpires, PasswordExpired, PasswordLastSet, EmailAddress |where {$_.Enabled -eq "True"} | where { $_.PasswordNeverExpires -eq $false } | where { $_.passwordexpired -eq $false }
foreach ($user in $users)
{
$Name = (Get-ADUser $user | foreach { $_.Name})
$emailaddress = $user.emailaddress
$passwordSetDate = (get-aduser $user -properties * | foreach { $_.PasswordLastSet })
$PasswordPol = (Get-AduserResultantPasswordPolicy $user)
if (($PasswordPol) -ne $null)
{
$maxPasswordAge = ($PasswordPol).MaxPasswordAge
}
else
{
$maxPasswordAge = (Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge
}
$expireson = $passwordsetdate + $maxPasswordAge
$today = (get-date)
$daystoexpire = (New-TimeSpan -Start $today -End $Expireson).Days
$subject="Your windows password will expire in $daystoExpire days"
$body ="Insert text here"
if ($daystoexpire -lt $expireindays)
{
Send-Mailmessage -smtpServer $smtpServer -from $from -to "UsingMyEmail" -Credential $Credential -UseSsl -subject $subject -body $body -bodyasHTML -priority High
}
}
Please note:
I've changed my filled the email spots with "UsingMyEmail" to keep them private.
Thank you in advance.