Sending E-Mails for monitoring or documenting purposes is a common procedure in Windows networks. When you move to the cloud, there is no more on-premise exchange that means your service accounts have to send e-mails via Exchange Online. If you are currently in a migration process to Microsoft 365 you might consider changing your scripts to point to the Microsoft servers residing in the cloud.
This what this blog post is about. I will provide you a sample code you can build on to send e-mails via Exchange Online.
Sending Mails with Microsoft 365 via PowerShell
To send mails with PowerShell and the Microsoft 365 mail servers no additional configuration is required. The Microsoft mail servers listen to port 25 or port 587 (SSL) and that’s fine.
Copy the code and enter your username (e-mail address) and your password and send the mail to someone of your choosing.
### Ask for credentials $username = Read-Host 'Enter e-mail address' $password = Read-Host "Enter password of $username" -AsSecureString $cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username, $password $subject = 'Alert: Test!' $body = 'This is for testing purposes' ### Splatting with Hash Table $hash = @{ To = 'patrick.gruenauer@yourdomain.com' From = $username Subject = $subject Body = $body BodyAsHtml = $true SmtpServer = 'smtp.office365.com' UseSSL = $true Credential = $cred Port = 25 } ### Send Mail Send-MailMessage @hash -WarningAction Ignore
Fine! Here it is.
With scripts, however, you will run into problems: How should you specify the password if not in plain text? Don’t worry, there is a solution. How to encrypt passwords inside scripts see:
PowerShell: Encrypt and Decrypt Data by using Certificates (Public Key / Private Key)
Categories: Microsoft 365, PowerShell