0

I want to read my gmail inbox using Gmail API. I need to use a service account due my application haven't user interaction. I get a following error on request:

"InnerException = {"Error:\"unauthorized_client\", Description:\"Unauthorized client or scope in request.\", Uri:\"\""} "

This is my code:

        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
                }
            );
        }

What am I doing wrong? Can anybody help me?

Regards

Qazi
  • 5,015
  • 8
  • 42
  • 62
ratillo89
  • 53
  • 2
  • 10

4 Answers4

1

Try to check this documentation about service account in .NET libraries. This documentation also provides you a sample code that you can follow on how to setup service account. This link can also give you idea on how to access GMAIL API using Service Account.

Now, for the error that you receive, check this links if it can help you.

Community
  • 1
  • 1
KENdi
  • 7,576
  • 2
  • 16
  • 31
1

You can only use a service account to send emails for a GSuite account and not a gmail account.

If you have a gmail account you can use 3-legged OAuth2 authentication Or turn on 2FA, generate an App Password and use that as seen here

If you ARE using a GSuite account you can use the ServiceAccount but you will have to make sure it has G Suite Domain-wide Delegation as described here and then you need to give access to the GSuite Domain as described here

ender
  • 311
  • 2
  • 5
0

Have you tried the sample code from Google for this function?

  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;
 }

 // ...

}

Have you tried the API explorer here: https://developers.google.com/gmail/api/v1/reference/users/messages/get#net and entered your request information? Did it work from the API page?

Shannon Holsinger
  • 2,293
  • 1
  • 15
  • 21
  • From Google test works fine. I think that the problem is about authentication. I get this error {"Error:\"unauthorized_client\", Description:\"Unauthorized client or scope in request.\", Uri:\"\""} when I call this method credential.RequestAccessTokenAsync(CancellationToken.None).Result – ratillo89 Sep 15 '16 at 13:00
0

Service accounts cannot access @gmail.com mailboxes. You must use one of the other supported OAuth 2.0 authorization scenarios described at https://developers.google.com/identity/protocols/OAuth2.

See https://stackoverflow.com/a/39534420/3377170 for more details.

Community
  • 1
  • 1
  • I managed to work with an old Gmail account. The tests were done with a new account. Is it possible that if the old accounts allow you to use service accounts? – ratillo89 Sep 19 '16 at 07:48
  • 1
    There was a loophole in the past that allowed service accounts access to @gmail.com accounts, but it has been closed. See http://stackoverflow.com/a/39534420/3377170. – Brandon Jewett-Hall Sep 20 '16 at 15:49