1

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('myGmail@gmail.com')

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!

Eugene Levinson
  • 172
  • 2
  • 13
  • 1
    Have you [followed the entire tutorial by Google](https://developers.google.com/gmail/api/quickstart/python), and then the further reading section? – metatoaster Jun 08 '20 at 11:46
  • Ye, I tried the quickstart and replaced the OAuth2 method of getting credentials with the service account, the way it's specified in the docs on Github from further read section. I get a bunch of errors like ```Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested``` – Eugene Levinson Jun 08 '20 at 12:15

1 Answers1

3

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.

Linda Lawton - DaImTo
  • 106,405
  • 32
  • 180
  • 449
  • I recommend testing with a dummy email account. If your code starts spamming google they may shut you down and lock your google account. Not a happy experience i must add. – Linda Lawton - DaImTo Jun 08 '20 at 12:31