skip to Main Content

IDE: MS Visual Studio – C#

Code Screenshot:
Code

ServiceAccountCredential cred;
        //UserCredential cred;
        string[] scopes = new string[] { GmailService.Scope.GmailLabels, GmailService.Scope.GmailModify, GmailService.Scope.MailGoogleCom };
        using (var stream = new FileStream(@"C:UsersuserDownloadsiwt-mail-crm-sync-135b79aaca90.json", FileMode.Open, FileAccess.Read))
        {
            cred = ServiceAccountCredential.FromServiceAccountData(stream);
            cred.Scopes = scopes;
        }
        var gmailsvc = new GmailService(new Google.Apis.Services.BaseClientService.Initializer()
        {
            HttpClientInitializer = cred,
            ApplicationName = "Gmail immoMail Listener",
        });
        var test = cred.RequestAccessTokenAsync(CancellationToken.None).Result;
        try
        {
            var usr = gmailsvc.Users.GetProfile("me").Execute();
            var lbl = gmailsvc.Users.Labels.List("[email protected]").Execute();
            var messages = gmailsvc.Users.Messages.List("[email protected]").Execute();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }

Error Screenshot:

Error

error message: The service gmail has thrown an exception. HttpStatusCode is BadRequest. Precondition check failed.

We try to connect google service account via API to a google mailbox to query the mails.
We get a successfull request access token but we are not able to query the mailbox itself.

2

Answers


  1. Precondition failed means that you are trying to use a service account to access a google drive workspace account but have forgotten to delegate a user

    var credential = GoogleCredential.FromFile(PathToServiceAccountKeyFile)
        .CreateWithUser("[email protected]")  // delegate to user on workspace.
        .CreateScoped(new[] {DriveService.ScopeConstants.Drive});
    

    Its not enough to just configure domain wide delegation to the service account though workspace, you must also declare the user you want the service account to impersonate.

    Login or Signup to reply.
  2. Do I have to delegate the permissions via the admins console?
    (To grant the the service account the required permissions for the mailbox in advance?)

    Or should the maintainer of the mailbox accept a kind of consent screen?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search