无法使用 Microsoft Graph SDK 发送电子邮件
Unable to send an email with the Microsoft Graph SDK
我遵循了这些步骤:
- 我在 Azure 中创建了应用程序注册。
- 进入证书和机密并创建了一个新的客户端机密。
- 在 API 权限中,授予对所有邮件的委派权限。* 权限名称。
- 然后我点击了
Grant admin consent for {my org}
。
在我的代码(.net 核心控制台应用程序)中,我写了以下内容:
var clientId = "23fff856-***";
var tenantId = "6f541345-***";
var clientSecret = "_Sir**(";
IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
.Create(clientId)
.WithTenantId(tenantId)
.WithClientSecret(clientSecret)
.Build();
var authProvider = new ClientCredentialProvider(confidentialClientApplication);
var graphClient = new GraphServiceClient(authProvider);
var message = new Message
{
Subject = "my subject",
Body = new ItemBody {ContentType = BodyType.Text, Content = "body"},
ToRecipients = new List<Recipient>
{
new Recipient
{
EmailAddress = new EmailAddress{Address = "foo@gmail.com"}
}
}
};
await GraphClient.Me
.SendMail(message, true)
.Request()
.PostAsync();
这会导致错误:
"code":"NoPermissionsInAccessToken",
"message":"The token contains no permissions, or permissions can not be understood."
我已授予所有权限。我错过了什么?
由于您使用的是客户端凭据流,因此您需要在 Azure 门户上使用应用程序权限。请添加 Mail.Send 应用程序权限,它将起作用。
删除 'Me' 并添加用户 ['Userid'],因为 'Me' 谈论的是登录用户,而我们这里没有任何用户。
Userid 是 Azure AD 中的用户对象 ID。您也可以使用 userPrincipalname 进行测试。您可以使用 /users endpoint 获取用户的 userid,并使用 displayname 或 userPrincipalname 进行过滤。
我遵循了这些步骤:
- 我在 Azure 中创建了应用程序注册。
- 进入证书和机密并创建了一个新的客户端机密。
- 在 API 权限中,授予对所有邮件的委派权限。* 权限名称。
- 然后我点击了
Grant admin consent for {my org}
。
在我的代码(.net 核心控制台应用程序)中,我写了以下内容:
var clientId = "23fff856-***";
var tenantId = "6f541345-***";
var clientSecret = "_Sir**(";
IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
.Create(clientId)
.WithTenantId(tenantId)
.WithClientSecret(clientSecret)
.Build();
var authProvider = new ClientCredentialProvider(confidentialClientApplication);
var graphClient = new GraphServiceClient(authProvider);
var message = new Message
{
Subject = "my subject",
Body = new ItemBody {ContentType = BodyType.Text, Content = "body"},
ToRecipients = new List<Recipient>
{
new Recipient
{
EmailAddress = new EmailAddress{Address = "foo@gmail.com"}
}
}
};
await GraphClient.Me
.SendMail(message, true)
.Request()
.PostAsync();
这会导致错误:
"code":"NoPermissionsInAccessToken",
"message":"The token contains no permissions, or permissions can not be understood."
我已授予所有权限。我错过了什么?
由于您使用的是客户端凭据流,因此您需要在 Azure 门户上使用应用程序权限。请添加 Mail.Send 应用程序权限,它将起作用。
删除 'Me' 并添加用户 ['Userid'],因为 'Me' 谈论的是登录用户,而我们这里没有任何用户。
Userid 是 Azure AD 中的用户对象 ID。您也可以使用 userPrincipalname 进行测试。您可以使用 /users endpoint 获取用户的 userid,并使用 displayname 或 userPrincipalname 进行过滤。