Can we access GMAIL API using Service Account?

gmail api service account
gmail api authentication
gmail api scopes
authorized gmail api service instance
gmail api-python
gmail access token
gmail api service account python
how to use gmail api

I have a desktop application to read mail using GMAIL API over REST Interface. I want to use service account so that we can download the mails using domain setting and user interaction is null. I am successfully able to create Gmail Service instance but when I try to access any Gmail API method like fetching mail list or any other I get an exception saying

Google.Apis.Auth.OAuth2.Responses.TokenResponseException: Error:"access_denied", Description:"Requested client not authorized."

I am done with all the setting at developer console and added scopes to my gapps domain.

Does Gmail API support service account? Using the same setting and service account I am able to get list of all files in Google drive using Drive service and API.

I use the following C# code for accessing Gmail from Service Account

String serviceAccountEmail =
    "999999999-9nqenknknknpmdvif7onn2kvusnqct2c@developer.gserviceaccount.com";

var certificate = new X509Certificate2(
    AppDomain.CurrentDomain.BaseDirectory +
        "certs//fe433c710f4980a8cc3dda83e54cf7c3bb242a46-privatekey.p12",
    "notasecret",
    X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);

string userEmail = "user@domainhere.com.au";

ServiceAccountCredential credential = new ServiceAccountCredential(
    new ServiceAccountCredential.Initializer(serviceAccountEmail)
    {
        User = userEmail,
        Scopes = new[] { "https://mail.google.com/" }
    }.FromCertificate(certificate)
);

if (credential.RequestAccessTokenAsync(CancellationToken.None).Result)
{   
    GmailService gs = new GmailService(
        new Google.Apis.Services.BaseClientService.Initializer()
        {
            ApplicationName = "iLink",
            HttpClientInitializer = credential
        }
    );

    UsersResource.MessagesResource.GetRequest gr =
        gs.Users.Messages.Get(userEmail, msgId);
    gr.Format = UsersResource.MessagesResource.GetRequest.FormatEnum.Raw;
    Message m = gr.Execute();

    if (gr.Format == UsersResource.MessagesResource.GetRequest.FormatEnum.Raw)
    {
        byte[] decodedByte = FromBase64ForUrlString(m.Raw);
        string base64Encoded = Convert.ToString(decodedByte);
        MailMessage msg = new MailMessage();
        msg.LoadMessage(decodedByte);
    }
}

Implementing Server-Side Authorization | Gmail API, I am trying to use the gmail apis for sending mail from a .net windows application. Can we use a service account instead of the user credential to call the Unfortunately i don't have access to a Gsuite account so cant help you  If you use Google Apps for your domain email and if you have admin access, you can easily use the gmail api. Because you have admin access, you can create a "service account" in the Google Developer Console. This makes authentication easy.

If you want to "read mail" you'll need the newer Gmail API (not the older admin settings API that 'lost in binary' pointed out). Yes you can do this with oauth2 and the newer Gmail API, you need to whitelist the developer in Cpanel and create a key you can sign your requests with--it take a little bit to setup: https://developers.google.com/accounts/docs/OAuth2ServiceAccount#formingclaimset

Authorizing Your App with Gmail | Gmail API, Google+ Sign-in to provide a "sign-in with Google" authentication method for your app. Modifying your signature with the Gmail API This video walks you through an example of modifying user signatures. Other settings the API can modify include email forwarding, vacation responder, external access via IMAP/POP, and filters.

Yes you can... check the delegation settings...

https://developers.google.com/admin-sdk/directory/v1/guides/delegation#delegate_domain-wide_authority_to_your_service_account

Edit: Use the link Eric DeFriez shared.

using Gmail API using Service Account · Issue #1043 · googleapis , You could quite easily continue and modify Gmail signatures. Many of the online tutorials on the subject focus on using OAuth user credentials  No. The Gmail API is for Gmail users and service accounts are just for doing auth to a real Gmail account, they don't have their own Gmail account, etc.

For C# Gmail API v1, you can use the following code to get the gmail service. Use gmail service to read emails. Once you create the service account in Google Console site, download the key file in json format. Assuming the file name is "service.json".

    public static GoogleCredential GetCredenetial(string serviceAccountCredentialJsonFilePath)
    {
        GoogleCredential credential;

        using (var stream = new FileStream(serviceAccountCredentialJsonFilePath, FileMode.Open, FileAccess.Read))
        {
            credential = GoogleCredential.FromStream(stream)
                .CreateScoped(new[] {GmailService.Scope.GmailReadonly})
                .CreateWithUser(**impersonateEmail@email.com**);
        }

        return credential;
    }

    public static GmailService GetGmailService(GoogleCredential credential)
    {
        return new GmailService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,                
            ApplicationName = "Automation App",                
        });
    }

   // how to use
   public static void main()
   {
        var credential = GetCredenetial("service.json");
        var gmailService = GetGmailService(credential);

        // you can use gmail service to retrieve emails. 
        var mMailListRequest = gmailService.Users.Messages.List("me");
        mMailListRequest.LabelIds = "INBOX";

        var mailListResponse = mMailListRequest.Execute();            
   }

Google Gmail API Pricing, Sending emails programmatically with Gmail API and Python Following this tutorial, you can create a script that will send an email using Gmail API. run the script, it will open a tab in your browser and request access to your Gmail/GSuite account. Create a service account with domain-wide authority. Service accounts will only work with Gsuite email accounts. The admin of the Gsuite (domain) account will have to grant the service account access to the users email account. Unfortunately i don't have access to a Gsuite account so cant help you set it up. This might help Perform G Suite Domain-Wide Delegation of Authority

Here is a little bit of python 3.7:

from google.oauth2 import service_account
from googleapiclient.discovery import build

def setup_credentials():
    key_path = 'gmailsignatureproject-zzz.json'
    API_scopes =['https://www.googleapis.com/auth/gmail.settings.basic',
                 'https://www.googleapis.com/auth/gmail.settings.sharing']
    credentials = service_account.Credentials.from_service_account_file(key_path,scopes=API_scopes)
    return credentials


def test_setup_credentials():
    credentials = setup_credentials()
    assert credentials


def test_fetch_user_info():
    credentials = setup_credentials()
    credentials_delegated = credentials.with_subject("tim@vci.com.au")
    gmail_service = build("gmail","v1",credentials=credentials_delegated)
    addresses = gmail_service.users().settings().sendAs().list(userId='me').execute()
    assert gmail_service

Access GSuite APIs on your domain using a service account, Introduction A service account provides a streamlined way to connect multiple Gmail, and to get back from the specific API pages click the API & Services Link, and to your computer you should store this securely as it provides access to your Log into Gmail select the Admin panel you generally will need to scroll down  If you want to use a service account to access mailboxes of users across a domain that you administer, see the answer that the other commenter referred to: Can we access GMAIL API using Service Account?

Sending emails programmatically with Gmail API and Python, Developers who need to create service accounts for their apps should use this article. Tip: If you can't find the API, specify the API name in the search box. Admin SDK, Google Calendar API, Contacts API, Gmail API, Groups Migration API. All requests to the Gmail API must be authorized by an authenticated user. Gmail uses the OAuth 2.0 protocolfor authenticating a Google account and authorizing access to user data. You can also use

How to a create Gmail service account – Ebsta Knowledge Base, App developers and G Suite administrators can create service accounts with For example, you can delegate access to an app that uses the Calendar API to add an account with super administrator privileges (does not end in @gmail.​com). Once OAuth 2.0 credentials have been retrieved as shown in the previous section, they can be used to authorize a Gmail service object and send requests to the API. Instantiate a service object.

Create a service account - G Suite Admin Help, All service accounts have Cloud IAM policies that grant access to the service account. You can use a service account from the virtual machines on the external  For these types of server-to-server interactions you need a service account, which is an account that belongs to your application instead of to an individual end-user. Your application calls Google

Comments
  • even I am following the same process but getting the exception, could you please tell me what all scope list i need to add at my google apps domain level?
  • I am using a marketplace app. I have googleapis.com/auth/userinfo.email googleapis.com/auth/userinfo.profile mail.google.com
  • Also, if you are using the constant GmailService.Scope.MailGoogleCom (instead of writing the url), then you must append the "/" to make it work!
  • The userEmail, is that a regular gmail account or a domain account? Becasue for this code I am getting this unauthorized_client\", Description:\"Unauthorized client or scope in request error. Even tho I have the APIs enabled from the developer console.
  • Hi @Rahat, this is a bit late but yes it is a regular user email account from within the domain.
  • Interesting! Am I understanding correctly that using this method one should be able to use a service account to access the new Gmail API methods across an entire Google Apps domain's users? Does the response contain information on specific user that the returned results are for? Accessing Gmail API using traditional Oauth, a user context is implied so the response doesn't need to contain contextual user info such as user Id, etc.
  • More an oauth2 question at this point, so hopefully one of the experts on auth can comment however my understanding is as part of each request you'll generate the userId (email address) you want to access with that request. You'll use your private key, etc to form this. So you will only be authorized once for the entire domain (in Cpanel) but you can request access for any user in the domain and you'll obviously know who it is for beforehand.
  • Does it work for regular gmail account? Or it has to be a domain account?
  • I am still getting the above exception. Following are my scope list:: User Provisioning (Read only) apps-apis.google.com/a/feeds/user/#readonly docs.google.com/feeds Email (Read/Write/Send) mail.google.com googleapis.com/auth/admin.directory.group googleapis.com/auth/admin.directory.user googleapis.com/auth/drive googleapis.com/auth/gmail.compose googleapis.com/auth/gmail.modify googleapis.com/auth/gmail.readonly Do I need to add more scope list?
  • i am using a trial account and not getting this option, just says 'Manage OAuth Client access'. is it because of the trial or is there some configuration required
  • I get the error Google.Apis.Auth.OAuth2.Responses.TokenResponseException: 'Error:"unauthorized_client", Description:"Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested.", Uri:""' How can I add permissions to the service account?
  • You need to assign scopes. See how to Delegate domain-wide authority to your service account. For step 6, you can assign the scope https://www.googleapis.com/auth/gmail.readonly if you want to grant read only access. You can get a list of scopes from here
  • Also the scopes have to match. Watever scopes I add at admin.google.com/ublux.com/… have to match in the code! Thanks so much for the help Circuit Breaker I finally made this work!