This script uses the Get-ADUser cmdlet to retrieve user accounts that are enabled, have a set expiration date, and are expiring within the next 7 days. It then loops through the accounts and adds their name, email address, and expiration date to an HTML table in the email body. Finally, the script sends the email using the Send-MailMessage cmdlet, specifying the SMTP server, sender address, recipient address, subject, HTML body, and the -BodyAsHtml parameter to indicate that the email body is in HTML format.
Note that you’ll need to replace the $smtpServer, $fromAddress, and $toAddress variables with your own values. You may also need to modify the Get-ADUser filter to match your organization’s requirements.
# Set variables
$smtpServer = "your-smtp-server.com"
$fromAddress = "sender@yourdomain.com"
$toAddress = "recipient@yourdomain.com"
$subject = "Account Expiry Report"
$body = ""
# Set the report end date to 7 days from now
$startdate=(get-date)
$reportEndDate = (Get-Date).AddDays(7)
# Get all user accounts whose expiration date is within the next 7 days
$expiringAccounts = Get-ADUser -Filter {Enabled -eq $true -and AccountExpirationDate -gt $startdate -and AccountExpirationDate -lt $reportEndDate} -Properties AccountExpirationDate, EmailAddress
# Generate the email body
$emailbody += "<html><body><table border='1' cellpadding='5'><tr><th>Name</th><th>Email</th><th>Expiration Date</th></tr>"
foreach ($account in $expiringAccounts) {
$emailBody += "<tr><td>$($account.Name)</td><td>$($account.EmailAddress)</td><td>$($account.AccountExpirationDate)</td></tr>"
}
$emailBody += "</table></body></html>"
# Send HTML email
$credentials = new-object Management.Automation.PSCredential $smtpUsername, ($smtpPassword | ConvertTo-SecureString -AsPlainText -Force)
Send-MailMessage -SmtpServer $smtpserver -Port 587 -UseSsl -Credential $credentials -To amitceh@gmail.com -From $from -Subject $subject -Body $emailbody -BodyAsHtml