0
votes

I am trying to send an email using the Microsoft Graph API, and getting the following response:

StatusCode: 401, ReasonPhrase: 'Unauthorized'...

I'm trying to find out if there's something wrong with my code, or if the user account is lacking permissions.

Here is the code below:

string accessToken = GetADToken();
string graphRequest = "https://graph.microsoft.com/v1.0/me/sendMail";

HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization =
    new AuthenticationHeaderValue("Bearer", accessToken);
client.DefaultRequestHeaders.Accept
    .Add(new MediaTypeWithQualityHeaderValue("application/json"));

var email = new {
    message = new {
    subject = "test subject",
    body = new {
    contentType = "Text",
    content = "The cafeteria is open"
    },
    toRecepients = new List<object> {
    new {
    emailAddress = new {
    address = "[email protected]"
    }
    }
    },
    ccRecipients = new List<object> {
    new {
    emailAddress = new {
    address = "[email protected]"
    }
    }
    }
    },
    saveToSentItems = false
};

string requestContent = JsonConvert.SerializeObject(email);
var buffer = Encoding.UTF8.GetBytes(requestContent);
var byteContent = new ByteArrayContent(buffer);
byteContent.Headers.ContentType = new System.Net
    .Http.Headers.MediaTypeHeaderValue("application/json");

var response = client.PostAsync(graphRequest, byteContent).Result;

return response;

I would appreciate some help getting my code to send emails through the graph api

1
Which scopes have you requested? Also, please include the value of accessToken. This will shed light on which permission scopes are actually getting applied. - Marc LaFleur

1 Answers

0
votes

If you are using the MVC, you can check the scope in the following code(Web.Config file)

  <add key="ida:GraphScopes" value="Mail.Send"/> 

If you are using the NETCore, you can check the scope in the following code(appsettings.json)

 "GraphScopes": "Mail.Send"

We suggest you start the mail send sample:https://github.com/microsoftgraph/aspnet-connect-rest-sample