How to read gmail with imaplib after "less secure app" removed. (or alternatives) when hosted on AWS

Viewed 1309

I'm using a simple script that reads my gmail using imaplib, using my username and password and "less secure app" Gmail option. Gmail will disable the "less secure app" option on May 20, so I need to fix the login credentials before that happends.

I've followed this tutorial about using Oauth2, but the problem is that the script is not running locally (running on AWS ubuntu 20.04), so I can't open the web authentication on the machine that has running the script and the login fails.

More precisely, when I run the tutorial code, I get the following:

Please visit this URL to authorize this application: https://accounts.google.com/o/oauth2/...

I can't open that URL on the AWS command line, and logging in at my local machine doesn't work (it redirects to localhost with the credentials).

I believe the following code obtains the google response with the credentials:

            flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)

I think that one option is to get the credentials running the script locally or catching them with a local server and then send them to AWS, but if they expire I'll need to do that again and probably this wont work anyways.

My intuition says thats not the path to take. Any ideas?

1 Answers

If you want to keep using imaplib then The easiest fix for the depiction of less secure apps is to switch to using an apps pasword

This may or may not continue to work there is no way of knowing really.

That tutorial.

The way that tutorial works is that it stores the credetinals from the user in the file token.pickle. If the file does not exist it prompts you to authorize it.

# The file token.pickle contains the user access token.
# Check if it exists
if os.path.exists('token.pickle'):

    # Read the token from the file and store it in the variable creds
    with open('token.pickle', 'rb') as token:
        creds = pickle.load(token)

# If credentials are not available or are invalid, ask the user to log in.
if not creds or not creds.valid:
    if creds and creds.expired and creds.refresh_token:
        creds.refresh(Request())
    else:
        flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)
        creds = flow.run_local_server(port=0)

    # Save the access token in token.pickle file for the next run
    with open('token.pickle', 'wb') as token:
        pickle.dump(creds, token)

What you can do is run your code once get that token.pickle and make sure when you upload it to AWS that you include the file.

Make sure that you set your app to production or your refresh token is only going to be good for seven days and its going to stop working at that point.

My intuition says thats not the path to take. Any ideas?

Unless this is a Google workspace domain email there is no other option really.

Related