Search code examples
pythonauthenticationgmailgmail-api

Reading Gmail inbox using Gmail API and service account credentials


My goal is to have a script on my server to check the inbox of a specific Gmail account and when new emails come in, respond to them.

There are many examples of code using OAuth2, however, I don't want to use that since I need to work without GUI and I only need to authorise it for one Gmail account owned by me.

Here is python code that creates credentials from service account creds

from google.oauth2 import service_account

SCOPES = ['https://www.googleapis.com/auth/sqlservice.admin']
SERVICE_ACCOUNT_FILE = 'credentials.json'

credentials = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
delegated_credentials = credentials.with_subject('[email protected]')

But I am kinda lost to what I suppose to be doing next. I apologise if this is a very stupid question but for some reason, I can't figure out what to next as all the tutorials and examples use OAuth2 method of authorisation. Can someone help me with this? Thanks in advance!


Solution

  • Service accounts only work with Gsuite gmail accounts. You will need the domain admin to enable domain wide authorization to your service account to allow it to send and check emails on behalf of the owner of the gmail account.

    If this is a normal user gmail account. Then you will not be able to use service accounts. You will need to use Oauth2 save your refresh token then use the refresh token as part of your application to request a new access token when ever it is needed.