Gmail API服务帐户

时间:2016-09-15 12:00:22

标签: c# oauth-2.0 gmail-api service-accounts

我想使用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 = "MYEMAIL@gmail.com";
        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
                }
            );
        }

我做错了什么?有人能帮助我吗?

此致

4 个答案:

答案 0 :(得分:0)

您是否尝试过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页面中有效?

答案 1 :(得分:0)

尝试检查此documentation有关.NET库中的服务帐户的信息。本文档还提供了一个示例代码,您可以按照该代码设置服务帐户。此link还可以让您了解如何使用服务帐户访问GMAIL API。

现在,对于您收到的错误,请检查此链接是否可以帮助您。

答案 2 :(得分:0)

服务帐户无法访问@ gmail.com邮箱。您必须使用https://developers.google.com/identity/protocols/OAuth2中描述的其他受支持的OAuth 2.0授权方案之一。

请参阅 https://stackoverflow.com/a/39534420/3377170了解更多详情。

答案 3 :(得分:0)

您只能使用服务帐户为GSuite帐户发送电子邮件,而不能为gmail帐户发送电子邮件。

如果您有Gmail帐户,则可以使用3-legged OAuth2 authentication 或打开2FA,生成App Password并使用here

如果您使用的是GSuite帐户,则可以使用ServiceAccount,但必须确保该帐户具有{strong> here中所述的 G Suite域范围委托,然后您需要提供如here

所述访问GSuite域