Microsoft Graph PowerShell is a powerful tool for administrators to manage Microsoft 365 environments programmatically. Two important cmdlets, New-MgUserMessage
and Send-MgUserMessage
, can be combined to create and send emails seamlessly. This article walks you through the process of using these cmdlets together, with detailed steps, tips, and troubleshooting guidance.
# Create the draft message
$draftMessage = @{
subject = "Reminder: Upcoming Meeting"
body = @{
contentType = "HTML"
content = "This is a reminder for your upcoming meeting scheduled for tomorrow at 10 AM."
}
toRecipients = @(@{ emailAddress = @{ address = "jane.doe@domain.com" } })
}
# Create the message and retrieve the MessageId
$message = New-MgUserMessage -UserId "john.doe@domain.com" -BodyParameter $draftMessage
# Send the message
Send-MgUserMessage -UserId "john.doe@domain.com" -MessageId $message.Id
$draftMessage
object defines the email's structure, including the subject, body content, and recipients. The body content is formatted in HTML, making it possible to include rich text formatting, links, and other elements.New-MgUserMessage
cmdlet sends the draft message data to Microsoft Graph and creates the message in the sender's Drafts folder. The cmdlet returns a message object, from which the unique MessageId
is extracted for the next step.Send-MgUserMessage
cmdlet takes the MessageId
and sends the email on behalf of the specified user. This modular approach separates the creation and sending processes, allowing additional actions like reviewing or modifying drafts before sending.
try {
# Code to create and send message
} catch {
Write-Error "An error occurred: $_"
}
Mail.Send
and Mail.ReadWrite
application permissions to the Azure AD app. Without these, the script will fail.Error | Cause | Solution |
Access Denied | Insufficient permissions in Azure AD | Ensure the app has Mail.Send and Mail.ReadWrite permissions. |
User Not Found | Incorrect -UserId or user does not exist |
Verify the User Principal Name (UPN) or user ID is correct. |
Invalid Object | Malformed draft message | Ensure $draftMessage adheres to the required schema. |
API Throttling | Too many requests in a short time | Implement retry logic with exponential backoff. |
Combining New-MgUserMessage
and Send-MgUserMessage
simplifies the process of automating email communications using Microsoft Graph PowerShell. By understanding their interplay, administrators can streamline operations and reduce manual workload. With the provided script and best practices, you are well-equipped to implement robust email solutions in your Microsoft 365 environment.
© m365corner.com. All Rights Reserved. Design by HTML Codex