Send Email using PowerShell command and Graph API

We can use the Send-MailMessage cmdlet to send email using powershell and you can use Send mail API endpoint to send a message using Microsoft Graph API.

Send Email 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 = "[email protected]"
$password = "user_password"
$sstr = ConvertTo-SecureString -string $password -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential -argumentlist $username, $sstr
$from = "[email protected]"
$to = "[email protected]"
$body = "This is a test email"
$subject = "Test message"
Send-MailMessage -To $to -from $from -Subject $subject -Body $body -BodyAsHtml -SmtpServer "smtp.office365.com" -UseSSL -Credential $cred -Port 587

Troubleshooting : Fix: Send-MailMessage : The SMTP server requires a secure connection or the client was not authenticated

Send Email with 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 “[email protected]”.

$AccessToken = "eyJ0***Access Token with Mail.Send permission*****"
$ApiUrl = "https://graph.microsoft.com/v1.0/me/sendMail"
# Create JSON Body object
$Body = 
@"
{
"message" : {
"subject": "Test message",
"body" : {
"contentType": "Text",
"content": "This is test mail"
},
"toRecipients": [{"emailAddress" : { "address" : "[email protected]" }}]
}
}
"@ 
Invoke-RestMethod -Headers @{Authorization = "Bearer $AccessToken"} -Uri $ApiUrl -Method Post -Body $Body -ContentType "application/json"

Advertisement

Leave a Comment