Error 4000 Precondition Check Failed – Google Gmail Api Service Account

I am facing an issue when I tried to implement a connection to the gmail api using a service account and get the Error:

Error 400: Precondition check failed., failedPrecondition

The following is the code that is being executed:

func connectToGmail() error {
err := godotenv.Load()
if err != nil {
    return err
}
gmailService, err := gmail.NewService(context.Background(), option.WithScopes(gmail.GmailReadonlyScope))
if err != nil {
    return err
}

resp, err := gmailService.Users.Messages.List("me").Do()
if err != nil {
    return err
}

fmt.Println(resp)

return nil

}

From my research nothing leads me to belive that anything is wrong with my code and all research and error code leads me to belive my set up is wrong.

I have done my setup process for a service account (which I will describe below) twice now without any success which is outlined at this link:

https://developers.google.com/workspace/guides/create-credentials#google-cloud-console

  1. Created a service account

  2. Assigned the the group admin role to the account

  3. Created a key for the account

  4. downloaded the Json produced and renamed it credentials.json and put it into my coding directory

  5. set the environmental variable GOOGLE_APPLICATION_CREDENTIALS to the absolute path of the credential file.

  6. Set up Domain-wide Delegation. Coppied the client ID and went to the APi controls and added the client id along with the following scopes:
    https://www.googleapis.com/auth/gmail.readonly, https://www.googleapis.com/auth/gmail.modify, https://mail.google.com/

  7. Ran the code.

The reason for choosing those scopes it because I only want to read emails in my account automatically, the modify and the mail.google one were added because I thought the read only one was restrictive and were the cause for my error. The purpose of my application is to be able to read emails in my inbox after an event and verify if an email has come in.

Let me know if more information is needed.

Any guidance is much appreciated.

preconstruction failed normal means you are using a service account for Gmail without configuring domain wide deligation

Check the deligation and the user your code is impersonating

Leave a Comment