I am desperate to resolve this task, so I hope to get the answer here.
I set up the service account in my GSuit and my goal is to get all the emails and calendars of all the users in my company.
Steps, that I have done:
Created a new API app
Enable access to APIs
Enabled API apps Google Calendar API, Gmail API, Admin SDK API, Google People API, Contacts API
OAuth consent screen. Internal. Add scopes:
/auth/admin.directory.user.readonly
mail.google.com/
/auth/profile.emails.read
/auth/gmail.readonly
/auth/user.emails.read
/auth/userinfo.email
Created Service Account. Granted permissions “Service Account Token Creator”, Viewer.
Security > API Controls > Domain-wide Delegation to my Service Account client ID:
mail.google.com,
/auth/contacts,
/auth/gmail.readonly,
/auth/userinfo.email,
auth/userinfo.profile,
auth/admin.directory.user,
auth/admin.directory.user.readonly
I can get Users but not emails.
It throws the error:
The service gmail has thrown an exception. HttpStatusCode is BadRequest.
Google.Apis.Requests.RequestError Precondition check failed.
[400] Errors [ Message[Precondition check failed.] Location[ – ] Reason[failedPrecondition] Domain[global] ]
Google.GoogleApiException: The service gmail has thrown an exception.
HttpStatusCode is BadRequest. The precondition check failed.
And my code is simple as:
string[] scopes = { DirectoryService.Scope.AdminDirectoryUser, GmailService.Scope.GmailReadonly, CalendarService.Scope.CalendarReadonly };
GoogleCredential credential;
using (var stream = new FileStream(keyFilePath, FileMode.Open, FileAccess.Read))
{
credential = GoogleCredential.FromStream(stream)
.CreateWithUser("my service account email")
.CreateScoped(scopes);
}
var service = new DirectoryService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Your Application Name",
});
// Call the API to get users
var users = service.Users.List();
users.Customer = "My company's CustomerID";
var response = users.Execute();
var userList = response.UsersValue;
var serviceGmail = new GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Your Application Name",
});
foreach (var user in userList)
{
var request = serviceGmail.Users.Messages.List(user.Id);
ListMessagesResponse emails = request.Execute();
var messages = emails.Messages;
}
I followed the oficial documentation and checked out tons of the stach overflow articles.
Victor Duma is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.