As per different threads here on stackoverflow, it seems that I can create a service account for any regular gmail account. But cannot assign permissions from the domain admin panel.
Can anyone confirm if ServiceAccount can be used to download Emails from any regular gmail account?
If I use the following code:
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
User = userEmail,
Scopes = new string[] { Gmail.v1.GmailService.Scope.GmailReadonly }
}.FromCertificate(certificate)
);
then I get the following error:
{"Error:\"unauthorized_client\", Description:\"Unauthorized client or scope in request.\", Uri:\"\""}
And If I remove the User object from the ServiceAccountCredential constructor then the error is gone. But have the following error when I use any google service:
{"Google.Apis.Requests.RequestError\r\nBad Request [400]\r\nErrors [\r\n\tMessage[Bad Request] Location[ - ] Reason[failedPrecondition] Domain[global]\r\n]\r\n"}
I did set the 'Viewer' role for the service account from the developer console and enabled the google APIs. Is this anyway related to domain account or permissions for the domain account?
Full Code is as following:
String serviceAccountEmail = "gmailscraperserviceaccount2@gmailscraper-1221.iam.gserviceaccount.com";
var certificate = new X509Certificate2("key2.p12", "notasecret",
X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);
string userEmail = "abc@gmail.com";
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new string[] { Gmail.v1.GmailService.Scope.GmailReadonly }
}.FromCertificate(certificate)
);
if (credential.RequestAccessTokenAsync(CancellationToken.None).Result)
{
Google.Apis.Auth.OAuth2.Responses.TokenResponse toke = credential.Token;
GmailService gs = new GmailService(
new Google.Apis.Services.BaseClientService.Initializer()
{
ApplicationName = "TestApp",
HttpClientInitializer = credential
}
);
UsersResource.MessagesResource.ListRequest allMessageRequest = gs.Users.Messages.List(userEmail);
Google.Apis.Gmail.v1.Data.ListMessagesResponse response = allMessageRequest.Execute();