Using New-MgUserMessage in Microsoft Graph PowerShell

This guide demonstrates how to use the New-MgUserMessage cmdlet in Microsoft Graph PowerShell to draft new emails. Learn how to compose messages, add recipients, and include attachments with practical examples

The New-MgUserMessage cmdlet is a powerful tool in the Microsoft Graph PowerShell module enabling administrators to create new messages in a user's mailbox. This article will delve into the cmdlet's syntax, provide usage examples, share tips, highlight use cases, and address possible errors and solutions.


Cmdlet Syntax

New-MgUserMessage -UserId <String> -BodyParameter <IMicrosoftGraphMessage> [<CommonParameters>]
  • -UserId: The ID or User Principal Name (UPN) of the user.
  • -BodyParameter: The message content provided as a hashtable.

Usage Examples

Example 1: Create a Simple Email Message

$params = @{
    subject = "Meeting Reminder"
    body = @{
        contentType = "Text"
        content = "This is a reminder for the team meeting scheduled for tomorrow at 10 AM."
    }
    toRecipients = @(
        @{
            emailAddress = @{
                address = "john.doe@example.com"
            }
        }
    )
}

New-MgUserMessage -UserId "jane.doe@example.com" -BodyParameter $params
Screenshot of PowerShell script creating a simple email message using New-MgUserMessage, with parameters for subject, body, and recipient email address.​

Example 2: Create an HTML Email Message

$params = @{
    subject = "Project Update"
    body = @{
        contentType = "HTML"
        content = "<p>Dear Team</p><p>Please find the latest updates on the project.</p><p>Best Regards<br/>Jane</p>"
    }
    toRecipients = @(
        @{
            emailAddress = @{
                address = "team@example.com"
            }
        }
    )
}

New-MgUserMessage -UserId "jane.doe@example.com" -BodyParameter $params
Screenshot of PowerShell script drafting an HTML-formatted email using New-MgUserMessage, showcasing the inclusion of HTML tags in the email body.

Example 3: Create an Email with Attachments

$params = @{
    subject = "Monthly Report"
    body = @{
        contentType = "Text"
        content = "Please find the attached monthly report."
    }
    toRecipients = @(
        @{
            emailAddress = @{
                address = "manager@example.com"
            }
        }
    )
    attachments = @(
        @{
            "@odata.type" = "#microsoft.graph.fileAttachment"
            name = "report.pdf"
            contentBytes = [System.Convert]::ToBase64String([System.IO.File]::ReadAllBytes("C:\Reports\report.pdf"))
        }
    )
}

New-MgUserMessage -UserId "jane.doe@example.com" -BodyParameter $params
​Screenshot of PowerShell script demonstrating the creation of an email with an attachment using New-MgUserMessage, highlighting the process of encoding a PDF file to Base64.

Cmdlet Tips

  • Use Hashtables for BodyParameter: Ensure you format the -BodyParameter as a hashtable for easier readability and maintainability.
  • HTML Formatting: Utilize HTML content type for richer email content and formatting options.
  • Base64 Encoding for Attachments: Convert file contents to Base64 strings for attaching files to the message.
  • Ensure Proper Permissions: Before using New-MgUserMessage, verify that the executing account has the necessary permissions, such as Mail.ReadWrite and Mail.Send. You can grant these permissions using the Connect-MgGraph cmdlet:
  • #For Using New-MgUserMessage
    Connect-MgGraph -Scopes “Mail.ReadWrite” 
    #For Using Send-MgUserMessage
    Connect-MgGraph -Scopes “Mail.Send” 
  • Draft Before Sending: It's a best practice to create a draft of your email using New-MgUserMessage before sending it. This allows you to review and modify the message as needed:
  • $draft = New-MgUserMessage -UserId "your.email@example.com" -BodyParameter $params
    Send-MgUserMessage -UserId "your.email@example.com" -MessageId $draft.Id
    This approach provides an opportunity to verify the email content before dispatching it.
  • Error Handling: Implement error handling to manage issues such as invalid email addresses or missing attachments. For example:
  • try {
        $draft = New-MgUserMessage -UserId "your.email@example.com" -BodyParameter $params
        Send-MgUserMessage -UserId "your.email@example.com" -MessageId $draft.Id
    }
    catch {
        Write-Error "An error occurred: $_"
    }

    This script attempts to send the email and catches any errors that occur during the process.


Use Cases

  1. Automating Welcome Emails for New Employees
    • Scenario: When new employees join the organization, it’s essential to send them welcome emails with necessary information such as login credentials, policies, and orientation schedules.
    • Implementation: Use New-MgUserMessage to automate the process of sending personalized welcome emails to new hires. The script can be integrated with HR systems to trigger automatically upon account creation.
    • Benefit: Streamlines the onboarding process by ensuring that all new employees receive consistent and timely communication with essential onboarding details, reducing the administrative burden on HR teams.
  2. Sending Automated Notifications for Project Updates:
    • Scenario: Project managers need to send regular updates or notifications to team members about project milestones, status changes, or upcoming deadlines.
    • Implementation: Use New-MgUserMessage to automate sending email notifications to the relevant team members. This ensures that everyone is kept up to date with critical project information without requiring manual intervention.
    • Benefit: Improves team coordination and ensures that key project updates are communicated efficiently and on time, enhancing overall project management.
  3. Generating and Sending Daily Reports via Email:
    • Scenario: Many organizations need to send daily or weekly reports to management or stakeholders. These reports can include sales data, system statuses, or other operational insights.
    • Implementation: Use New-MgUserMessage to automatically send reports generated by scripts. For example, a script that generates a daily system health report can use New-MgUserMessage to send the report to IT managers.
    • Benefit: Automates the distribution of critical reports, ensuring they reach the intended recipients without manual effort, improving decision-making based on timely data.
  4. Sending Targeted Email Campaigns:
    • Scenario: Internal communications teams may need to send targeted email campaigns to specific departments, teams, or individuals within the organization for announcements, surveys, or events.
    • Implementation: Use New-MgUserMessage to automate sending bulk emails to a predefined list of recipients, ensuring that internal announcements are delivered efficiently and at scale.
    • Benefit: Helps centralize and automate internal email communications, improving delivery speed and ensuring that important messages reach the intended audience without relying on external tools.

Possible Errors & Solutions

Error: "Authentication_DelegateAuthFailure"

Cause: The authentication token provided is not valid or has expired.

Solution: Ensure you have a valid authentication token. Re-authenticate using the Connect-MgGraph cmdlet.

Connect-MgGraph -Scopes "Mail.Send"

Error: "ResourceNotFound"

Cause: The specified user ID or UPN does not exist.

Solution: Verify the user ID or UPN. Ensure it is correct and the user exists in your tenant.

Error: "InvalidRequest"

Cause: The message body parameter is not correctly formatted.

Solution: Double-check the format of the -BodyParameter. Ensure all required fields are included and correctly structured.


Frequently Asked Questions

1. What is New-MgUserMessage used for?

New-MgUserMessage is a Microsoft Graph PowerShell cmdlet used to create draft email messages in a user’s mailbox, with options to specify recipients, subject, body, and attachments.

2. How can I ensure the draft is saved in the user’s mailbox?

The draft is automatically saved when using New-MgUserMessage. You can verify it by listing messages in the Drafts folder:

Get-MgUserMailFolderMessage -UserId "<UserPrincipalName>" -MailFolderId "Drafts"

3. What permissions are required to draft messages?

You need the Mail.ReadWrite permission in Microsoft Graph PowerShell. Ensure appropriate permissions are granted in Azure AD.

4. How can I add multiple recipients to an email using New-MgUserMessage?

You can include multiple recipients by adding their email addresses to the toRecipients array within the -BodyParameter hashtable. For example:

$params = @{
    subject = "Team Meeting"
    body = @{
        contentType = "Text"
        content = "Reminder for the team meeting scheduled tomorrow at 10 AM."
    }
    toRecipients = @(
            @{
                emailAddress = @{
                        address = "john.doe@example.com"
                }
             },
            @{
                emailAddress = @{
                        address = "jane.smith@example.com"
                }
             }
        )
    }
New-MgUserMessage -UserId "your.email@example.com" -BodyParameter $params

This script drafts an email addressed to both John Doe and Jane Smith.

5. How do I specify the sender of the email when using New-MgUserMessage?

The sender is determined by the UserId parameter, which specifies the mailbox where the draft is created. To send an email from a shared mailbox or on behalf of another user, ensure you have the appropriate permissions (e.g., "Send As" or "Send on Behalf") and specify the shared mailbox's user ID or UPN in the UserId parameter.


Conclusion

The New-MgUserMessage cmdlet is a versatile tool for creating and sending email messages programmatically within a user's mailbox. By understanding its syntax, leveraging usage examples, and being aware of potential errors, administrators can effectively automate email communications, improve workflow efficiency, and enhance their Microsoft 365 environment management. Whether for automated notifications, report distributions, or team communications, New-MgUserMessage offers a robust solution for a variety of scenarios.


Related Articles:

Using Get-MgDirectoryRole in Graph PowerShell
Using Get-MgUserLicenseDetail in Graph PowerShell
Using Find-GraphMgCommand in Graph PowerShell
Connect to Microsoft 365 Using PowerShell
How to Create Bulk Users in Office 365 Using Graph PowerShell?
Create Microsoft 365 Group Using Microsoft Graph PowerShell
Block Microsoft 365 User Using Microsoft Graph PowerShell
Assign Microsoft 365 License Using Graph PowerShell
Microsoft 365 User Management Using Graph PowerShell
Checking Group Membership in Microsoft 365
Bulk Assign Microsoft 365 License
Find Inactive Users in Microsoft 365
Using Powershell Graph Search Query
Using Powershell Graph Filter Query
Using Where-Object In Graph PowerShell
Using Expand Property In Graph PowerShell
Using Select Object In Graph PowerShell
Using -Contains Operator In Graph PowerShell
Add User to Multiple Microsoft 365 Groups Using Graph PowerShell
Get Microsoft 365 User Location Using Graph PowerShell
Import Microsoft 365 Groups from CSV File Using Graph PowerShell
Microsoft 365 Group User Import Using Graph PowerShell

© m365corner.com. All Rights Reserved. Design by HTML Codex