我们正在创建一个应用程序,我们可以为用户提供电子邮件服务,并且用户也可以安排电子邮件发送。我们正在使用 Java 上的 microsoft graph api 进行概念验证。为此,我们在 Microsoft Azure 上创建了一个应用程序,在应用程序上设置权限并添加用户。我正在使用 msalj 和 microsoft graph api 为此编写 JAVA POC。这就是我正在做的事情。
IAuthenticationProvider iAuthProvider = new TokenCredentialAuthProvider(clientSecretCredential());
GraphServiceClient<Request> graphClient = GraphServiceClient
.<Request>builder()
.authenticationProvider(iAuthProvider)
.buildClient();
//Creating msg body for Email
Message message = new Message();
graphClient.users(senderUserEmail).sendMail(UserSendMailParameterSet
.newBuilder()
.withMessage(message)
.withSaveToSentItems(saveToSentItems)
.build()).buildRequest()
.post();
我使用 clientCredentialAuth 来获取令牌,我确实拥有所有值 ClientID、ClientSecret、TenantId。方法 clientSecretCredential() 定义如下。
private ClientSecretCredential clientSecretCredential() {
return new ClientSecretCredentialBuilder()
.clientId(clientId)
.tenantId(tenantId)
.clientSecret(clientSecret)
.build();
}
但是当我运行代码时出现错误
{
"error": {
"code": "OrganizationFromTenantGuidNotFound",
"message": "The tenant for tenant guid {tenantId} does not exist.",
"innerError": {
"errorUrl": "https://aka.ms/autherrors#error-InvalidTenant",
"date": "2024-02-04T11:18:24"
}
}
}
不确定我在这里做错了什么。我探索了很多解决方案,但没有明白这里出了什么问题。
更新:@Rukmini 所建议的就是我们正在做的事情,但是是在 Java 方面。看来它不起作用,因为我们没有office365的许可证。我正在努力再次尝试。
要代表用户发送邮件,请检查以下内容:
创建 Microsoft Entra ID 应用程序并授予 API 权限:
我通过邮递员通过客户端凭证流程生成了访问令牌:
https://login.microsoftonline.com/TenantID/oauth2/v2.0/token
client_id:ClientID
client_secret:ClientSecret
grant_type:client_credentials
scope:https://graph.microsoft.com/.default
使用上述访问令牌,我能够成功发送邮件:
POST https://graph.microsoft.com/v1.0/me/sendMail
Content-type: application/json
{
"message": {
"subject": "Meet for lunch?",
"body": {
"contentType": "Text",
"content": "The new cafeteria is open."
},
"toRecipients": [
{
"emailAddress": {
"address": "[email protected]"
}
}
],
"ccRecipients": [
{
"emailAddress": {
"address": "[email protected]"
}
}
]
},
"saveToSentItems": "false"
}
如果用户未分配 Office 365 许可证,通常会出现错误 “OrganizationFromTenantGuidNotFound”。确保向租户订阅 Office 365 许可证。
如果问题仍然存在,请检查以下内容:
TenantID
是否有效。https://graph.microsoft.com/.default