Send-MgUserMail: How to Send Emails with Graph PowerShell

This guide demonstrates how to use the Send-MgUserMail cmdlet in Microsoft Graph PowerShell to send emails from a user’s mailbox. Learn how to compose messages, add attachments, and send emails programmatically with practical examples.

The Send-MgUserMail cmdlet is a powerful tool in the Microsoft Graph PowerShell module enabling administrators to send emails on behalf of users in a Microsoft 365 environment. This article will cover the cmdlet's syntax, provide practical usage examples, discuss various use cases, and address common errors with their solutions.


Cmdlet Syntax

Send-MgUserMail -UserId <String> -BodyParameter <MessageBody> [<CommonParameters>]
  • -UserId: Specifies the user ID or UPN of the user to send the mail on behalf of.
  • -BodyParameter: Represents the message body and other mail properties like subject, recipients, etc.

Usage Examples

1. Sending Mail with CC

$params = @{
    Message = @{
        Subject = "Project Update"
        Body = @{
            ContentType = "Text"
            Content = "Please find the latest update on the project."
        }
        ToRecipients = @(
            @{
                EmailAddress = @{
                    Address = "recipient@example.com"
                }
            }
        )
        CcRecipients = @(
            @{
                EmailAddress = @{
                    Address = "ccrecipient@example.com"
                }
            }
        )
    }
    SaveToSentItems = $true
}

Send-MgUserMail -UserId "user@example.com" -BodyParameter $params

2. Sending Mail with Attachments

$params = @{
    Message = @{
        Subject = "Project Documents"
        Body = @{
            ContentType = "Text"
            Content = "Please find the attached documents related to the project."
        }
        ToRecipients = @(
            @{
                EmailAddress = @{
                    Address = "recipient@example.com"
                }
            }
        )
        Attachments = @(
            @{
                "@odata.type" = "#microsoft.graph.fileAttachment"
                Name = "ProjectPlan.docx"
                ContentBytes = [System.Convert]::ToBase64String([System.IO.File]::ReadAllBytes("C:\Path\To\ProjectPlan.docx"))
            }
            @{
                "@odata.type" = "#microsoft.graph.fileAttachment"
                Name = "Budget.xlsx"
                ContentBytes = [System.Convert]::ToBase64String([System.IO.File]::ReadAllBytes("C:\Path\To\Budget.xlsx"))
            }
        )
    }
    SaveToSentItems = $true
}

Send-MgUserMail -UserId "user@example.com" -BodyParameter $params

3. Sending Mail with Internet Message Headers

$params = @{
    Message = @{
        Subject = "Special Announcement"
        Body = @{
            ContentType = "Text"
            Content = "Here is an important announcement."
        }
        ToRecipients = @(
            @{
                EmailAddress = @{
                    Address = "recipient@example.com"
                }
            }
        )
        InternetMessageHeaders = @(
            @{
                Name = "X-Custom-Header-1"
                Value = "Custom Value 1"
            }
            @{
                Name = "X-Custom-Header-2"
                Value = "Custom Value 2"
            }
        )
    }
    SaveToSentItems = $true
}

Send-MgUserMail -UserId "user@example.com" -BodyParameter $params

Use Cases

  1. Automating Internal Notifications:
    • Scenario: In large organizations, employees often need to be informed about important internal updates, such as policy changes, IT outages, or upcoming events.
    • Implementation: Use Send-MgUserMail to automate sending notifications to all employees or specific departments about critical updates. These notifications can be triggered by events such as system outages or scheduled maintenance, ensuring timely communication.
    • Benefit: Streamlines the process of distributing important notifications across the organization, ensuring that employees are kept informed without relying on manual communication.
  2. Sending Customized Email Alerts for Task Deadlines:
    • Scenario: Project managers may need to remind team members of upcoming task deadlines or milestones, especially in fast-paced work environments.
    • Implementation: Use Send-MgUserMail to automatically send personalized email reminders to team members as project deadlines approach. These reminders can include details about the task, deadline, and any required actions.
    • Benefit: Helps ensure that project deadlines are met by keeping team members aware of their tasks, improving productivity and reducing the risk of missed deadlines.
  3. Automating Follow-Up Emails for Client Interactions:
    • Scenario: Sales or customer support teams often need to send follow-up emails after client meetings, inquiries, or support requests to maintain strong relationships and close deals.
    • Implementation: Use Send-MgUserMail to automatically generate and send follow-up emails after a specific trigger, such as after a client inquiry or meeting. These emails can be personalized with the client’s details and the context of the interaction.
    • Benefit: Automates routine follow-up tasks, ensuring timely and consistent communication with clients while reducing the manual effort required from sales and support teams.
  4. Delivering Scheduled Reports via Email:
    • Scenario: Many organizations rely on regular reports for monitoring performance, sales, or operations, which need to be sent to managers or stakeholders at specific intervals.
    • Implementation: Use Send-MgUserMail to automatically send reports to relevant recipients at scheduled intervals (daily, weekly, etc.). The email can include an attached report or a summary within the body.
    • Benefit: Ensures that key stakeholders receive timely reports without manual intervention, enabling faster decision-making based on up-to-date data.

Possible Errors & Solutions

Error Cause Solution
"Resource not found for the segment 'me'." This error occurs when the specified UserId does not exist or is incorrect. Verify the UserId or UPN provided in the -UserId parameter and ensure the user exists in the tenant.
"Insufficient privileges to complete the operation." This error occurs when the authenticated user does not have the necessary permissions to send mail on behalf of the specified user. Ensure the user has the Mail.Send permission granted. You may need to consent to the required permissions through the Azure AD portal or by using the Connect-MgGraph cmdlet with the appropriate scopes.

Connect-MgGraph -Scopes "Mail.Send"
"Attachment size exceeds the limit." This error occurs when the attachment size exceeds the allowable limit. Ensure that the total size of the attachments does not exceed the maximum allowed limit for email attachments in your tenant. Consider splitting the attachments into multiple emails if necessary.

Frequently Asked Questions

1. What is Send-MgUserMail used for?

Send-MgUserMail is a Microsoft Graph PowerShell cmdlet used to send emails programmatically from a user’s mailbox. It supports composing messages, adding recipients, and attaching files.

2. How can I send a simple email using Send-MgUserMail?

Use the following script to send a basic email:

$Body = @{
message = @{
            subject = "Test Email"
            body = @{
                    contentType = "Text"
                    content = "This is a test email."
                    }
                    toRecipients = @(@{emailAddress = @{address = "recipient@domain.com"}})
                }
            }
Send-MgUserMail -UserId "" -BodyParameter $Body -SaveToSentItems
                            

3. Can I send an email with an attachment?

Yes, include the attachments property in the body. Example:

$Attachment = @{
            name = "example.txt"
            contentBytes = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes("Attachment content"))
            contentType = "text/plain"
}
                            
$Body = @{
        message = @{
                    subject = "Email with Attachment"
                    body = @{
                            contentType = "Text"
                            content = "Please find the attachment."
                    }
                toRecipients = @(@{emailAddress = @{address = "recipient@domain.com"}})
                attachments = @($Attachment)
        }
}
Send-MgUserMail -UserId "" -BodyParameter $Body -SaveToSentItems
                            

4. What permissions are required to use Send-MgUserMail?

You need the Mail.Send permission in Microsoft Graph PowerShell. Ensure delegated permissions are granted to send emails from a user's mailbox.


Send Emails on Behalf of Another User

The Send-MgUserMail cmdlet allows admins to send messages on behalf of another user if proper permissions (like SendAs or SendOnBehalf) are granted.

This is particularly useful for delegates, shared mailboxes, or service accounts.
Include Rich HTML Content in Emails

You can send HTML-formatted messages using Send-MgUserMail by specifying the content type as HTML.

This lets you include tables, styled text, and clickable links, making your automated emails more professional and engaging.

Conclusion

The Send-MgUserMail cmdlet is a versatile tool for automating email communications within a Microsoft 365 environment. By understanding its syntax, parameters, and common use cases, administrators can efficiently leverage this cmdlet to streamline various email-related tasks. Additionally, being aware of potential errors and their solutions ensures smooth operation and troubleshooting.


Suggested Reading

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