我正在开发一个基于Python的项目,可以访问各种Google API,如Google Contacts API,Pub/Sub API,Gmail API等。
通过OAuth 2.0获取这些API的相关令牌和凭据目前是通过Google API控制台高度手动的。我想为那些愿意让我通过上面提到的API(不仅仅是gmail API)管理他们的Gmail邮箱的多个用户实现自动化。
如何在注册过程中获得所有这些API的凭据,以便将凭据json文件保存到数据库中,然后管理邮箱?“注册谷歌”功能只产生一个基本的凭证,我不知道如何将用户路由到相关的页面,在那里我请求他/她允许使用API(谷歌联系人,Gmail和发布/订阅API)访问邮箱。然后,我计划以编程方式在Python脚本中使用此凭据(对象)。
下面是我通过get_credentials()创建凭据的脚本。正如您所看到的,我需要首先在API控制台上手动获取client-secret-file,然后使用以下脚本生成凭据wrt作用域(这是我需要在注册过程中自动获取其他几个凭据的地方)
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谢谢
发布于 2018-04-18 01:31:58
你必须让web服务器来做同样的事情。流程将会如下-
上面的过程是一步一步的here。
发布于 2020-10-02 04:02:32
让你的作用域成为一个列表,然后像这样添加它们,例如
SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly', 'https://www.googleapis.com/auth/spreadsheets']这对我很有效,所以我希望这对我有帮助。
https://stackoverflow.com/questions/49775620
复制相似问题