OP的决议:
使用 login.microsoftonline.com/consumers 而不是
login.microsoftonline.com/ 用于权限属性,所以现在
我可以阅读消息或发送电子邮件。
然后它仍然可以使用下面的代码发送电子邮件
var graphClient = new GraphServiceClient(authProvider);
await graphClient.Me.SendMail(message).Request().PostAsync();
=================================================== ========
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="js/msal.js"></script>
<script src="js/jquery-3.5.1.min.js" type="text/javascript" charset="utf-8"></script>
<!-- <script type="text/javascript" src="https://js.monitor.azure.com/scripts/b/ai.2.min.js"></script> -->
</head>
<body>
<div style="margin-top: 15px; background-color: #DDDDDD;">
<button type="button" id="signIn" onclick="signIn()">Sign In</button>
<button type="button" id="getAccessToken" onclick="getAzureAccessToken()">getAccessToken</button>
<h5 class="card-title" id="welcomeMessage">Please sign-in to see your profile and read your mails</h5>
<div>
<div>
accesstoken :
<div id="accesstoken">
</div>
</div>
</div>
</div>
<script type="text/javascript">
const msalConfig = {
//clientsecret:"client_secret"
auth: {
clientId: "your_azuread_app_client_id",
authority: "https://login.microsoftonline.com/your_tenant_name.onmicrosoft.com",
redirectUri: "your_home_page_url_like_http://localhost:8848/new_file.html",
},
cache: {
cacheLocation: "sessionStorage", // This configures where your cache will be stored
storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
}
};
//scope used for sign in
const loginRequest = {
scopes: ["openid", "profile", "User.Read"]
};
//scope used for generating access token
const AzureMgmtScops ={
scopes:["User.Read", ...]
}
let accessToken = '';
const myMSALObj = new Msal.UserAgentApplication(msalConfig);
function signIn() {
myMSALObj.loginPopup(loginRequest)
.then(loginResponse => {
console.log("id_token acquired at: " + new Date().toString());
console.log(loginResponse);
if (myMSALObj.getAccount()) {
showWelcomeMessage(myMSALObj.getAccount());
getAzureAccessToken();
}
}).catch(error => {
console.log(error);
});
}
function showWelcomeMessage(account) {
document.getElementById("welcomeMessage").innerHTML = `Welcome ${account.name}`;
}
function getAzureAccessToken(){
myMSALObj.acquireTokenSilent(AzureMgmtScops).then(tokenResponse => {
showAccesstoken(tokenResponse.accessToken)
console.info("======the accesstoken is ======:"+tokenResponse.accessToken);
}).catch(function (error) {
console.log(error);
})
}
function showAccesstoken(data){
document.getElementById("accesstoken").innerHTML = JSON.stringify(data, null, 2);
}
</script>
</body>
</html>
===========================更新===================== ===========
你用过var graphClient = new GraphServiceClient(authProvider);
首字母缩写graphClient
,并且访问令牌是从前端传递的,所以我认为您遵循了这个样本 https://learn.microsoft.com/en-us/graph/sdks/choose-authentication-providers?tabs=CS#on-behalf-of-provider在这里使用代表流。但您提供的代码片段在这里有所不同。所以我认为这就是发送电子邮件失败问题的原因。
这里你有 2 个选项,第一个选项是阅读代表流 https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-on-behalf-of-flow如果您同意使用这里的流程,您只需按照我上面提供的教程完成代码并尝试即可。
但我认为你可能更喜欢第二种方式。在我看来,你需要后端做的是执行一些逻辑来完成电子邮件,然后调用 api 来发送电子邮件。如果是这样,为什么不直接发送 http 请求,因为您已经获得了访问令牌。
您可以检查访问令牌是否适用于发送电子邮件,只需尝试在邮递员等工具中使用令牌调用 api 即可。如果您收到 202 响应,则表示令牌正常。
然后你需要像这样修改你的发送电子邮件方法,它对我有用:
public async Task sendAsync() {
var mesg = new Message
{
Subject = "Meet for lunch?",
Body = new ItemBody
{
ContentType = BodyType.Text,
Content = "The new cafeteria is open."
},
ToRecipients = new List<Recipient>
{
new Recipient
{
EmailAddress = new EmailAddress
{
Address = "[email protected] /cdn-cgi/l/email-protection"
}
}
},
Attachments = new MessageAttachmentsCollectionPage()
};
var temp = new MailContentModel
{
message = mesg
};
var jsonStr = JsonSerializer.Serialize(temp);
string token = "your_token";
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
HttpResponseMessage response = await httpClient.PostAsync("https://graph.microsoft.com/v1.0/me/sendMail", new StringContent(jsonStr, Encoding.UTF8, "application/json"));
}
using Microsoft.Graph;
public class MailContentModel
{
public Message message { get; set; }
}