首页 > 解决方案 > 使用 API 密钥和 .NET (C#) 访问 Gmail?

问题描述

尝试使用 NuGet 包 Google.Apis.Gmail.v1 访问我的 Gmail 收件箱。我不想使用 OAuth。我确实想使用 API 密钥。

所以我去获取了一个 API 密钥:https ://developers.google.com/api-client-library/dotnet/guide/aaa_apikeys

然后我去这里了解如何使用 API 密钥进行授权:https ://developers.google.com/api-client-library/dotnet/get_started

然后我得到了这个:

var service = new GmailService(new BaseClientService.Initializer
{
    ApplicationName = "NAME OF MY APP HERE",
    ApiKey = "MY API KEY HERE"
});

var inboxlistRequest = service.Users.Messages.List("mygmail@gmail.com");

inboxlistRequest.LabelIds = "INBOX";
inboxlistRequest.IncludeSpamTrash = true;

var emailListResponse = inboxlistRequest.Execute();

当最后一行执行时,我得到了这个:

Google.GoogleApiException : Google.Apis.Requests.RequestError 请求缺少所需的身份验证凭据。预期的 OAuth 2 访问令牌、登录 cookie 或其他有效的身份验证凭据。请参阅https://developers.google.com/identity/sign-in/web/devconsole-project。

at Google.Apis.Requests.ClientServiceRequest`1.ParseResponse(HttpResponseMessage response)
   at Google.Apis.Requests.ClientServiceRequest`1.Execute()
  ...

为什么它不起作用?对哪些 API 密钥可以访问有一些限制吗?它在哪里说?

标签: c#gmailgmail-api.net-5

解决方案


API 密钥用于识别您的 API。它不会授予您访问任何内容的权限。

您仍然需要邮箱所有者的凭据。


推荐阅读