【问题标题】:python - how to authenticate against GmailAPI without user inputpython - 如何在没有用户输入的情况下对 GmailAPI 进行身份验证
【发布时间】:2022-06-10 19:04:32
【问题描述】:

我有一个小的 python 脚本,它收集一些数据并使用 gmail api 在电子邮件中发送。我的目标是把这个脚本放在我的树莓上,创建一个每天调用它的 cronjob,然后忘记它。但是,我完成 google 身份验证的方式使我无法将其自动化。目前我必须使用我的浏览器进行身份验证(用户需要按下允许按钮),然后我可以使用凭据几天,然后它们过期并且再次需要用户输入。我怎样才能让它验证一次,然后开始自动刷新它的凭据?

当前代码:

def get_creds():
creds = None
if os.path.exists(os.path.join(dir,'token.json')):
    creds = Credentials.from_authorized_user_file('token.json', SCOPES)

if not creds or not creds.valid:
    if creds and creds.expired and creds.refresh_token:
        print("refreshing")
        creds.refresh(Request())
    else:
        flow = InstalledAppFlow.from_client_secrets_file(
            os.path.join(dir,'credentials.json'), SCOPES)
        creds = flow.run_local_server(port=0)

    with open(os.path.join(dir,'token.json'), 'w') as token:
        token.write(creds.to_json())

return creds

【问题讨论】:

  • 我最近回答了这样的问题。解决方案是使用您的代码示例已经拥有的刷新令牌,但为了防止令牌过期,您需要发布项目或将其设置为内部。见avoid auth token to expire

标签: python authentication google-api gmail-api credentials


【解决方案1】:

您可以使用service account 代替令牌。它不会过期。

from google.oauth2 import service_account
from googleapiclient.discovery import build

credentials = service_account.Credentials.from_service_account_file(
    CREDENTIALS_JSON_PATH,
    SCOPES
)

service = build('gmail', 'v1', credentials=credentials)

print(service.users().getProfile(userId='me').execute())

如果您创建Google Workspace service account,您需要指定用户电子邮件地址

credentials = credentials.with_subject(USER_EMAIL)

【讨论】:

    猜你喜欢
    • 2018-11-09
    • 1970-01-01
    • 1970-01-01
    • 2020-05-12
    • 2016-12-15
    • 2020-01-12
    • 2014-08-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多