Thursday, 12 September 2019

Send Email using PowerShell command and Graph API

We can use the Send-MailMessage cmdlet to send e-mail from Powershell script and you can use Send mail API endpoint to send a message using Microsoft Graph API.

Send Email using PowerShell command with Office 365 SMTP Server settings

You can replace the required parameter values ($username, $password, $from and $to) in below script and run the commands to send mail. Here, we are using Office 365 SMTP server, you can also use different mail server settings with this script by providing required inputs.
$username = ""
$password = "user_password"
$sstr = ConvertTo-SecureString -string $password -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential -argumentlist $username, $sstr
$from = ""
$to = ""
$body = "This is a test email"
$subject = "Test message"
Send-MailMessage -To $to -from $from -Subject $subject -Body $body -BodyAsHtml -SmtpServer "" -UseSSL -Credential $cred -Port 587
Troubleshooting : Fix: Send-MailMessage : The SMTP server requires a secure connection or the client was not authenticated

Send Email using Microsoft Graph API

The Send mail API requires the permission Mail.Send. If you have valid Graph AccessToken with this permission, you can easily send mail without providing user credentials from Powershell. Before proceed, replace the parameters $AccessToken and "".
$AccessToken = "eyJ0***Access Token with Mail.Send permission*****"
$ApiUrl = ""
# Create JSON Body object
$Body = 
"message" : {
"subject": "Test message",
"body" : {
"contentType": "Text",
"content": "This is test mail"
"toRecipients": [{"emailAddress" : { "address" : "" }}]
Invoke-RestMethod -Headers @{Authorization = "Bearer $AccessToken"} -Uri $ApiUrl -Method Post -Body $Body -ContentType "application/json"


No comments:

Post a Comment