3
votes

I'm working on a Python based project that would gain access to various Google APIs such as Google Contacts API, Pub/Sub API, Gmail API etc.

Getting the relevant tokens and credentials with OAuth 2.0 for those APIs are highly manual at the moment via Google API console. I'd like automate this for multiple users who're willing to let me manage their gmail mailbox through APIs mentioned above (not just Gmail API).

How can I get the credentials for all these APIs during signup process so that I can save the credentials json file in db and then manage the mailboxes? "Sign-up with Google" feature produce just a basic credentials and I couldn't figure out how to route users to relevant page in which I ask for him/her permission to gain access to mailbox with the APIs (Google Contacts, Gmail and pub/sub APIs). Then I'm planning to use this credentials (object) in my Python script programmatically..

Here is the script that I create the credentials by get_credentials(). As you can see, I need to manually get client-secret-file at first on API Console, and then generate credentials wrt scopes with the following script (this is where I need to automate and get several other credentials during signup process)

SCOPES = 'https://www.googleapis.com/auth/gmail.modify'
CLIENT_SECRET_FILE = "client_secret_pubsub.json"
APPLICATION_NAME = "pub-sub-project-te"

def get_credentials():
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
    os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,
                               'gmail-python-quickstart.json')

store = oauth2client.file.Storage(credential_path)

credentials = store.get()
if not credentials or credentials.invalid:
    flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
    flow.user_agent = APPLICATION_NAME
    print('Storing credentials to ' + credential_path)
return credentials


def pull_emails_from_mailbox(credentials_obj):

credentials = get_credentials()

http = credentials.authorize(Http())

GMAIL=discovery.build('gmail', 'v1', http=http)

user_id =  'me'
label_id_one = 'INBOX'
label_id_two = 'UNREAD'

# Getting all the unread messages from Inbox
# labelIds can be changed accordingly
messages = GMAIL.users().messages().list(userId=user_id, maxResults=1000).execute()
#unread_msgs = GMAIL.users().messages().list(userId='me',labelIds=[label_id_one,label_id_two]).execute()

# We get a dictonary. Now reading values for the key 'messages'

mssg_list = messages['messages']

print ("Total messages in inbox: ", str(len(mssg_list)))

final_list = []

new_messages=[]
for mssg in mssg_list:
    m_id = mssg['id'] # get id of individual message
    new_messages.append(GMAIL.users().messages().get(userId=user_id, id=m_id).execute()) # fetch the message using API

return new_messages


def prepare_raw_db (raw_messages):

messageId=[]
historyId=[]
raw=[]

print ("Total number of emails to be parsed:", len(raw_messages))

for msg in raw_messages:
    messageId.append(msg["id"])
    historyId.append(msg['historyId'])
    raw.append(msg)

        #'addLabelIds': ['UNREAD']
    GMAIL.users().messages().modify(userId="me", id=msg["id"],body={ 'removeLabelIds': ['UNREAD'] }).execute() 

msg_dict={"messageId":messageId, "historyId":historyId, "raw":raw}

df=pd.DataFrame(msg_dict)

df.raw=df.raw.astype(str)

return df

thanks

2
What exactly do you want to do with PubSub API here?VictorGGl

2 Answers

1
votes

You've to make web server to do the same. The flow will be following -

  1. User goes to your web app.
  2. User clicks on Sign in with Google.
  3. User will be redirected to Goole OAuth2 url with required scopes (in your case, it is Google Contacts API, Pub/Sub API, Gmail API etc.)
  4. User will give access to your application created on Google Developer Console.
  5. It will return with token/code for your application with required access as per OAuth2 request.
  6. You can store the same in some database and can use it as per OAuth2.

Above process is given step-by-step here.

0
votes

Make your scopes a list and then add them like that, for example

SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly', 'https://www.googleapis.com/auth/spreadsheets']

This worked for me so i hope it helps