我无法在Google协作平台上授权Gmail API应用程序。

4

我正在使用colab笔记本电脑运行来自https://developers.google.com/people/quickstart/python的快速入门代码。

# \[START people_quickstart\]

from __future__ import print_function

import os.path

from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

# If modifying these scopes, delete the file token.json.

SCOPES = \['https://www.googleapis.com/auth/contacts.readonly'\]

def main():
"""Shows basic usage of the People API.
Prints the name of the first 10 connections.
"""
creds = None
\# The file token.json stores the user's access and refresh tokens, and is
\# created automatically when the authorization flow completes for the first
\# time.
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
\# If there are no (valid) credentials available, let the user 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 credentials for the next run
with open('token.json', 'w') as token:
token.write(creds.to_json())

    try:
        service = build('people', 'v1', credentials=creds)
    
        # Call the People API
        print('List 10 connection names')
        results = service.people().connections().list(
            resourceName='people/me',
            pageSize=10,
            personFields='names,emailAddresses').execute()
        connections = results.get('connections', [])
    
        for person in connections:
            names = person.get('names', [])
            if names:
                name = names[0].get('displayName')
                print(name)
    except HttpError as err:
        print(err)

if __name__ == '__main__':
main()

# \[END people_quickstart\]

但是它在这个阶段未通过身份验证:

http://localhost:52591/?state=K8nzFjxOrWJkPEqjeG1AZiGpsT5DSx&code=4/0ARtbsJoAH2rD9UYgHOKJ__UdJcq87d2vuFjEAqcI3aKJpj1rLJ-93TXR0_v-LnBR4Fytsg&scope=https://www.googleapis.com/auth/gmail.readonly

为什么会重定向到 localhost? 在 Google Colab 上有一种简单的方法可以发送电子邮件吗?是否使用 Gmail?

我正在使用 Opera 浏览器上的 Google Colab。

有人能帮助我如何在 Google Colab 发送简单的电子邮件,而不降低 Gmail 的安全级别吗?

T.T


1
这段代码存在明显的语法错误。SCOPES = \['https://www.googleapis.com/auth/contacts.readonly'\]是由于反斜杠引起的错误。if块没有缩进。如果我们甚至无法运行您的代码,那么很难为您提供帮助。 - John Gordon
2个回答

2
今天我遇到了同样的问题,我找到解决方法是在Jupyter Notebook中运行代码,然后保存生成的令牌,并将其上传到colab。
我运行了下面的代码,然后在笔记本所在的文件夹中生成了一个名为“token”的json文件:
import os.path

import google.auth.exceptions
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

SCOPES = ["https://www.googleapis.com/auth/gmail.send"]

creds = None

if os.path.exists('token.json'):
    try:
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
        creds.refresh(Request())
    except google.auth.exceptions.RefreshError as error:
        # if refresh token fails, reset creds to none.
        creds = None
        print(f'An error occurred: {error}')
# If there are no (valid) credentials available, let the user 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)
InstalledAppFlow.from_client_secrets_file('credentials_web.json', SCOPES)
        creds = flow.run_local_server(port=0)
    with open('token.json', 'w') as token:
        token.write(creds.to_json())

当一切结束后,在colab中运行相同的代码,确保您已将token更新到环境中,就这样。虽然不太简单,但是它能够工作。


1

如果你在加载run_local_server时遇到404错误,那么可能存在一些问题。

下面的代码是我标准的People api快速入门示例。我刚刚测试了它,它可以正常工作,我没有遇到404错误。

#   To install the Google client library for Python, run the following command:
#   pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib


from __future__ import print_function

import os.path

import google.auth.exceptions
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/contacts']

def main():

    """Shows basic usage of the People API.
    Prints a list of user contacts.
    """
    creds = None
    # The file token.json stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.json'):
        try:
            creds = Credentials.from_authorized_user_file('token.json', SCOPES)
            creds.refresh(Request())
        except google.auth.exceptions.RefreshError as error:
            # if refresh token fails, reset creds to none.
            creds = None
            print(f'An error occurred: {error}')
    # If there are no (valid) credentials available, let the user 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(
                'C:\YouTube\dev\credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.json', 'w') as token:
            token.write(creds.to_json())

    try:
        service = build('people', 'v1', credentials=creds)

        # Call the People API
        print('List 10 connection names')
        results = service.people().connections().list(
            resourceName='people/me',
            pageSize=10,
            personFields='names,emailAddresses').execute()
        connections = results.get('connections', [])

        for person in connections:
            names = person.get('names', [])
            if names:
                name = names[0].get('displayName')
                print(name)
    except HttpError as err:
        print(err)


if __name__ == '__main__':
    main()

你在Google Colab环境中测试过了吗?我复制了你的代码并使用我的凭据执行,但仍然无法在Colab上运行。 也许我在错误的方式下使用了OAuth 2.0客户端ID API... 我将尝试使用不同的SMTP邮件。 - Igor Rocha Amorim

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接