PowerShell script to send activation link emails for Forgot Password or Reset Password requests
Scenario:
We know there are plenty number of web sites online and almost all of them will have a user login page with support for “Forgot Password”/”Reset Password” option. Considering it such a basic functionality, whatif this “Forgot Password”/”Reset Password” request email system has issues and you want to setup an automation script in the interim. This script will address such a requirement and can come handy for most of the web developers.
Requirement Specifications: A Powershell script that
- Runs on a Windows Server 2008 x64 bit server with PowerShell version v1.0 and
- Connects to Oracle DataBase hosted on a Linux/Fedora x64bit system and
- Reads the new “Forgot Password”/”Reset Password” entries from an Oracle DB table
- Frames a message that can be sent as in email form to the requested user
- Uses a SMTP server to send the emails
- Saves the Data of the users/email to whom emails have been sent
- Ensures duplicates emails are not sent to the users
- Writes to the log upon
- Successfully sending an email, along with the details to which user email sent and the email subject and the sent time
- if there are no “Forgot Password”/”Reset Password” entries in the last 15 minutes
- if it find same user within 15 minutes, ignore sending the email again
- Runs as a Windows Scheduled task at every 14 minutes for 24 hours.
- Script:
[code language=”powershell”]
$LogFile = "C:\scripting\Send-Emails.log"
$connectionString = "Data Source=ORALAB01.TESTLAB.LAN;User Id=reportsadmin;Password=Rep0rTs;Integrated Security=no"
$queryString = "SELECT FROM_ADDR, TO_ADDR, SUBJECT, TXT, SENT FROM EmailActivation Order by firstname desc"
[System.Reflection.Assembly]::LoadWithPartialName("System.Data.OracleClient") | Out-Null
$connection = New-Object System.Data.OracleClient.OracleConnection($connectionString)
$command = new-Object System.Data.OracleClient.OracleCommand($queryString, $connection)
$connection.Open()
$users = $command.ExecuteReader()
$Counter = $users.FieldCount
$ResCounter = $users.HasRows
if (! $ResCounter) {
$Date = (Get-Date -Format F)
Add-Content $LogFile "$Date : No records found in last 15 minutes"
}
while ($users.Read()) {
$smtpServer = "192.68.2.14"
$smtpFrom = $users.GetValue(0)
$smtpTo = $users.GetValue(1)
$messageSubject = $users.GetValue(2)
$messageBody = $users.GetValue(3)
$AlreadySent = (Get-Item -path Hklm:\SOFTWARE\MyAppUsers).GetValue("$smtpTo")
if (! $AlreadySent) {
$smtp = New-Object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($smtpFrom,$smtpTo,$messagesubject,$messagebody)
new-itemproperty -path Hklm:\SOFTWARE\MyAppUsers -name $smtpTo -value 1 -propertyType STRING | Out-null
$Date = (Get-Date -Format F)
Add-Content $LogFile "$Date : Sent [$messageSubject] to [$smtpTo]"
} else {
$Date = (Get-Date -Format F)
Add-Content $LogFile "$Date : Mail [$messageSubject] already sent to [$smtpTo]"
}
}
$connection.Close()
[/code]