Using New-MgUserMessage with Send-MgUserMessage to Send Emails

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.

The Script: Creating and Sending an Email


# 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
                            

How the Script Works

  • Drafting the Message: The $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.
  • Creating the Message: The 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.
  • Sending the Message: The 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.

Tips and Best Practices

  • Error Handling: Use try-catch blocks to handle exceptions and log errors effectively:
    try {
        # Code to create and send message
    } catch {
        Write-Error "An error occurred: $_"
    }
  • Ensure Correct Permissions: Assign the Mail.Send and Mail.ReadWrite application permissions to the Azure AD app. Without these, the script will fail.
  • Test in a Non-Production Environment: Always test your script in a sandbox environment to avoid accidental emails to unintended recipients.
  • Dynamic Recipients: Use variables or external data sources (like a CSV file) to populate recipient email addresses dynamically.
  • Monitor Throttling Limits: Microsoft Graph has API rate limits. For bulk operations, include pauses to prevent throttling.

Possible Errors and Solutions

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.

Use Cases

  • Automated Notifications: Send reminders for upcoming meetings or pending tasks.
  • Mass Communication: Combine with a loop to send bulk emails to multiple recipients.
  • Customized Alerts: Create personalized messages with dynamic content for specific users.
  • Scheduled Emails: Integrate with task schedulers or workflow automation tools for timed messages.

Conclusion

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