Search code examples
c#gmail-apigoogle-workspaceservice-accountsgoogle-api-dotnet-client

Google Workspace Service Account Credential setup for automated sending of emails and calendar automation with the .NET API Library


I have a Google Workspace with a few users in the directory, including a couple of Super Admins and regular users. I have set up a service account, created an API Client with Domain-wide Delegation.

In code, I have the following for setting up the credential:

            GoogleCredential credential = GoogleCredential
                .FromFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "my-project-112233445566.json"))
                .CreateScoped("https://mail.google.com/")
                .CreateWithUser("account@mydomain.com");

Note that the email address in CreateWithUser is a regular user in the directory. I have NOT set up Gmail Delegation for any users. I enabled Email Delegation in the Admin Console, but the section in the users Gmail Settings page has not appeared that would allow me to add a delegate. That shouldn't matter since I have done the Domain-wide Delegation, right?

After creating that credential above and trying to send a mail message, I receive the following error message:

The service gmail has thrown an exception. HttpStatusCode is Forbidden. Delegation denied for account@mydomain.com

In addition to Domain-wide Delegation do I need to explicitly delegate authority to the service account on a per-user basis? According to the documentation I don't.

If I DO need explicit email delegation, why have I not seen the "Grant access to your account" section on the Accounts page of the Gmail Settings?

Service Account Setup

Google Cloud => IAM & Admin => Service Accounts setting page

Service Account Settings Page

Google Workspace => Security => API Controls => Domain-wide Delegation

Domain-wide Delegation

Is there something else that I need to do to make impersonation happen?


Solution

  • I'm posting the answer here for visibility since it was resolved in the chat

    It seems that the issue was not in the impersonation but by changing the userId="me".

    We also created a new project, services account, key, and domain-wide delegation following the steps in the Google Documentation here.