Skip to main content

How to execute Gmail API request using Service Account - C# .NET 6

Where and How to Use Service Account?

A service account is a special kind of account used by an application, rather than a person.

You can use a service account to access data or perform actions by the robot account itself, or to access data on behalf of Google Workspace or Cloud Identity users.

In this post, I will review how to execute Gmail API requests using Service Account

see the full sample code on GitHub



Prerequisites

  1. A Google Cloud Platform project
    With the Admin SDK API enabled service account with domain-wide delegation.
  2. A Google Workspace domain.
    With an active account and granted administrator privileges.
  3. Visual Studio 2013 or later

Step 1: Set up the Google Cloud Platform project

  • Create a Google Cloud project
    A Google Cloud project is required to use Google Workspace APIs and build Google Workspace add-ons or apps. If you don't already have a Google Cloud project, refer to: How to Create a Google Cloud project
  • Enable Google Workspace APIs
    Before using Google APIs, you need to enable them in a Google Cloud project. To Enable Google Workspace APIs refer to How to Enable Google Workspace APIs
  • Create a Service Account with a domain-wide delegation
    To create a service account refer to How to create a service account? In the Domain Wide delegation pane, select Manage Domain Wide Delegation.
  • Download Service Account private key (p12 format)
    Download p12 file containing the private key for your Service Account.

Step 2: Set up the Google Workspace

  • Enable API access in the Google Workspace domain with
    To enable API access in the Google Workspace domain, refer to how to enable API access
  • Delegating domain-wide authority to the service account
    To call APIs on behalf of users in a Google Workspace organization, your service account needs to be granted a domain-wide delegation of authority in the Google Workspace Admin console by a super administrator account.
    To delegate domain-wide authority in the Google Workspace domain, refer to How to Delegate domain-wide authority to the service account.

Step 3: Prepare Visual Studio project

  • Create a new Visual C# ASP.NET Core WebAPI (.NET 6.0) project in Visual Studio.
  • Open the NuGet Package Manager Console, select the package source nuget.org, and run the following commands:
    Install-Package Google.Apis.Auth
    Install-Package Google.Apis.Gmail.v1

Step 4: Add code 

See the full c# code sample of "How to Use Service Account" on my GitHub

Add code to provide the certificate

using System.Security.Cryptography.X509Certificates;
namespace Gapis.SA.Core.Services;
public interface ICertificateProvider : IDisposable {
X509Certificate2 Certificate { get; }
}
public class CertificateProvider : ICertificateProvider, IDisposable {
public X509Certificate2 Certificate { get; }
public CertificateProvider(string fileName) {
this.Certificate = new X509Certificate2(
fileName,
"notasecret",
X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);
}
...


Add code to initiate service account

using Google.Apis.Auth.OAuth2;

using Google.Apis.Gmail.v1;
using Google.Apis.Services;
namespace Gapis.SA.Core.Services;
public class GoogleServiceProvider : IGoogleServiceProvider, IDisposable {
private readonly ICertificateProvider? _certificateProvider;
public string ServiceAccountId { get; }
public GoogleServiceProvider(ICertificateProvider? certificateProvider, string serviceAccountId) {
this._certificateProvider = certificateProvider;
this.ServiceAccountId = serviceAccountId;

Add code to user Gmail Client with the Service Account

using Google.Apis.Gmail.v1;namespace Gapis.SA.Core.Services;
public interface IGmailClientService : IDisposable {
Task<IList<Google.Apis.Gmail.v1.Data.Thread>> ListThreadsAsync(string userId);
}
public class GmailClientService : IGmailClientService, IDisposable {
private readonly IGoogleServiceProvider _provider;
public GmailClientService(IGoogleServiceProvider provider) {
this._provider = provider;
}
public void Dispose() {
if (this._provider != null) {
_provider.Dispose();
...

Initiate middleware service

using Gapis.SA.Core.Services;
var builder = WebApplication.CreateBuilder(args);
// The full path; name of a certificate file
builder.Services.AddSingleton<IGoogleServiceProvider>((provider) => {
var certificte = provider.GetService<ICertificateProvider>();
return new GoogleServiceProvider(certificate, serviceAccountId);
});
builder.Services.AddTransient<IGmailClientService, GmailClientService>();

Bundle all together to execute the request

public GmailController(ILogger<GmailController> logger, IGmailClientService gmailClient) {
_logger = logger;
_gmailClient = gmailClient;
}}



See full c# sample and code at GitHub