【问题标题】:Create labels with GMail API in C#在 C# 中使用 GMail API 创建标签
【发布时间】:2023-03-19 04:42:01
【问题描述】:

花了几个小时寻找有关如何使用服务帐户访问 Gmail API 的答案,发现我不能,除非我使用的是提供域范围授权的 GSuite 帐户,我来这里问您是否有一种方法可以使用上述 API 实际创建标签 私人帐户。我正在使用 Visual Studio 2019 和 C#。在“developers.google.com”中,有一个名为“Try this API”的工具,我可以使用我的 OAuth 2.0 创建一个标签,并且找到 here 的 .NET 快速入门也适用于列出我的标签。但为什么它不能让我创建标签?我已经启用了所有可能的作用域。

这是我得到的错误:

"Google.GoogleApiException: 'Google.Apis.Requests.RequestError 请求的身份验证范围不足。 [403] 错误 [ Message[Insufficient Permission] Location[-] Reason[insufficientPermissions] Domain[global]" enter image description here

【问题讨论】:

标签: c# .net label visual-studio-2019 gmail-api


【解决方案1】:

Lables.create 方法需要权限才能在用户帐户上创建标签。用户必须同意该权限。

错误信息

Google.Apis.Requests.RequestError 请求的身份验证范围不足。

告诉您用户没有同意适当的范围。用户必须同意以下范围之一

如果您遵循快速入门,那么您可能只包含了GmailService.Scope.GmailReadonly。您将需要更改范围并再次请求用户的授权。请注意,您所遵循的教程不是针对服务帐户身份验证,而是针对 Oauth2 身份验证。

服务帐号

string ApplicationName = "Gmail API .NET Quickstart";
            const string serviceAccount = "xxxxx-smtp@xxxxx-api.iam.gserviceaccount.com";

            var certificate = new X509Certificate2(@"c:\xxxxx-api-ed4859a67674.p12", "notasecret", X509KeyStorageFlags.Exportable);

            var gsuiteUser = "xxxxx@xxxx.com";

            var serviceAccountCredentialInitializer = new ServiceAccountCredential.Initializer(serviceAccount)
            {
                User = gsuiteUser,
                Scopes = new[] { GmailService.Scope.GmailSend, GmailService.Scope.GmailLabels }

            }.FromCertificate(certificate);

            var credential = new ServiceAccountCredential(serviceAccountCredentialInitializer);
            if (!credential.RequestAccessTokenAsync(CancellationToken.None).Result)
                throw new InvalidOperationException("Access token failed.");

            var service = new GmailService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = ApplicationName,
            });

【讨论】:

  • 你绝对是最棒的,我看到你回答了很多关于 Google API 的问题!谢谢!虽然,在我没有意识到我应该更改这些代码行中的范围之前,我已经将其视为一个答案!我总是在 Google.console 的项目中更改它们!
  • 在 google 控制台中更改它们实际上只会告诉 google 你在做什么,它的代码定义了你实际要求的权限
猜你喜欢
  • 2015-06-07
  • 2021-05-25
  • 2013-07-30
  • 2016-05-31
  • 1970-01-01
  • 2021-09-24
  • 2018-06-17
  • 1970-01-01
  • 2014-09-03
相关资源
最近更新 更多