我想使用Gmail API阅读我的Gmail收件箱。由于我的应用程序没有用户交互,我需要使用服务帐户。我根据要求收到以下错误:
"InnerException = {"Error:\"unauthorized_client\", Description:\"Unauthorized client or scope in request.\", Uri:\"\""} "
这是我的代码:
string applicationName = "Gmail API .NET";
string[] scopes = { GmailService.Scope.GmailReadonly };
string certPath = "./XXXXXXXXXX.p12";
string userEmail = "[email protected]";
string serviceAccountEmail = "MYSERVICEACCOUNT...am.gserviceaccount.com";
//Carga el certificado obtenido de
var certificate = new X509Certificate2(certPath, "notasecret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
User = userEmail,
Scopes = scopes
}.FromCertificate(certificate)
);
if (credential.RequestAccessTokenAsync(CancellationToken.None).Result) <--- Here I get the error
{
GmailService gs = new GmailService(
new BaseClientService.Initializer()
{
ApplicationName = applicationName,
HttpClientInitializer = credential
}
);
}
我究竟做错了什么?有谁能够帮我?
问候
您是否尝试过Google的示例代码来实现此功能?
using Google.Apis.Gmail.v1;
using Google.Apis.Gmail.v1.Data;
// ...
public class MyClass {
// ...
/// <summary>
/// Retrieve a Message by ID.
/// </summary>
/// <param name="service">Gmail API service instance.</param>
/// <param name="userId">User's email address. The special value "me"
/// can be used to indicate the authenticated user.</param>
/// <param name="messageId">ID of Message to retrieve.</param>
public static Message GetMessage(GmailService service, String userId, String messageId)
{
try
{
return service.Users.Messages.Get(userId, messageId).Execute();
}
catch (Exception e)
{
Console.WriteLine("An error occurred: " + e.Message);
}
return null;
}
// ...
}
您是否在此处尝试过API资源管理器:https://developers.google.com/gmail/api/v1/reference/users/messages/get#net并输入了您的请求信息?它是否在API页面中有效?
尝试检查这个documentation有关.NET库中的服务帐户。本文档还提供了一个示例代码,您可以按照该代码设置服务帐户。这个link还可以为您提供有关如何使用服务帐户访问GMAIL API的建议。
现在,对于您收到的错误,请检查此链接是否可以帮助您。
服务帐户无法访问@ gmail.com邮箱。您必须使用https://developers.google.com/identity/protocols/OAuth2中描述的其他受支持的OAuth 2.0授权方案之一。
有关详细信息,请参阅https://stackoverflow.com/a/39534420/3377170。
您只能使用服务帐户为GSuite帐户而不是Gmail帐户发送电子邮件。
如果你有一个gmail帐户,你可以使用3-legged OAuth2 authentication或打开2FA,生成一个App Password并使用它看到here
如果您使用的是GSuite帐户,则可以使用ServiceAccount,但您必须确保它具有here描述的G Suite域范围的委派,然后您需要访问GSuite域,如here所述