Microsoft 365

Microsoft 365: Send E-Mails with PowerShell

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 = ''
From = $username
Subject = $subject
Body = $body
BodyAsHtml = $true
SmtpServer = ''
UseSSL = $true
Credential = $cred
Port = 25


### Send Mail

Send-MailMessage @hash -WarningAction Ignore

Fine! Here it is.

Anmerkung 2020-04-06 085948.png

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 store your Passwords and use them for Remote Authentication (Protect-CmsMessage)

PowerShell: Encrypt and Decrypt Data by using Certificates (Public Key / Private Key)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.