MeowMeow Posted February 13 Share Posted February 13 (edited) Bonjour à toutes et à tous, J'essaie d'envoyer des emails pour l'expiration des MDP AD via un script power shell : ### Variables modifiables # Nombre de jours avant l'expiration pour envoyer la notification $DateThreshold = 31 #Configuration email TTLSSL $password = "mon mdp" $userName = "email expéditeur" [SecureString]$securepassword = $password | ConvertTo-SecureString -AsPlainText -Force $credential = New-Object System.Management.Automation.PSCredential -ArgumentList $username, $securepassword [System.Net.ServicePointManager]::SecurityProtocol = 'Tls,TLS11,TLS12' # Serveur SMTP - Nom du serveur $SMTPServer = "smtp.office365.com" # Serveur SMTP - Numéro de port $SMTPPort = 567 # Serveur SMTP - Adresse e-mail de l'expéditeur $SMTPSender = "email expéditeur" # Serveur SMTP - Encodage Email $SMTPEncoding =[System.Text.Encoding]::UTF8 # Envoyer une synthèse aux administrateurs [boolean]$SendReportAdmin = $true # Adresse e-mail du destinataire pour la synthèse $SendReportAdminEmail = "mon email" ### Fonctions Function Send-MailMessageForUser{ <# .SYNOPSIS : Envoyer une notification à un utilisateur dont le mot de passe expire dans X jours (selon seuil) #> Param([Parameter(Mandatory=$true)][string]$SendMailUserGivenName, [Parameter(Mandatory=$true)][string]$SendMailUserSurname, [Parameter(Mandatory=$true)][string]$SendMailUserEmail, [Parameter(Mandatory=$true)][string]$SendMailUserPrincipalName, [Parameter(Mandatory=$true)][string]$SendMailUserPasswordExpirationDate) # Corps de l'email pour les utilisateurs $SendMailBody=@" <p>Bonjour $SendMailUserGivenName,</p> <p>Dans <b>moins de $DateThreshold jours</b>, le mot de passe du compte <b>$SendMailUserPrincipalName</b> va expirer.<br> <b>Pensez à le changer</b> avant qu'il arrive à expiration (date d'expiration : $SendMailUserPasswordExpirationDate)</p> Cordialement,<br> Le service informatique "@ # Objet de l'e-mail pour les utilisateurs $SendMailObject="$SendMailUserGivenName $SendMailUserSurname : votre mot de passe arrive à expiration !" # Envoyer l'e-mail Send-MailMessage -UseSsl -Credential $credential -Verbose -SmtpServer $SMTPServer -Encoding $SMTPEncoding ` -From $SMTPSender -To $SendMailUserEmail ` -Subject $SendMailObject ` -Body $SendMailBody -BodyAsHtml -Port $SMTPPort } ### Variables # Date du jour (format FileTime) $DateToday = (Get-Date).ToFileTime() # Date de référence (date du jour + nombre jours avant expiration pour la notification) $DateWithThreshold = (Get-Date).AddDays($DateThreshold).ToFileTime() # Liste des utilisateurs Active Directory $UsersInfos = Get-ADUser -Filter { (Enabled -eq $True) -and (PasswordNeverExpires -eq $False)} –Properties "DisplayName", "mail", "msDS-UserPasswordExpiryTimeComputed" | Select-Object -Property "GivenName", "Surname","mail", "UserPrincipalName", "msDS-UserPasswordExpiryTimeComputed" # Initialiser l'objet avec la liste des utilisateurs $UsersNotifList=@() # Traiter chaque utilisateur Foreach($User in $UsersInfos){ if(($User."msDS-UserPasswordExpiryTimeComputed" -lt $DateWithThreshold) -and ($User."msDS-UserPasswordExpiryTimeComputed" -gt $DateToday)){ $UserPasswordExpirationDate = [datetime]::FromFileTime($User."msDS-UserPasswordExpiryTimeComputed") $UserObj = New-Object System.Object $UserObj | Add-Member -Type NoteProperty -Name GivenName -Value $User.GivenName $UserObj | Add-Member -Type NoteProperty -Name Surname -Value $User.Surname $UserObj | Add-Member -Type NoteProperty -Name Email -Value $User.mail $UserObj | Add-Member -Type NoteProperty -Name UserPrincipalName -Value $User.UserPrincipalName $UserObj | Add-Member -Type NoteProperty -Name PasswordExpirationDate -Value ($UserPasswordExpirationDate).ToString('dd/MM/yyyy') $UsersNotifList+=$UserObj Send-MailMessageForUser -SendMailUserGivenName $User.GivenName -SendMailUserSurname $User.Surname -SendMailUserEmail $User.mail ` -SendMailUserPrincipalName $User.UserPrincipalName -SendMailUserPasswordExpirationDate ($UserPasswordExpirationDate).ToString('d MMMM yyyy') } } # Faut-il envoyer une synthèse aux administrateurs ? if(($SendReportAdmin -eq $true) -and ($UsersNotifList.Count -ne 0)){ # Corps de l'e-mail (sous la forme d'un tableau) $SendMailAdminBody = $UsersNotifList | ConvertTo-HTML -PreContent "Bonjour,<br><p>Voici la liste des comptes Active Directory dont le mot de passe expire dans moins de $DateThreshold jours.</p>" | Out-String | ForEach-Object{ $_ -replace "<table>","<table style='border: 1px solid;'>" ` -replace "<th>","<th style='border: 1px solid; padding: 5px; background-color:#014B83; color:#fff;'>" ` -replace "<td>","<td style='padding: 10px;'>" } # Envoyer l'e-mail Send-MailMessage -Verbose -SmtpServer $SMTPServer -Encoding $SMTPEncoding - ` -From $SMTPSender -To $SendReportAdminEmail ` -Subject "Synthèse - Expiration des mots de passe AD - $(Get-Date -Format dd/MM/yyyy)" ` -Body $SendMailAdminBody -BodyAsHtml -Port $SMTPPort } Et voici l'erreur qui me retourne : Send-MailMessage : Impossible de se connecter au serveur distant Au caractère C:\***************\mdpexpi.ps1:73 : 5 + Send-MailMessage -UseSsl -Credential $credential -Verbose -SmtpServer $SMTPS ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation : (System.Net.Mail.SmtpClient:SmtpClient) [Send-MailMessage], SmtpException + FullyQualifiedErrorId : SmtpException,Microsoft.PowerShell.Commands.SendMailMessage Vous avez une idée? Différent sources utilisées : ici et ici Merci. Edited February 13 by MeowMeow Quote Link to comment Share on other sites More sharing options...
brice.wernet Posted February 13 Share Posted February 13 Le port 567 au lieu de 587 peut-être? Quote Link to comment Share on other sites More sharing options...
MeowMeow Posted February 13 Author Share Posted February 13 (edited) il y a une heure, brice.wernet a dit : Le port 567 au lieu de 587 peut-être? Nop et testé aussi avec le port 25025 😞 Edited February 13 by MeowMeow Quote Link to comment Share on other sites More sharing options...
brice.wernet Posted February 13 Share Posted February 13 Et pour tester juste l'accès au serveur: qu'as tu comme erreur avec : Send-MailMessage -From meowmeow@cat-a-strophes.fr -To toto@pluton.com -Subject 'Hi from earth' -Body 'What's the weather like?' -SmtpServer smtp.office365.com -UseSsl -Credential (Get-Credential) Quote Link to comment Share on other sites More sharing options...
MeowMeow Posted February 13 Author Share Posted February 13 (edited) Même erreur. Avec pare-feu désactivé Send-MailMessage : Erreur lors du traitement. La réponse du serveur était: 5.7.3 STARTTLS is required to send mail [PAZP264CA0081.FRAP264.PROD.OUTLOOK.COM 2023-02-13T15:15:28.614Z 08DB0D481E93FE2F] Au caractère Ligne:1 : 1 + Send-MailMessage -SmtpServer smtp.office365.com Avec un autre code simple : + CategoryInfo : InvalidOperation : (System.Net.Mail.SmtpClient:SmtpClient) [Send-MailMessage], SmtpExcep tion + FullyQualifiedErrorId : SmtpException,Microsoft.PowerShell.Commands.SendMailMessage Edited February 13 by MeowMeow Quote Link to comment Share on other sites More sharing options...
MeowMeow Posted February 13 Author Share Posted February 13 Send-MailMessage : Impossible de lire les données de la connexion de transport : net_io_connectionclosed. Au caractère Ligne:1 : 1 + Send-MailMessage -From email@email.fr -To email@email.fr -Subject "Test ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation : (System.Net.Mail.SmtpClient:SmtpClient) [Send-MailMessage], SmtpExcep tion + FullyQualifiedErrorId : SmtpException,Microsoft.PowerShell.Commands.SendMailMessage Quote Link to comment Share on other sites More sharing options...
ashlol Posted February 13 Share Posted February 13 t'utilises bien -UseSsl car je ne le vois pas. dans ton script c'est écris port 567 mais c'est le 587 pour starttls et sinon Send-MailMessage est obsolète donc n'est peut être plus supporté pour se logguer sur un smtp office365. https://stackoverflow.com/questions/74941163/powershell-send-mailmessage-deprecated-future-consequences-for-people-still-re sinon juste pour être sûr si tu va sur office365 t'arrives bien à te logguer avec les identifiants mis ? et ton ip n'est pas bloquée après toutes ces tentatives infructueuse ça pourrait, à checker sur ton compte office365 Quote Link to comment Share on other sites More sharing options...
MeowMeow Posted February 14 Author Share Posted February 14 Résolu! Du coup. Repasser en 587. Puis, j'ai suivi ce site : https://stackoverflow.com/questions/20228644/smtpexception-unable-to-read-data-from-the-transport-connection-net-io-connect Activer le support TLS sur le centre admin de office365. Et voila 🙂 Quote Link to comment Share on other sites More sharing options...
MeowMeow Posted February 16 Author Share Posted February 16 Merci à tous pour vos réponses et solutions 🙂 Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.