27 August 2020

How to Send Email with Office365 and PowerShell

This is nice and handy.
I came across this at Adam the Automator, it's 2 ways to send mail with PowerShell.

One is with authenticated send the other with direct send.

The authenticated way:

# Get the credential            
$credential = Get-Credential            
            
## Define the Send-MailMessage parameters            
$mailParams = @{            
    SmtpServer                 = 'smtp.office365.com'            
    Port                       = '587' # or '25' if not using TLS            
    UseSSL                     = $true ## or not if using non-TLS            
    Credential                 = $credential            
    From                       = 'sender@yourdomain.com'            
    To                         = 'recipient@yourdomain.com', 'recipient@NotYourDomain.com'            
    Subject                    = "SMTP Client Submission - $(Get-Date -Format g)"            
    Body                       = 'This is a test email using SMTP Client Submission'            
    DeliveryNotificationOption = 'OnFailure', 'OnSuccess'            
}            
            
## Send the message            
Send-MailMessage @mailParams
The direct send way:
## Build parameters            
$mailParams = @{            
    SmtpServer                 = '.mail.protection.outlook.com'            
    Port                       = '25'            
    UseSSL                     = $true               
    From                       = 'sender@yourdomain.com'            
    To                         = 'recipient@yourdomain.com'            
    Subject                    = "Direct Send $(Get-Date -Format g)"            
    Body                       = 'This is a test email using Direct Send'            
    DeliveryNotificationOption = 'OnFailure', 'OnSuccess'            
}            
            
## Send the email            
Send-MailMessage @mailParams
See the full blogpost here

No comments:

Post a Comment