Search code examples
pythonauthenticationgoogle-apigmail-apicredentials

python - how to authenticate against GmailAPI without user input


I have a small python script that collects some data and sends it in an email using the gmail api. My goal is to put this script on my raspberry, create a daily cronjob that calls it and forget about it. However, the way I have done my google authentication prevents me from automating it. Currently I have to authenticate using my browser(user needs to press the allow button), then I can use the credentials for a few days and then they expire and user input is required again. How can I make it authenticate once and then start refreshing its credentials automatically?

Current code:

def get_creds():
    creds = None
    if os.path.exists(os.path.join(dir,'token.json')):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)

    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            print("refreshing")
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                os.path.join(dir,'credentials.json'), SCOPES)
            creds = flow.run_local_server(port=0)

        with open(os.path.join(dir,'token.json'), 'w') as token:
            token.write(creds.to_json())

    return creds

Solution

  • As Daniel mentioned the problem was that my GoogleCLoud app was in test mode. I had to publish it first and then it started refreshing the token successfully without my help.

    avoid auth token to expire