【问题标题】:How to interact with the Gmail API - Delegate User - Python 3.7如何与 Gmail API 交互 - 委托用户 - Python 3.7
【发布时间】:2020-01-23 19:13:57
【问题描述】:

我正在尝试编写一个 Python 应用程序,它只是将一个用户作为委托添加到另一个用户邮箱。

我正在关注 API @Google API Documentation - Users.settings.delegates: create

但是,我很难找到以下参数:

用户 - 将被添加到委托邮箱的帐户 邮箱 - 拥有我希望该帐户成为其代表的邮箱的帐户。

我目前尝试制作一个具有委托用户的 API。但是,它似乎并没有按照我的预期进行交互。我希望 Google 会为浏览器创建一个响应式 API 来支持这一点。但是,我正在为代码苦苦挣扎:

from googleapiclient import discovery
from oauth2client.service_account import ServiceAccountCredentials


def main(user_to_be_added, delegated_mailbox):
    service_account_credentials = ServiceAccountCredentials.from_json_keyfile_name('credentials/service_account.json')
    service_account_credentials = service_account_credentials.create_scoped('https://mail.google.com/ https://www.googleapis.com/auth/gmail.insert https://www.googleapis.com/auth/gmail.modify')
    service_account_credentials = service_account_credentials.create_delegated(user_to_be_added)

    service = discovery.build('gmail', 'v1', credentials=service_account_credentials)

    response = service.users().settings().delegates().create().execute(userId=delegated_mailbox)


if __name__ == '__main__':
    main('some_account_to_be_added@gmail.com', 'delegated_mailbox@gmail.com')

我与此 API 的交互完全错误吗?如果是这样,其他人是如何做到这一点的?

感谢您的宝贵时间。 约旦

【问题讨论】:

  • 如果代码不正确,请不要回答。尝试编辑您的原始帖子并删除新答案。您遇到什么错误?
  • 嘿,杰斯卡内拉斯。感谢您对 SA 的提示。我解决了下面的问题!

标签: python-3.x gmail-api google-workspace


【解决方案1】:

工作解决方案:

from googleapiclient import discovery
from google.oauth2 import service_account


def _create_client(subject):
    credentials = service_account.Credentials
    credentials = credentials.from_service_account_file('credentials/service_account.json',
        scopes=['https://www.googleapis.com/auth/gmail.settings.sharing',
                'https://www.googleapis.com/auth/gmail.settings.basic'],
        subject=subject)
    service = discovery.build('gmail', 'v1', credentials=credentials)
    return service


def add_delegate_to_email(user_to_be_added, delegated_mailbox):
    service = _create_client(user_to_be_added)

    body = {
        "delegateEmail": delegated_mailbox,
        "verificationStatus": "accepted"
    }
    try:

        response = service.users().settings().delegates().create(userId='me', body=body).execute()
        print(response)

    except Exception as e:
        print('Exception: {}'.format(e))

主要问题:从 oauth2client.service_account 导入 ServiceAccountCredentials 已被弃用,因为 Google 获得了 google-auth 的所有权。

【讨论】:

    猜你喜欢
    • 2020-09-23
    • 1970-01-01
    • 2016-01-04
    • 2020-10-08
    • 1970-01-01
    • 2020-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多