Search code examples
c#microsoft-graph-apimicrosoft-graph-sdksmicrosoft-graph-mail

Move message to another folder with graphClient 5.18


I need to move (some filtered) messages between folders at specified users with Microsoft Graph Api 5.18.

  • I created the API in Azure AD with the required permissions.
    • Mail.Read (Delegated)
    • Mail.ReadBasic (Delegated)
    • Mail.ReadWrite (Delegated)
    • User.Read (Delegated)
    • User.Read.All (Delegated)
    • User.ReadBasic.All (Delegated)
  • I can access the logged in user's messages and folders. (Delegated permission is working fine.)

The API documentation give an example with the Messages of the authenticated user (.Me).

https://learn.microsoft.com/en-us/graph/api/message-move?view=graph-rest-1.0&tabs=csharp

C#

// Code snippets are only available for the latest version. Current version is 5.x

var graphClient = new GraphServiceClient(requestAdapter);

var requestBody = new Microsoft.Graph.Me.Messages.Item.Move.MovePostRequestBody
{
    DestinationId = "deleteditems",
};
var result = await graphClient.Me.Messages["{message-id}"].Move.PostAsync(requestBody);

It is possible to configure the user id with CLI:

CLI

mgc users messages move post --user-id {user-id} --message-id {message-id} --body '{\
  "destinationId": "deleteditems"\
}\
'

How can I define the 'user id' instead of 'Me' in C#?

I'd like to make similar than this (specify the 'user id' with 'ArchiveUser.Id'):

var requestBody = new Microsoft.Graph.Users[ArchiveUser.Id].Messages.Item.Move.MovePostRequestBody
{
DestinationId = "deleteditems",
};
var result2 = await graphClient.Users[ArchiveUser.Id].Messages[item.Id].Move.PostAsync(requestBody);

UPDATE: What does the correct requestBody2 parameter look like for the following PostAsync parameter? I'd like to use another user id (ArchiveUser.Id) to move his messages. enter image description here

https://github.com/microsoftgraph/microsoft-graph-docs/blob/main/api-reference/v1.0/api/message-move.md


Solution

  • The class MovePostRequestBody is in the namespace Microsoft.Graph.Users.Item.Messages.Item.Move, so create the request body like this:

    try
    {
        var requestBody = new Microsoft.Graph.Users.Item.Messages.Item.Move.MovePostRequestBody
        {
            DestinationId = "{destination_mailbox_folder_id}",
        };
        var result2 = await graphClient.Users[ArchiveUser.Id].Messages[item.Id].Move.PostAsync(requestBody);
    }
    catch (ODataError ex)
    {
        Console.WriteLine(ex.Error.Code);
        Console.WriteLine(ex.Error.Message);
    }