Imagine you need to inform an user about something which had already been automated in a PowerShell script. You do not want to start a manual task (e.g. sending an email) every time the script is executed. Especially if you need it multiple times per day. So I decided to extend the script with the email-sending function. Just a few lines of code are necessary and you can adapt it to your needs. Mail Subject and Mail Body can be modified and even attachments can be added. Sending Email with PowerShell
To show you the possibilities, the following script reads the assigned groups of an Active Directory user and exports them to a .txt file. Then, the email data gets specified and afterwards the email will be sent to the recipient.
$Permissions = Get-ADPrincipalGroupMembership -Identity $Username | Select name | Sort-Object name | Out-File -FilePath C:\temp\AssignedGroups.txt
$SmtpServer = 'myServer.myDomain.com'
$SmtpPort = 587
$FromSender = 'mySender@myDomain.com'
$Recipient = 'myRecipient@myDomain.com'
$Subject = 'Assigned groups from : ' + $UserName
$PermissionsFilePath = "C:\temp\AssignedGroups.txt"
$Body = Get-Content -Path $PermissionsFilePath | Out-String
Send-MailMessage -SmtpServer $SmtpServer -Port $SmtpPort -From $FromSender -To $Recipient -Subject $Subject -Body $Body -Attachments $PermissionsFilePath
I would definitely recommend you to check out the Microsoft Docs about the Send-MailMessage command in order to properly adapt it to your needs and requirements. You can also combine that script with other ones. For example, you can export Active Directory Groups and their members from a specific organizational unit as CSV and send an automated email message within a scheduled task – there are no limitations.
Sending Email with PowerShell