microsoft-graph-apimicrosoft-graph-mail

how to receive anly the Id of a newly created email draft by using microsoft-graph


With Microsoft Graph 4 I used to write my queries myself.

For an draft creation I used (I remove error handling for brevity):

using GM = Microsoft.Graph.Models;
GM.Message mgm = new GM.Message { /* ... */ };

StringContent baContent = new StringContent(
GetSerializedMessage(mgm), Encoding.UTF8, "application/json");
baContent.Headers.Add("Prefer", "IdType=ImmutableId, return=minimal");

string webApiUrl = $"{_apiUrl}v1.0/users/{senderId}/messages";

HttpResponseMessage response = await _httpClient.PostAsync(webApiUrl, baContent);
return System.Text.Json.JsonSerializer.Deserialize<GM.Message>(
    await response.Content.ReadAsStringAsync());

So I used a specific header to only receive ne Id of the created draft.

I migrate to sdk v5 and decide to stick to it. So my new code is

using GM = Microsoft.Graph.Models;
GM.Message mgm = new GM.Message { /* ... */ };

return await _gsc.Users[senderId].Messages.PostAsync(mgm
   , rc => { rc.Headers.Add("Prefer", "IdType=ImmutableId, return=minimal"); }
);

much more concise, but it returns null.

If I use

return await _gsc.Users[senderId].Messages.PostAsync(mgm);

then I can retrieve the Id among all the other elements of the message (including the attachments that are sent back)

What do I do wrong ?


Solution

  • Because, you have added to Prefer header the value return=minimal, it will cause that the POST request will return the code 204 No Content and empty response.

    I can't confirm whether it's expected behavior, but I would expect that the response will contain at least id when Prefer:return=minimal. I can reproduce the same behavior in Graph Explorer.

    As a workaround, do not add return=minimal.

    using GM = Microsoft.Graph.Models;
    GM.Message mgm = new GM.Message { /* ... */ };
    
    return await _gsc.Users[senderId].Messages.PostAsync(mgm
       , rc => { rc.Headers.Add("Prefer", "IdType=\"ImmutableId\""); }
    );