How To Use a Service Account To Access Gmail Records of a Domain User

Like most of Google’s services, Gmail comes with bountiful APIs to help us build out software for meeting our growing demands. To learn the full details of the Gmail API, check out the very informative guide to Google’s Gmail API here.

For this tutorial we are not going to focus on getting your service account, which is necessary for server sided operation, our focus will only be on reading domain user messages. This example is for operations where user input will not be required. Because of this you will need a few items before you can begin. I will keep this simple.


Required Reference Libraries

  • Google.Apis
  • Google.Apis.Auth
  • Google.Apis.Auth.Platform
  • Google.Apis.Core
  • Google.Apis.Gmail.v1
  • Google.Apis.PlatformServices
  • Google.Apis.Plus.v1
  • Google.Apis.Vault.v1
  • Google.Apis.Services

Required Using Statements

using System.Data;
using Google.Apis.Gmail.v1;
using System;
using System.Collections.Generic;
using System.Configuration;
using Google.Apis.Util;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;

The Code

Our first code snippet will be creating the gmail service, which we will use to go through our domain user account gmail records.

public static GmailService CreateGmailService(string userId)
    var key = ConfigurationManager.AppSettings["EncryptionKey"].ToString(); //service account key
    var email = ConfigurationManager.AppSettings["Email"].ToString(); //service account email
    key = key.Replace("\n", "n");

    var cred = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(email)
        Scopes = new[] { GmailService.Scope.GmailReadonly, GmailService.Scope.GmailModify },
        User = userId

    var svc = new GmailService(new BaseClientService.Initializer()
        HttpClientInitializer = cred

    return svc;

The second snippet will be reading the actual gmail records. For my example I am only calling with a single user: (fake obviously). You could easily add a foreach loop and pass in a dynamic list of users from a domain user group or database list, etc.

You can also customize the metadata headers which are defined in the standard RFC 2822 documentation.

public static void GetGmailRecs()
   GmailRecsUsers _GmailRecsUsers = new GmailRecsUsers(); = "";
    GmailService _GmailService = CreateGmailService(;
    UsersResource.MessagesResource.ListRequest request2 = _GmailService.Users.Messages.List(;
    request2.MaxResults = 25;
    var messages = request2.Execute().Messages;
    for (int index = 0; index < messages.Count; index++)
        var message = messages[index];
        var getRequest = _GmailService.Users.Messages.Get(, message.Id);
        getRequest.Format = UsersResource.MessagesResource.GetRequest.FormatEnum.Metadata;
        getRequest.MetadataHeaders = new Repeatable<string>(new[] { "Subject", "Date", "From", "To", "In-Reply-To", "historyId" });
        messages[index] = getRequest.Execute();

How to know if you are setup correctly? If you haven’t enabled the APIs, and your service account properly then you will probably see a warning similar to: “Client is unauthorized to retrieve access tokens using this method”.

I hope I kept this simple enough, enjoy and good luck!