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